<?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 and quantity tracking
        if ($status === 'served') {
            $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = ?, preparation_notes = ?, served_quantity = quantity WHERE id = ?");
            $stmt->bind_param("ssi", $status, $notes, $item_id);
        } else {
            $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 - mark as 'served' (completed)
        if ($has_items && $all_completed) {
            $stmt = $conn->prepare("UPDATE kds_orders SET order_status = 'served', served_at = NOW(), 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 and update served_quantity
            $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = 'ready', served_quantity = quantity 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 and update served_quantity
            $stmt = $conn->prepare("UPDATE kds_order_items SET item_status = 'served', served_quantity = quantity 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();
        
    } elseif ($input['action'] === 'update_station_items') {
        // Update items from specific station as served
        if (!isset($input['order_id']) || !isset($input['station_id']) || !isset($input['status'])) {
            throw new Exception('Missing order_id, station_id, or status parameter');
        }
        
        $order_id = intval($input['order_id']);
        $station_id = intval($input['station_id']);
        $status = $input['status'];
        
        // Validate status
        $valid_statuses = ['pending', 'preparing', 'ready', 'served'];
        if (!in_array($status, $valid_statuses)) {
            throw new Exception('Invalid status');
        }
        
        // Update items from the specific station to served
        $stmt = $conn->prepare("
            UPDATE kds_order_items koi
            JOIN kds_station_items ksi ON koi.item_id = ksi.item_id
            SET koi.item_status = ?, koi.served_at = NOW(), koi.served_quantity = koi.quantity
            WHERE koi.kds_order_id = ? 
            AND ksi.station_id = ? 
            AND ksi.is_active = 1
        ");
        $stmt->bind_param("sii", $status, $order_id, $station_id);
        $stmt->execute();
        $affected_rows = $stmt->affected_rows;
        $stmt->close();
        
        if ($affected_rows == 0) {
            throw new Exception('No items found for this station in the order');
        }
        
        // Check if all items in the entire order are now served
        $check_stmt = $conn->prepare("
            SELECT COUNT(*) as total_items,
                   SUM(CASE WHEN item_status = 'served' THEN 1 ELSE 0 END) as served_items
            FROM kds_order_items 
            WHERE kds_order_id = ?
        ");
        $check_stmt->bind_param("i", $order_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        $counts = $result->fetch_assoc();
        $check_stmt->close();
        
        // If all items are served, mark the entire order as served
        if ($counts['total_items'] > 0 && $counts['total_items'] == $counts['served_items']) {
            $order_stmt = $conn->prepare("UPDATE kds_orders SET order_status = 'served', served_at = NOW(), updated_at = NOW() WHERE id = ?");
            $order_stmt->bind_param("i", $order_id);
            $order_stmt->execute();
            $order_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 (?, 'station_items_updated', ?, NOW())
        // ");
        // $details = "Station $station_id items updated to: $status";
        // $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()]);
}
?>
