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

// Check if user has access to POS
if (!isset($_SESSION['role_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

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

// Get the request data
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

if ($action === 'restore_to_kds') {
    $order_id = intval($input['order_id'] ?? 0);
    $restore_status = $input['restore_status'] ?? 'ready'; // 'ready' or 'preparing'
    
    if ($order_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
        exit;
    }
    
    // Validate restore status
    if (!in_array($restore_status, ['ready', 'preparing'])) {
        $restore_status = 'ready';
    }
    
    try {
        // Start transaction
        $conn->begin_transaction();
        
        // Check if order exists and is currently served/completed
        $check_query = "SELECT id, order_status FROM kds_orders WHERE id = ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param("i", $order_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows === 0) {
            $conn->rollback();
            echo json_encode(['success' => false, 'message' => 'Order not found']);
            exit;
        }
        
        $order = $check_result->fetch_assoc();
        
        // Only allow restoring if order is currently served or completed
        if (!in_array($order['order_status'], ['served', 'completed'])) {
            $conn->rollback();
            echo json_encode(['success' => false, 'message' => 'Order is not in a completed state']);
            exit;
        }
        
        // Update the order status
        $update_order_query = "UPDATE kds_orders SET order_status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $update_order_stmt = $conn->prepare($update_order_query);
        $update_order_stmt->bind_param("si", $restore_status, $order_id);
        $update_order_stmt->execute();
        
        // Update all order items to the appropriate status
        $item_status = ($restore_status === 'ready') ? 'ready' : 'preparing';
        $update_items_query = "UPDATE kds_order_items SET item_status = ? WHERE kds_order_id = ?";
        $update_items_stmt = $conn->prepare($update_items_query);
        $update_items_stmt->bind_param("si", $item_status, $order_id);
        $update_items_stmt->execute();
        
        // Log the restoration activity
        // Check if details column exists, otherwise use description column
        $check_details_column = "SHOW COLUMNS FROM kds_activity_log LIKE 'details'";
        $check_result = $conn->query($check_details_column);
        
        if ($check_result->num_rows > 0) {
            // Details column exists - use it
            $log_query = "INSERT INTO kds_activity_log (kds_order_id, action, details, user_id, created_at) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)";
            $log_stmt = $conn->prepare($log_query);
            $log_stmt->bind_param("issi", $order_id, $action, $log_details, $_SESSION['user_id']);
        } else {
            // Details column doesn't exist - use description column
            $log_query = "INSERT INTO kds_activity_log (kds_order_id, action, description, user_id, created_at) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)";
            $log_stmt = $conn->prepare($log_query);
            $log_stmt->bind_param("issi", $order_id, $action, $log_details, $_SESSION['user_id']);
        }
        
        $log_details = "Order restored to KDS with status: " . $restore_status;
        $log_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Order successfully restored to KDS',
            'order_status' => $restore_status
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
