<?php

namespace EasyRestaurantManager\Models;

class Table extends Model
{
    protected $model = 'erm_tables';

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

    public static function updateTable($data)
    {
        global $wpdb;
        if (!isset($data['id'])) {
            return ('missing id');
        }
        $id = (int) $data['id']; 
        unset($data['id']); 

        $updated = $wpdb->update($wpdb->prefix . 'erm_tables',$data, ['id' => $id],null, ['%d']
        );

        if ($updated === false) {
            return ('update failed');
        }
        return $updated;
    }
    
    public static function getTable($date, $time){
        global $wpdb;
        // Convert 12-hour format with AM/PM to 24-hour format
        $convertedTime = (new \DateTime($time))->format('H:i:s');
        $res = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT t.*, 
                IFNULL(r.status, 'available') as reservation_status
                FROM {$wpdb->prefix}erm_tables t
                LEFT JOIN {$wpdb->prefix}erm_table_reservations r 
                ON t.id = r.table_id AND r.reservation_date = %s AND r.reservation_time = %s
                ORDER BY t.id DESC",
                $date, $convertedTime
            )
        );
        return $res;
    }

    public static function getAllTable() {
        global $wpdb;
        return $wpdb->get_results("SELECT * FROM {$wpdb->prefix}erm_tables  ORDER BY id DESC"); 
    }

    public static function deleteTable($id){
        global $wpdb;
        $res = $wpdb->delete($wpdb->prefix . 'erm_tables', ['id' => $id]);
        return $res;
    }
}
