<?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;

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

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("SELECT user_id FROM orders WHERE id = ? AND status = 'ready'");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        echo json_encode(['success' => false, 'message' => 'Order not found']);
        exit;
    }
    
    $code = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
    
    $stmt = $pdo->prepare("DELETE FROM delivery_codes WHERE order_id = ?");
    $stmt->execute([$order_id]);
    
    $stmt = $pdo->prepare("INSERT INTO delivery_codes (order_id, code) VALUES (?, ?)");
    $stmt->execute([$order_id, $code]);
    
    $title = 'Delivery Code';
    $message = "Your delivery code for order #$order_id is: $code. Share this code with the delivery person.";
    $stmt = $pdo->prepare("INSERT INTO notifications (title, message, type, user_id, created_at) VALUES (?, ?, 'info', ?, NOW())");
    $stmt->execute([$title, $message, $order['user_id']]);
    
    echo json_encode(['success' => true, 'code' => $code]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
