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

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

if (!isset($data['phone']) || !isset($data['password'])) {
    echo json_encode(['success' => false, 'error' => 'Missing phone or password']);
    exit;
}

$phone = $data['phone'];
$password = $data['password'];

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

    if ($driver && password_verify($password, $driver['password'])) {
        // Generate new API key if not exists or rotate it
        $apiKey = bin2hex(random_bytes(32));
        
        $updateStmt = $pdo->prepare("UPDATE drivers SET api_key = ? WHERE id = ?");
        $updateStmt->execute([$apiKey, $driver['id']]);

        echo json_encode([
            'success' => true,
            'api_key' => $apiKey,
            'driver_name' => $driver['name'],
            'bus_id' => $driver['bus_id']
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid credentials or inactive account']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error']);
}
?>
