<?php
class ResTable
{
  public $id;
  public $name;       
  public $capacity;   
  public $status;    

  public function __construct($_id, $_name, $_capacity, $_status)
  {
    $this->id = $_id;
    $this->name = $_name;
    $this->capacity = $_capacity;
    $this->status = $_status;
  }

  // Create new table
  public function create()
  {
    global $db;
    $sql = "INSERT INTO res_tables (name, capacity, status_id) 
            VALUES ('{$this->name}', '{$this->capacity}', '{$this->status}')";
    if ($db->query($sql)) {
      return "Table added successfully.";
    } else {
      return "Query failed: " . $db->error;
    }
  }

  // Read all tables
  public static function readAll()
  {
    global $db;
    $sql = "SELECT t.*, ts.availability as status FROM res_tables t, table_status ts where t.table_status_id = ts.id";
    $res = $db->query($sql);
    if ($res) {
      return $res->fetch_all(MYSQLI_ASSOC);
    } else {
      return "Query failed: " . $db->error;
    }
  }

  // Read table by ID
  public static function readById($id)
  {
    global $db;
    $id = (int)$id;
    $sql = "SELECT * FROM res_tables WHERE id = $id";
    $res = $db->query($sql);
    if ($res) {
      return $res->fetch_assoc();
    } else {
      return "Query failed: " . $db->error;
    }
  }

  // Update table
  public function update($id)
  {
    global $db;
    $sql = "UPDATE res_tables 
            SET name='{$this->name}', 
                capacity='{$this->capacity}', 
                table_status_id='{$this->status}' 
            WHERE id = $id";
    if ($db->query($sql)) {
      if ($db->affected_rows > 0) {
        return "Update successful.";
      } else {
        return "No changes made or record not found.";
      }
    } else {
      return "Update failed: " . $db->error;
    }
  }

  // Delete table
  public static function delete($id)
  {
    global $db;
    $sql = "DELETE FROM res_tables WHERE id = $id";
    if ($db->query($sql)) {
      if ($db->affected_rows > 0) {
        return "Delete successful.";
      } else {
        return "No record found with ID $id.";
      }
    } else {
      return "Delete failed: " . $db->error;
    }
  }

  
}
?>
