<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../includes/db_config.php';

try {
    session_start();
    
    if (!isset($_SESSION['staff_id'])) {
        throw new Exception('Delivery staff not logged in');
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        throw new Exception('Invalid JSON data');
    }
    
    $order_id = isset($input['order_id']) ? (int)$input['order_id'] : 0;
    if (!$order_id) {
        throw new Exception('Order ID is required');
    }
    
    $db = getDBConnection();
    
    $checkQuery = "SELECT id, user_id, status FROM orders WHERE id = ?";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->execute([$order_id]);
    $order = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        throw new Exception('Order not found');
    }
    
    if ($order['status'] !== 'pending') {
        throw new Exception('Order has already been picked up');
    }
    
    $updateQuery = "
        UPDATE orders 
        SET picked_up_at = NOW(), 
            delivery_staff_id = ?,
            status = 'processing',
            processing_started_at = NOW(),
            updated_at = NOW()
        WHERE id = ?
    ";
    $updateStmt = $db->prepare($updateQuery);
    $result = $updateStmt->execute([$_SESSION['staff_id'], $order_id]);
    
    if (!$result) {
        throw new Exception('Failed to update order');
    }
    
    $notificationTitle = 'Order Picked Up';
    $notificationMessage = "Your order #$order_id has been picked up by our delivery staff and processing has started. We will notify you when it's ready for delivery.";
    
    $notifStmt = $db->prepare("
        INSERT INTO notifications (title, message, type, user_id, created_at) 
        VALUES (?, ?, 'info', ?, NOW())
    ");
    $notifStmt->execute([$notificationTitle, $notificationMessage, $order['user_id']]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Order picked up successfully and customer has been notified',
        'picked_up_at' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
