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

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

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']);
    exit;
}

$order_id = $_POST['order_id'] ?? null;
$code = $_POST['code'] ?? null;

if (!$order_id || !$code) {
    echo json_encode(['success' => false, 'message' => 'Order ID and code required']);
    exit;
}

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("SELECT dc.*, o.user_id FROM delivery_codes dc 
                          JOIN orders o ON dc.order_id = o.id 
                          WHERE dc.order_id = ? AND dc.used = 0");
    $stmt->execute([$order_id]);
    $delivery_code = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$delivery_code) {
        echo json_encode(['success' => false, 'message' => 'No code found']);
        exit;
    }
    
    if ($delivery_code['code'] !== $code) {
        echo json_encode(['success' => false, 'message' => 'Wrong code']);
        exit;
    }
    
    $stmt = $pdo->prepare("UPDATE orders SET status = 'delivered', delivery_staff_id = ?, delivered_at = NOW() WHERE id = ?");
    $stmt->execute([$_SESSION['staff_id'], $order_id]);
    
    $stmt = $pdo->prepare("UPDATE delivery_staff SET total_deliveries = total_deliveries + 1 WHERE id = ?");
    $stmt->execute([$_SESSION['staff_id']]);
    
    $stmt = $pdo->prepare("UPDATE delivery_codes SET used = 1 WHERE order_id = ?");
    $stmt->execute([$order_id]);
    
    $title = 'Order Delivered!';
    $message = "Your order #$order_id has been delivered. Thank you!";
    $stmt = $pdo->prepare("INSERT INTO notifications (title, message, type, user_id, created_at) VALUES (?, ?, 'success', ?, NOW())");
    $stmt->execute([$title, $message, $delivery_code['user_id']]);
    
    echo json_encode(['success' => true]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
