<?php
ob_start();
require 'config.php';
ob_clean();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? 'list';

// Ensure table exists
try {
    $pdo->query("SELECT 1 FROM customer_orders LIMIT 1");
} catch (Exception $e) {
    echo json_encode(['success' => true, 'orders' => [], 'new_count' => 0]);
    exit;
}

if ($action === 'list') {
    // Return orders from last 12 hours, all statuses except cancelled
    $stmt = $pdo->query("
        SELECT id, invoice, table_no, customer_name, customer_phone,
               order_type, cart, subtotal, service_charge, takeaway_fee,
               total, payment_method, status, created_at
        FROM customer_orders
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 12 HOUR)
          AND status != 'cancelled'
        ORDER BY
          FIELD(status,'new','processing','done') ASC,
          created_at DESC
        LIMIT 100
    ");
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Parse cart JSON
    foreach ($orders as &$o) {
        $o['cart'] = json_decode($o['cart'], true) ?? [];
        $o['items_count'] = array_sum(array_column($o['cart'], 'qty'));
    }
    unset($o);

    $new_count = (int)$pdo->query("SELECT COUNT(*) FROM customer_orders WHERE status='new'")->fetchColumn();

    echo json_encode(['success' => true, 'orders' => $orders, 'new_count' => $new_count]);

} elseif ($action === 'update_status') {
    $id     = (int)($_POST['id'] ?? 0);
    $status = $_POST['status'] ?? '';
    if (!in_array($status, ['new','processing','done','cancelled'])) {
        echo json_encode(['success' => false, 'message' => 'Status tidak valid']);
        exit;
    }
    $pdo->prepare("UPDATE customer_orders SET status=? WHERE id=?")->execute([$status, $id]);
    echo json_encode(['success' => true]);

} elseif ($action === 'mark_all_seen') {
    $pdo->query("UPDATE customer_orders SET is_notified=1 WHERE status='new' AND is_notified=0");
    echo json_encode(['success' => true]);

} else {
    echo json_encode(['success' => false, 'message' => 'Unknown action']);
}