<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';
require_once '../../vendor/autoload.php';

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

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

$auth = new Auth();
try {
    $auth->requireRole('admin');
} catch (Exception $e) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);

if (
    empty($data['sender_phone']) || 
    empty($data['pickup_location']) || 
    empty($data['delivery_location']) || 
    empty($data['package_description'])
) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields.']);
    exit;
}

try {
    $db = new Database();
    
    // 1. Find or Create Sender
    $phone = $data['sender_phone'];
    $senderName = !empty($data['sender_name']) ? $data['sender_name'] : 'Customer ' . substr($phone, -4);
    
    $stmt = $db->query("SELECT id FROM users WHERE phone = ?", [$phone]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $customerId = null;
    
    if ($user) {
        $customerId = $user['id'];
    } else {
        // Create new user with placeholder email
        $email = $phone . '@temp.mabanga.com'; 
        // Random default password
        $password = password_hash('12345678', PASSWORD_DEFAULT);
        
        $db->query(
            "INSERT INTO users (name, email, phone, password, role) VALUES (?, ?, ?, ?, 'customer')",
            [$senderName, $email, $phone, $password]
        );
        $customerId = $db->lastInsertId();
    }
    
    // 2. Generate Tracking ID
    $trackingId = 'MBX' . strtoupper(substr(md5(uniqid()), 0, 8));
    
    // 3. Create Delivery
    $instructions = "";
    if (!empty($data['receiver_name']) || !empty($data['receiver_phone'])) {
        $instructions .= "\nReceiver: " . ($data['receiver_name'] ?? '') . " " . ($data['receiver_phone'] ?? '');
    }
    
    // Combine package description and instructions since the deliveries table uses 'package_description'
    $packageDescription = $data['package_description'] . (trim($instructions) ? "\n" . trim($instructions) : "");

    $db->query("INSERT INTO deliveries (user_id, tracking_id, pickup_location, delivery_location, package_description, status, price) VALUES (?, ?, ?, ?, ?, 'pending', 0.00)", [
        $customerId, $trackingId, $data['pickup_location'], $data['delivery_location'], $packageDescription
    ]);
    
    // 4. Notify Riders
    $deliveryId = $db->lastInsertId();
    $riders = $auth->getUsersByRole('rider');
    foreach ($riders as $rider) {
        $notifMsg = "New delivery available from " . $data['pickup_location'];
        $db->query("INSERT INTO notifications (user_id, message, link) VALUES (?, ?, ?)", [$rider['id'], $notifMsg, '/rider_dashboard']);
    }

    // 5. Send Web Push Notifications
    $pushRiders = $db->query("SELECT subscription FROM push_subscriptions WHERE user_id IN (SELECT id FROM users WHERE role = 'rider')")->fetchAll(PDO::FETCH_ASSOC);
    
    if (!empty($pushRiders)) {
        $auth_config = [
            'VAPID' => [
                'subject' => 'mailto:admin@mabanga-express.com',
                'publicKey' => 'YOUR_PUBLIC_VAPID_KEY_HERE', // Replace with your real key
                'privateKey' => 'YOUR_PRIVATE_VAPID_KEY_HERE', // Replace with your real key
            ],
        ];

        $webPush = new WebPush($auth_config);
        $payload = json_encode([
            'title' => 'New Delivery Available!',
            'body' => "From: " . $data['pickup_location'] . "\nTo: " . $data['delivery_location'],
            'url' => '/rider_dashboard'
        ]);

        foreach ($pushRiders as $row) {
            $subData = json_decode($row['subscription'], true);
            $webPush->queueNotification(
                Subscription::create($subData),
                $payload
            );
        }
        
        $webPush->flush();
    }

    echo json_encode([
        'success' => true,
        'message' => 'Delivery created successfully.',
        'tracking_id' => $trackingId
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server Error: ' . $e->getMessage()]);
}
?>