<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

require_once "config.php";

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode([
        "status" => false,
        "message" => "Method not allowed"
    ]);
    exit;
}

/**
 * Sanitize helper
 */
function clean($value) {
    return htmlspecialchars(trim($value));
}

/**
 * Validate required fields
 */
$required = [
    "first_name",
    "last_name",
    "date_of_birth",
    "gender",
    "phone_number",
    "address",
    "drivers_license_number",
    "nin"
];

foreach ($required as $field) {
    if (empty($_POST[$field])) {
        http_response_code(400);
        echo json_encode([
            "status" => false,
            "message" => "Missing required field: $field"
        ]);
        exit;
    }
}

/**
 * Image validation
 */
if (!isset($_FILES["photo"]) || $_FILES["photo"]["error"] !== 0) {
    http_response_code(400);
    echo json_encode([
        "status" => false,
        "message" => "Photo is required"
    ]);
    exit;
}

$allowedTypes = ["image/jpeg", "image/png", "image/jpg"];
$maxSize = 2 * 1024 * 1024; // 2MB

$photo = $_FILES["photo"];

if (!in_array($photo["type"], $allowedTypes)) {
    http_response_code(400);
    echo json_encode([
        "status" => false,
        "message" => "Invalid image type"
    ]);
    exit;
}

if ($photo["size"] > $maxSize) {
    http_response_code(400);
    echo json_encode([
        "status" => false,
        "message" => "Image too large (max 2MB)"
    ]);
    exit;
}

/**
 * Create upload directory if not exists
 */
$uploadDir = __DIR__ . "/images/";

if (!is_dir($uploadDir)) {
    http_response_code(500);
    echo json_encode([
        "status" => false,
        "message" => "Upload directory not found"
    ]);
    exit;
}

$extension = strtolower(pathinfo($photo["name"], PATHINFO_EXTENSION));
$allowedExt = ["jpg", "jpeg", "png"];

if (!in_array($extension, $allowedExt)) {
    http_response_code(400);
    echo json_encode([
        "status" => false,
        "message" => "Invalid image type"
    ]);
    exit;
}

$fileName = uniqid("driver_", true) . "." . $extension;
$filePath = $uploadDir . $fileName;

if (!move_uploaded_file($photo["tmp_name"], $filePath)) {
    http_response_code(500);
    echo json_encode([
        "status" => false,
        "message" => "Failed to upload photo"
    ]);
    exit;
}

/* Store THIS in database */
$photoPathForDB = "images/" . $fileName;


/**
 * Prepare data
 */
$data = [
    "first_name" => clean($_POST["first_name"]),
    "last_name"  => clean($_POST["last_name"]),
    "date_of_birth" => $_POST["date_of_birth"],
    "gender" => clean($_POST["gender"]),
    "phone_number" => clean($_POST["phone_number"]),
    "address" => clean($_POST["address"]),
    "drivers_license_number" => clean($_POST["drivers_license_number"]),
    "nin" => clean($_POST["nin"]),
    "photo_path" => "images/" . $fileName
];

/**
 * Insert into database (PDO prepared statement)
 */
try {
    $stmt = $pdo->prepare("
        INSERT INTO drivers 
        (first_name, last_name, date_of_birth, gender, phone_number, address, drivers_license_number, nin, photo_path)
        VALUES
        (:first_name, :last_name, :date_of_birth, :gender, :phone_number, :address, :drivers_license_number, :nin, :photo_path)
    ");

    $stmt->execute($data);

    echo json_encode([
        "status" => true,
        "message" => "Driver registration submitted successfully"
    ]);

} catch (PDOException $e) {

    if ($e->getCode() == 23000) {
        http_response_code(409);
        echo json_encode([
            "status" => false,
            "message" => "Driver already exists (NIN or License Number)"
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            "status" => false,
            "message" => "Something went wrong"
        ]);
    }
}
