<?php

namespace EasyRestaurantManager\Models;

class Reservation extends Model
{
    protected $model = 'erm_table_reservations';

    public static function getAvailableTables($date, $time)
    {
      
        $time_convert = date('H:i:s', strtotime($time));
      
        global $wpdb;
        return $wpdb->get_results(
            $wpdb->prepare(
                "SELECT table_id FROM {$wpdb->prefix}erm_table_reservations WHERE reservation_date = %s AND reservation_time = %s AND status != %s",
                $date, $time_convert, 'cancelled'
            ),

        );
      
    }


    public static function store($data)
    {
        global $wpdb;
        $wpdb->insert($wpdb->prefix . 'erm_table_reservations', $data);
        return $wpdb->insert_id;
    }

    public static function getReservation()
    {
        global $wpdb;
        $reservations = $wpdb->get_results(
            "
                SELECT r.*, t.table_number 
                FROM {$wpdb->prefix}erm_table_reservations r
                LEFT JOIN {$wpdb->prefix}erm_tables t 
                ON r.table_id = t.id
                ORDER BY r.id DESC"
        );
        return $reservations;
    }

    public static function UpdateReservation($id, $status)
    {
        global $wpdb;
    
        if (!isset($id) || !isset($status)) {
            return 'Missing ID or status';
        }
    
        $id = (int) $id;
    
        $updated = $wpdb->update(
            $wpdb->prefix . 'erm_table_reservations',
            [ 'status' => sanitize_text_field($status) ],
            [ 'id' => $id ],                             
            [ '%s' ],                                     
            [ '%d' ]                                      
        );
    
        if ($updated === false) {
            return 'Update failed';
        }
    
        return $updated; // number of rows affected
    }

    public static function deleteReservation($id)
    {
        global $wpdb;
        $wpdb->delete($wpdb->prefix . 'erm_table_reservations', ['id' => $id]);
        return $wpdb->rows_affected;
    }
    
}
