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

// Get driver API key from Authorization header
$headers = getallheaders();
$apiKey = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

if (!$apiKey) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

try {
    // Verify driver
    $stmt = $pdo->prepare("SELECT d.* FROM drivers d WHERE d.api_key = ? AND d.status = 'active'");
    $stmt->execute([$apiKey]);
    $driver = $stmt->fetch();

    if (!$driver) {
        echo json_encode(['success' => false, 'error' => 'Invalid API key']);
        exit;
    }

    // Get route_id from request
    $data = json_decode(file_get_contents('php://input'), true);
    if (!isset($data['route_id'])) {
        echo json_encode(['success' => false, 'error' => 'Missing route_id']);
        exit;
    }

    $routeId = $data['route_id'];

    // Verify route belongs to driver's bus
    $routeStmt = $pdo->prepare("
        SELECT r.* FROM routes r 
        WHERE r.id = ? AND r.bus_id = ? AND r.active = 1
    ");
    $routeStmt->execute([$routeId, $driver['bus_id']]);
    $route = $routeStmt->fetch();

    if (!$route) {
        echo json_encode(['success' => false, 'error' => 'Invalid route or route not assigned to your bus']);
        exit;
    }

    // Update driver's active route
    $updateStmt = $pdo->prepare("UPDATE drivers SET active_route_id = ? WHERE id = ?");
    $updateStmt->execute([$routeId, $driver['id']]);

    echo json_encode([
        'success' => true,
        'route_id' => $routeId,
        'route_name' => $route['route_name'],
        'shift' => $route['shift']
    ]);

} catch (PDOException $e) {
    error_log("Set Active Route Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Database error']);
}
?>
