<?php
session_start();
include 'db_connection.php'; // Replace with your actual database connection file

$userId = intval($_POST['user_id']);

$driver_name = htmlspecialchars($_POST['driver_name']);
$phone = htmlspecialchars($_POST['phone']);
$driver_email = htmlspecialchars($_POST['driver_email']);
$vehicle_number = htmlspecialchars($_POST['vehicle_number']);
$vehicle_type = htmlspecialchars($_POST['vehicle_type']);
$vehicle_model = htmlspecialchars($_POST['vehicle_model']);
$driver_address = htmlspecialchars($_POST['driver_address']);

// File upload handling
$uploads_dir = '../uploads/';
$profile_picture = $license_image = $nic_image_front = $nic_image_back = $vehicle_book_image = $vehicle_license_image = '';

function uploadFile($fileKey, $uploads_dir) {
    if (!empty($_FILES[$fileKey]['name'])) {
        $file_tmp = $_FILES[$fileKey]['tmp_name'];
        $file_ext = pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION);
        $unique_name = uniqid() . '.' . $file_ext;
        $destination =  $unique_name;
        if (move_uploaded_file($file_tmp, $destination)) {
            return $destination;
        }
    }
    return '';
}

$profile_picture = uploadFile('profile_picture', $uploads_dir);
$license_image = uploadFile('license_image', $uploads_dir);
$nic_image_front = uploadFile('nic_image_front', $uploads_dir);
$nic_image_back = uploadFile('nic_image_back', $uploads_dir);
$vehicle_book_image = uploadFile('vehicle_book_image', $uploads_dir);
$vehicle_license_image = uploadFile('vehicle_license_image', $uploads_dir);

// Update database with new profile information
$sql = "UPDATE registered_vehicles SET 
            driver_name = ?, 
            phone = ?, 
            driver_email = ?, 
            vehicle_number = ?, 
            vehicle_type = ?, 
            vehicle_model = ?, 
            driver_address = ?, 
            profile_picture = ?, 
            license_image = ?, 
            nic_image_front = ?, 
            nic_image_back = ?, 
            vehicle_book_image = ?, 
            vehicle_license_image = ? 
        WHERE id = ?";

if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param(
        'sssssssssssssi', 
        $driver_name, 
        $phone, 
        $driver_email, 
        $vehicle_number, 
        $vehicle_type, 
        $vehicle_model, 
        $driver_address, 
        $profile_picture, 
        $license_image, 
        $nic_image_front, 
        $nic_image_back, 
        $vehicle_book_image, 
        $vehicle_license_image, 
        $userId
    );

    if ($stmt->execute()) {
        $_SESSION['success'] = "Profile updated successfully.";
    } else {
        $_SESSION['error'] = "Error updating profile: " . $stmt->error;
    }
    
    $stmt->close();
} else {
    $_SESSION['error'] = "Error preparing statement: " . $conn->error;
}

$conn->close();
echo 'updated!';
exit();
?>
