<?php

class ResOrderDetails {
    public $id;
    public $order_id;
    public $menu_id;
    public $quantity;
    public $price;

    public function __construct($_id, $_order_id, $_menu_id, $_quantity, $_price) {
        $this->id = $_id;
        $this->order_id = $_order_id;
        $this->menu_id = $_menu_id;
        $this->quantity = $_quantity;
        $this->price = $_price;
    }

    public function create() {
        global $db;
        $sql = "INSERT INTO res_order_details (id,order_id,menu_id,quantity,price, sub_total) VALUES ('{$this->id}', '{$this->order_id}', '{$this->menu_id}', '{$this->quantity}', '{$this->price}',{$this->quantity}*{$this->price} )";
        if ($db->query($sql)) {
          return $db->insert_id;
        } else {
          return "Query failed: " . $db->error;
        }
    }

    public static function readAll() {
        global $db;
        $sql = "SELECT * FROM res_order_details";
        $res = $db->query($sql);
        if ($res) {
          return $res->fetch_all(MYSQLI_ASSOC);
        } else {
          return "Query failed: " . $db->error;
        }
    }

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

    public function update($id) {
        global $db;
        $sql = "UPDATE res_order_details SET id='{$this->id}', order_id='{$this->order_id}', menu_id='{$this->menu_id}', quantity='{$this->quantity}', price='{$this->price}' 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;
        }
    }

    public static function delete($id) {
        global $db;
        $sql = "DELETE FROM res_order_details 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;
        }
    }
}
