<?php
require_once __DIR__ . '/../../core/bootstrap.php';
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

uploadLog("🚀 [ride/card-image-driver/add.php] Card image upload started.");

try {
    $con = Database::get('main');
} catch (Exception $e) {
    uploadLog("❌ DB Connection failed: " . $e->getMessage(), 'ERROR');
    http_response_code(500);
    echo json_encode(['status' => 'Database connection failed.']);
    exit;
}

if (isset($_FILES['image'])) {
    uploadLog("$_FILES['image'] metadata", 'INFO', [
        'name' => $_FILES['image']['name'] ?? 'unknown',
        'type' => $_FILES['image']['type'] ?? 'unknown',
        'size' => $_FILES['image']['size'] ?? 0,
        'upload_error_code' => $_FILES['image']['error'] ?? UPLOAD_ERR_OK
    ]);
} else {
    uploadLog("No 'image' file was sent in request.", 'WARNING');
}

if (!isset($_FILES['image']) || $_FILES['image']['error'] != UPLOAD_ERR_OK) {
    $err = $_FILES['image']['error'] ?? 'missing_file';
    uploadLog("❌ File upload validation failed. Code: $err", 'ERROR');
    echo json_encode(['status' => 'The image file was not uploaded successfully.']);
    exit;
}

$image_file = $_FILES['image'];
$driverID = filterRequest("driver_id");

if (empty($driverID)) {
    uploadLog("❌ Missing driver_id parameter.", 'ERROR');
    echo json_encode(['status' => 'Missing driver ID.']);
    exit;
}

// التحقق من نوع الملف (MIME Type) للحماية من رفع سكربتات خبيثة
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $image_file['tmp_name']);
finfo_close($finfo);

$allowed_mime_types = ['image/jpeg', 'image/png', 'image/jpg'];
if (!in_array($mime_type, $allowed_mime_types)) {
    echo json_encode(['status' => 'The image file is not a valid image file.']);
    exit;
}

$image_name = $image_file['name'];
$image_extension = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
$allowed_extensions = ['jpg', 'jpeg', 'png'];

if (!in_array($image_extension, $allowed_extensions)) {
    echo json_encode(['status' => 'Invalid file extension.']);
    exit;
}

$new_filename = $driverID . '.' . $image_extension;
$target_dir = __DIR__ . "/../../card_image/";

if (!is_dir($target_dir)) {
    mkdir($target_dir, 0755, true);
}

$target_file = $target_dir . $new_filename;
if (!move_uploaded_file($image_file['tmp_name'], $target_file)) {
    echo json_encode(['status' => 'Failed to move uploaded file.']);
    exit;
}

$host = $_SERVER['HTTP_HOST'] ?? 'ride.mobile-app.store';
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$linlImage = "$protocol://$host/siro/card_image/" . $new_filename;

try {
    // استخدام Prepared Statements للحماية من الحقن (SQL Injection)
    $stmt = $con->prepare("SELECT id FROM card_images WHERE driver_id = :driver_id");
    $stmt->execute([':driver_id' => $driverID]);
    
    if ($stmt->rowCount() > 0) {
        $uploadDate = date("Y-m-d H:i:s");
        $updateStmt = $con->prepare("UPDATE card_images SET upload_date = :upload_date WHERE driver_id = :driver_id");
        $updateStmt->execute([
            ':upload_date' => $uploadDate,
            ':driver_id' => $driverID
        ]);
        
        uploadLog("✅ Card image updated successfully for driver_id: $driverID, URL: $linlImage");
        echo json_encode(['status' => 'Record updated successfully']);
    } else {
        $insertStmt = $con->prepare("INSERT INTO card_images (id, driver_id, image_name, link) VALUES (SHA2(UUID(), 256), :driver_id, :image_name, :link)");
        $insertStmt->execute([
            ':driver_id' => $driverID,
            ':image_name' => $new_filename,
            ':link' => $linlImage
        ]);
        
        uploadLog("✅ Card image inserted successfully for driver_id: $driverID, URL: $linlImage");
        echo json_encode(['status' => 'Record inserted successfully']);
    }
} catch (PDOException $e) {
    uploadLog("❌ Database error: " . $e->getMessage(), 'ERROR');
    error_log("Database Error in card-image-driver/add.php: " . $e->getMessage());
    echo json_encode(['status' => 'Database operation failed.']);
}
?>