<?php
session_start();
require 'config.php';

header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

$method = $_SERVER['REQUEST_METHOD'];

// Handle order details request FIRST (before general GET)
if ($method === 'GET' && isset($_GET['action']) && $_GET['action'] === 'get_details') {
    // Get specific order details with items
    try {
        if (!isset($_GET['order_id'])) {
            echo json_encode([
                'success' => false,
                'message' => 'Order ID is required'
            ]);
            exit;
        }
        
        $order_id = (int)$_GET['order_id'];
        
        // Get order details
        $orderSql = "SELECT id, order_number, full_name, email, phone, address, payment_method, subtotal, tax, total, status, created_at 
                    FROM orders WHERE id = ?";
        
        $orderStmt = $conn->prepare($orderSql);
        if (!$orderStmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $orderStmt->bind_param("i", $order_id);
        if (!$orderStmt->execute()) {
            throw new Exception("Execute failed: " . $orderStmt->error);
        }
        $orderResult = $orderStmt->get_result();
        $order = $orderResult->fetch_assoc();
        $orderStmt->close();
        
        if (!$order) {
            echo json_encode([
                'success' => false,
                'message' => 'Order not found'
            ]);
            exit;
        }
        
        // Get order items with product images
        $itemsSql = "SELECT oi.id, oi.item_name, oi.quantity, oi.price, mi.image_path
                    FROM order_items oi
                    LEFT JOIN menu_items mi ON oi.item_name = mi.item_name COLLATE utf8mb4_general_ci
                    WHERE oi.order_id = ?
                    ORDER BY oi.id";
        
        $itemsStmt = $conn->prepare($itemsSql);
        if (!$itemsStmt) {
            throw new Exception("Prepare failed for items: " . $conn->error);
        }
        $itemsStmt->bind_param("i", $order_id);
        if (!$itemsStmt->execute()) {
            throw new Exception("Execute failed for items: " . $itemsStmt->error);
        }
        $itemsResult = $itemsStmt->get_result();
        $items = [];
        while ($item = $itemsResult->fetch_assoc()) {
            // Clean up image path - remove 'assets/uploads/' prefix if it exists
            if ($item['image_path']) {
                $item['image_path'] = str_replace('assets/uploads/', '', $item['image_path']);
            }
            $items[] = $item;
        }
        $itemsStmt->close();
        
        echo json_encode([
            'success' => true,
            'order' => $order,
            'items' => $items
        ]);
        exit;
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
        exit;
    }
}

// Handle new_count request BEFORE general GET (to avoid matching generic GET)
if ($method === 'GET' && isset($_GET['action']) && $_GET['action'] === 'new_count') {
    // Get count of pending orders
    try {
        $sql = "SELECT COUNT(*) as count FROM orders WHERE status = 'pending'";
        $result = $conn->query($sql);
        $row = $result->fetch_assoc();
        
        echo json_encode([
            'success' => true,
            'count' => (int)$row['count']
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
    exit;
}

// Handle general GET for all orders
if ($method === 'GET') {
    try {
        // Fetch all orders for admin
        $sql = "SELECT id, order_number, full_name, email, phone, address, payment_method, subtotal, tax, total, status, created_at 
                FROM orders ORDER BY created_at DESC";
        
        $result = $conn->query($sql);
        
        if ($result) {
            $orders = [];
            while ($row = $result->fetch_assoc()) {
                $orders[] = $row;
            }
            
            echo json_encode([
                'success' => true,
                'data' => $orders,
                'count' => count($orders)
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Database error: ' . $conn->error
            ]);
        }
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
}

$conn->close();
?>
