<?php


class ResOnlineOrders
{
    public $id;
    public $name;
    public $order_id;
    public $phone_no;
    public $total_amount;
    public $shipping_address;
    public $order_status_id;

    public function __construct($_id, $_order_id, $_name,  $_phone_no, $_shipping_address, $_total_amount, $_order_status_id)
    {
        $this->id = $_id;
        $this->order_id = $_order_id;
        $this->name = $_name;
        $this->phone_no = $_phone_no;
        $this->shipping_address = $_shipping_address;
        $this->total_amount = $_total_amount;
        $this->order_status_id = $_order_status_id;
    }

   
    public function create()
    {
        global $db;

        $sql = "INSERT INTO res_online_orders 
            ( name, phone_no, shipping_address, total_amount, order_status_id) 
            VALUES (
                
                '{$this->name}', 
                '{$this->phone_no}', 
                '{$this->shipping_address}', 
                '{$this->total_amount}', 
                '{$this->order_status_id}'
            )";

        if ($db->query($sql)) {
            $this->id = $db->insert_id;
            return $this->id;
        } else {
            return "Query failed: " . $db->error;
        }
    }


    public function createOrder($items)
    {
        global $db;


        $sql = "INSERT INTO res_online_orders 
                (name, phone_no, shipping_address, total_amount, order_status_id) 
            VALUES (
                '{$this->name}', 
                '{$this->phone_no}', 
                '{$this->shipping_address}', 
                '{$this->total_amount}', 
                '{$this->order_status_id}'
            )";

        if ($db->query($sql)) {
            $order_id = $db->insert_id;



            foreach ($items as $item) {
                $order_details = new ResOnlineOrderDetails(
                    null,
                    $order_id,
                    $item->id,
                    $item->quantity,
                    $item->price
                );

                $res = $order_details->create();

                if (!is_int($res)) {
                    return "Error saving order details: " . $res;
                }
            }

            return "Order Placed Successfully";
        } else {
            return "Error saving order: " . $db->error;
        }
    }


   public function createOnlineOrder($items)
{
    global $db;

    try {
        $db->begin_transaction();

      
        $sql = "INSERT INTO res_online_orders (name, phone_no, shipping_address, total_amount, order_status_id) 
                VALUES ('{$this->name}', '{$this->phone_no}', '{$this->shipping_address}', '{$this->total_amount}', '{$this->order_status_id}')";

        if (!$db->query($sql)) {
            throw new Exception("Error saving order: " . $db->error);
        }

        $order_id = $db->insert_id;
        $this->id = $order_id; 

        foreach ($items as $item) {
           
            $product_id = is_array($item) ? $item['id'] : $item->id;
            $qty        = is_array($item) ? $item['quantity'] : $item->quantity;
            $price      = is_array($item) ? $item['price'] : $item->price;

            $order_details = new ResOnlineOrderDetails(
                null,
                $order_id,
                $product_id,
                $qty,
                $price
            );

            $res = $order_details->create();
            if (!is_int($res)) {
                throw new Exception("Error saving order details: " . $res);
            }
        }

        $db->commit();


    echo "
    <script>
    Swal.fire({
      icon: 'success',
      title: 'Order Placed!',
      text: 'Thank You For Dining With Us!',
      confirmButtonText: 'OK'
    });
    </script>
    ";
    } catch (Exception $e) {
        $db->rollback();
        return $e->getMessage();
    }
}


public static function readAll()
{
    global $db;
    $sql = "SELECT o.id, 
                   o.name, 
                   o.phone_no, 
                   o.shipping_address, 
                   o.total_amount, 
                   os.name AS order_status
            FROM res_online_orders o
            JOIN res_order_status os ON o.order_status_id = os.id
            ORDER BY o.id DESC";

    $res = $db->query($sql);
    return $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
}


public static function readById($id)
{
    global $db;
    $id = (int) $id;

    // Fetch main order info
    $orderSql = "SELECT o.id, 
                        o.name, 
                        o.phone_no, 
                        o.shipping_address, 
                        o.total_amount, 
                        os.name AS order_status
                 FROM res_online_orders o
                 JOIN res_order_status os ON o.order_status_id = os.id
                 WHERE o.id = $id";

    $orderRes = $db->query($orderSql);
    $order = $orderRes ? $orderRes->fetch_assoc() : null;

    // Fetch order items
   $itemsSql = "SELECT m.name AS menu_name, d.quantity, d.price, d.sub_total
             FROM res_online_order_details d
             JOIN res_menu m ON d.menu_id = m.id
             WHERE d.order_id = $id";


    $itemsRes = $db->query($itemsSql);
    $items = $itemsRes ? $itemsRes->fetch_all(MYSQLI_ASSOC) : [];

    return [
        "order" => $order,
        "items" => $items
    ];
}

public static function delete($id)
{
    global $db;
    $id = (int) $id;

    // First delete related order details
    $detailsSql = "DELETE FROM res_online_order_details WHERE order_id = $id";
    $db->query($detailsSql);

    // Then delete the main order
    $orderSql = "DELETE FROM res_online_orders WHERE id = $id";
    if ($db->query($orderSql)) {
        return $db->affected_rows > 0 
            ? "Delete successful." 
            : "No record found with ID $id.";
    } else {
        return "Delete failed: " . $db->error;
    }
}






}
