<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
include '../db.php';

$response = ['success' => false, 'message' => 'Unknown error', 'data' => null];

try {
    // Retrieve GET data
    $driver_name = $_GET['driver_name'] ?? '';
    $phone = $_GET['phone'] ?? '';
    $password = $_GET['password'] ?? '';
    $email = $_GET['email'] ?? '';
    $driver_address = $_GET['driver_address'] ?? '';
    $vehicle_number = $_GET['vehicle_number'] ?? '';
    $vehicle_model = $_GET['vehicle_model'] ?? '';
    $vehicle_type = $_GET['vehicle_type'] ?? 'Review';
    $vehicle_current_lat = $_GET['vehicle_current_lat'] ?? '';
    $vehicle_current_lng = $_GET['vehicle_current_lng'] ?? '';

    // Check if phone or email already exists
    $check_sql = "SELECT * FROM registered_vehicles WHERE phone = ? OR driver_email = ?";
    $check_stmt = $conn->prepare($check_sql);
    if (!$check_stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    $check_stmt->bind_param('ss', $phone, $email);
    $check_stmt->execute();
    $result = $check_stmt->get_result();
    if ($result->num_rows > 0) {
        // Phone or email already exists
        $response['message'] = 'Phone number or email already registered.';
        echo json_encode($response);
        exit;
    }
    $check_stmt->close();

    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Insert the data into the registered_vehicles table
    $sql = "INSERT INTO registered_vehicles (driver_name, phone, password, driver_email, driver_address, vehicle_number, vehicle_type, vehicle_model, vehicle_current_lat, vehicle_current_lng, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    $stmt->bind_param('ssssssssss', $driver_name, $phone, $hashed_password, $email, $driver_address, $vehicle_number, $vehicle_type, $vehicle_model, $vehicle_current_lat, $vehicle_current_lng);

    if ($stmt->execute()) {
        $response = ['success' => true, 'message' => 'Registration successful', 'data' => $_GET];
    } else {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $stmt->close();
    $conn->close();

} catch (Exception $e) {
    error_log($e->getMessage());
    $response['message'] = 'Registration failed: ' . $e->getMessage();
}

echo json_encode($response);


?>
