<?php
session_start();
header('Content-Type: application/json');
require_once '../includes/db_config.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
$staff_id = $_SESSION['staff_id'];

if ($order_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
    exit;
}

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("
        SELECT o.*, u.name as customer_name, u.email, u.phone
        FROM orders o
        LEFT JOIN users u ON o.user_id = u.id
        WHERE o.id = ?
    ");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        echo json_encode(['success' => false, 'message' => 'Order not found']);
        exit;
    }
    
    $stmt = $pdo->prepare("SELECT name, phone FROM delivery_staff WHERE id = ?");
    $stmt->execute([$staff_id]);
    $staff = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$staff) {
        echo json_encode(['success' => false, 'message' => 'Staff not found']);
        exit;
    }
    
    $notification_title = 'Delivery Staff Has Arrived!';
    $notification_message = "Your delivery person {$staff['name']} has arrived at your location for Order #{$order_id}. Contact: {$staff['phone']}";
    
    $stmt = $pdo->prepare("INSERT INTO notifications (title, message, type, user_id, created_at) VALUES (?, ?, 'info', ?, NOW())");
    $stmt->execute([$notification_title, $notification_message, $order['user_id']]);
    
    if ($order['status'] === 'processing') {
        $stmt = $pdo->prepare("UPDATE orders SET status = 'ready', delivery_staff_id = ? WHERE id = ?");
        $stmt->execute([$staff_id, $order_id]);
        
        $ready_title = 'Your Order is Ready for Delivery!';
        $ready_message = "Great news! Your order #" . $order_id . " is now ready and will be delivered soon.";
        $stmt = $pdo->prepare("INSERT INTO notifications (title, message, type, user_id, created_at) VALUES (?, ?, 'info', ?, NOW())");
        $stmt->execute([$ready_title, $ready_message, $order['user_id']]);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Customer has been notified of your arrival',
        'customer_name' => $order['customer_name'],
        'customer_phone' => $order['customer_phone']
    ]);
    
} catch (PDOException $e) {
    error_log("Notify customer arrival error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error occurred']);
}
?>
