<?php
include '../db.php';

// KDS endpoints don't require full authentication but should be protected
// Check for a simple KDS access token or allow direct access for now
// In production, you might want to implement a proper KDS authentication system

// For now, allow direct access to KDS endpoints

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['action'])) {
    echo json_encode(['success' => false, 'message' => 'Missing action parameter']);
    exit;
}

try {
    // Begin transaction
    $conn->begin_transaction();
    
    if ($input['action'] === 'update_item_status') {
        // Update individual item status
        if (!isset($input['item_id']) || !isset($input['status'])) {
            throw new Exception('Missing item_id or status parameter');
        }
        
        $item_id = intval($input['item_id']);
        $status = $input['status'];
        $notes = $input['notes'] ?? '';
        
        // Validate status
        $valid_statuses = ['pending', 'preparing', 'ready', 'served'];
        if (!in_array($status, $valid_statuses)) {
            throw new Exception('Invalid status');
        }
        
        // Update item status
        $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = ?, preparation_notes = ? WHERE id = ?");
        $stmt->bind_param("ssi", $status, $notes, $item_id);
        $stmt->execute();
        $stmt->close();
        
        // Get the KDS order ID for this item
        $order_result = $conn->query("SELECT kds_order_id FROM kds_order_items WHERE id = $item_id")->fetch_assoc();
        $kds_order_id = $order_result['kds_order_id'];
        
        // Check if all items in the order are completed
        $items_result = $conn->query("SELECT item_status FROM kds_order_items WHERE kds_order_id = $kds_order_id");
        $all_completed = true;
        $has_items = false;
        
        while ($item = $items_result->fetch_assoc()) {
            $has_items = true;
            if ($item['item_status'] !== 'served') {
                $all_completed = false;
                break;
            }
        }
        
        // Update order status if all items are completed
        if ($has_items && $all_completed) {
            $stmt = $conn->prepare("UPDATE kds_orders SET order_status = 'served', updated_at = NOW() WHERE id = ?");
            $stmt->bind_param("i", $kds_order_id);
            $stmt->execute();
            $stmt->close();
        }
        
        // Log activity (temporarily commented out to avoid table structure issues)
        // $activity_stmt = $conn->prepare("
        //     INSERT INTO kds_activity_log (
        //         kds_order_id, action, details, created_at
        //     ) VALUES (?, 'item_status_updated', ?, NOW())
        // ");
        // $details = "Item #$item_id status updated to: $status";
        // $activity_stmt->bind_param("is", $kds_order_id, $details);
        // $activity_stmt->execute();
        // $activity_stmt->close();
        
    } elseif ($input['action'] === 'update_order_status') {
        // Update entire order status
        if (!isset($input['order_id']) || !isset($input['status'])) {
            throw new Exception('Missing order_id or status parameter');
        }
        
        $order_id = intval($input['order_id']);
        $status = $input['status'];
        
        // Validate status
        $valid_statuses = ['pending', 'preparing', 'ready', 'served'];
        if (!in_array($status, $valid_statuses)) {
            throw new Exception('Invalid status');
        }
        
        // Update order status
        $stmt = $conn->prepare("UPDATE kds_orders SET order_status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("si", $status, $order_id);
        $stmt->execute();
        $stmt->close();
        
        // Update all items in the order based on the new status
        if ($status === 'preparing') {
            // When starting order, mark all pending items as preparing
            $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = 'preparing' WHERE kds_order_id = ? AND item_status = 'pending'");
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $stmt->close();
        } elseif ($status === 'ready') {
            // When marking ready, mark all preparing items as ready
            $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = 'ready' WHERE kds_order_id = ? AND item_status = 'preparing'");
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $stmt->close();
        } elseif ($status === 'served') {
            // If order is served, mark all items as served
            $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = 'served' WHERE kds_order_id = ?");
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $stmt->close();
        }
        
        // Log activity (temporarily commented out to avoid table structure issues)
        // $activity_stmt = $conn->prepare("
        //     INSERT INTO kds_activity_log (
        //         kds_order_id, action, details, created_at
        //     ) VALUES (?, 'order_status_updated', ?, NOW())
        // ");
        // $details = "Order status updated to: $status";
        // $activity_stmt->bind_param("is", $order_id, $details);
        // $activity_stmt->execute();
        // $activity_stmt->close();
        
    } elseif ($input['action'] === 'update_priority') {
        // Update order priority
        if (!isset($input['order_id']) || !isset($input['priority'])) {
            throw new Exception('Missing order_id or priority parameter');
        }
        
        $order_id = intval($input['order_id']);
        $priority = $input['priority'];
        
        // Validate priority
        $valid_priorities = ['normal', 'urgent', 'rush'];
        if (!in_array($priority, $valid_priorities)) {
            throw new Exception('Invalid priority');
        }
        
        // Update order priority
        $stmt = $conn->prepare("UPDATE kds_orders SET priority = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("si", $priority, $order_id);
        $stmt->execute();
        $stmt->close();
        
        // Log activity (temporarily commented out to avoid table structure issues)
        // $activity_stmt = $conn->prepare("
        //     INSERT INTO kds_activity_log (
        //         kds_order_id, action, details, created_at
        //     ) VALUES (?, 'priority_updated', ?, NOW())
        // ");
        // $details = "Order priority updated to: $priority";
        // $activity_stmt->bind_param("is", $order_id, $details);
        // $activity_stmt->execute();
        // $activity_stmt->close();
        
    } else {
        throw new Exception('Invalid action');
    }
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode(['success' => true, 'message' => 'Update successful']);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
