<?php
session_start();
require_once '../includes/db_config.php';

if (!isset($_SESSION['staff_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['order_id']) || !isset($_POST['order_status'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing required data']);
    exit;
}

$order_id = intval($_POST['order_id']);
$new_status = $_POST['order_status'];

$valid_statuses = ['pending', 'processing', 'ready', 'delivered', 'cancelled'];
if (!in_array($new_status, $valid_statuses)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid status']);
    exit;
}

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Order not found']);
        exit;
    }
    
    $stmt = $pdo->prepare("UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$new_status, $order_id]);
    
    $staff_id = $_SESSION['staff_id'];
    $stmt = $pdo->prepare("
        INSERT INTO order_status_log (order_id, staff_id, old_status, new_status, changed_at) 
        VALUES (?, ?, ?, ?, NOW())
    ");
    
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS order_status_log (
            id INT AUTO_INCREMENT PRIMARY KEY,
            order_id INT NOT NULL,
            staff_id INT NULL,
            old_status VARCHAR(20) NOT NULL,
            new_status VARCHAR(20) NOT NULL,
            changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
            FOREIGN KEY (staff_id) REFERENCES delivery_staff(id) ON DELETE SET NULL
        )
    ");
    
    $stmt->execute([$order_id, $staff_id, $order['status'], $new_status]);
    
    if ($new_status === 'delivered') {
        $stmt = $pdo->prepare("
            UPDATE delivery_staff 
            SET total_deliveries = total_deliveries + 1 
            WHERE id = ?
        ");
        $stmt->execute([$staff_id]);
    }
    
    echo json_encode([
        'success' => true, 
        'message' => 'Order status updated successfully',
        'order_id' => $order_id,
        'new_status' => $new_status
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>
