<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    jsonResponse(false, 'Invalid request method', [], 405);
}

$auth = new Auth();
if (!$auth->check()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

$restaurantId = $auth->restaurantId();
if (!$restaurantId) {
    jsonResponse(false, 'No restaurant associated', [], 403);
}

$db = Database::getInstance();
$pdo = $db->getConnection();

$search = trim($_GET['search'] ?? '');

if (!empty($search)) {
    $searchParam = '%' . $search . '%';
    $stmt = $pdo->prepare(
        "SELECT o.id, o.restaurant_id, o.table_id, o.order_number, o.order_type,
                o.customer_name, o.customer_phone, o.order_notes, o.subtotal,
                o.discount, o.tax, o.service_charge, o.delivery_charge,
                o.grand_total, o.payment_method, o.payment_status, o.order_status,
                o.created_at, o.updated_at,
                t.table_number, t.table_name
         FROM orders o
         LEFT JOIN tables t ON o.table_id = t.id
         WHERE o.restaurant_id = ?
         AND o.payment_status IN ('pending', 'partial')
         AND o.order_status NOT IN ('cancelled', 'rejected')
         AND (o.order_number LIKE ? OR t.table_number LIKE ?)
         ORDER BY o.created_at DESC
         LIMIT 50"
    );
    $stmt->execute([$restaurantId, $searchParam, $searchParam]);
} else {
    $stmt = $pdo->prepare(
        "SELECT o.id, o.restaurant_id, o.table_id, o.order_number, o.order_type,
                o.customer_name, o.customer_phone, o.order_notes, o.subtotal,
                o.discount, o.tax, o.service_charge, o.delivery_charge,
                o.grand_total, o.payment_method, o.payment_status, o.order_status,
                o.created_at, o.updated_at,
                t.table_number, t.table_name
         FROM orders o
         LEFT JOIN tables t ON o.table_id = t.id
         WHERE o.restaurant_id = ?
         AND o.payment_status IN ('pending', 'partial')
         AND o.order_status NOT IN ('cancelled', 'rejected')
         ORDER BY o.created_at DESC
         LIMIT 50"
    );
    $stmt->execute([$restaurantId]);
}

$orders = $stmt->fetchAll();

foreach ($orders as &$order) {
    $itemStmt = $pdo->prepare(
        "SELECT id, item_name, variation_name, quantity, unit_price, variation_price,
                addons_total, item_total, item_notes
         FROM order_items WHERE order_id = ?"
    );
    $itemStmt->execute([$order['id']]);
    $order['items'] = $itemStmt->fetchAll();

    $paidStmt = $pdo->prepare(
        "SELECT COALESCE(SUM(amount), 0) AS total_paid FROM payments WHERE order_id = ? AND status = 'paid'"
    );
    $paidStmt->execute([$order['id']]);
    $paidResult = $paidStmt->fetch();
    $order['total_paid'] = (float) ($paidResult['total_paid'] ?? 0);
    $order['balance'] = (float) $order['grand_total'] - $order['total_paid'];
}
unset($order);

jsonResponse(true, 'Orders loaded', ['orders' => $orders]);
