<?php
/**
 * API: تسجيل عميل جديد - Auto Tester
 * متوافق مع الأعمدة المضافة حديثاً
 */

// منع أي رسائل تحذيرية من تخريب رد الـ JSON
error_reporting(0);
ini_set('display_errors', 0);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

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

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'بيانات الطلب غير مكتملة'], JSON_UNESCAPED_UNICODE);
    exit();
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // توليد رقم الطلب
    $requestNumber = 'CLT-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    $fullName = trim($input['fullName']);

    // معالجة الملفات (الرخصة والصور الإضافية)
    $licensePath = !empty($input['carLicensePhoto']) ? saveBase64File($input['carLicensePhoto'], 'license') : null;
    
    $additionalPhotosJson = null;
    if (!empty($input['additionalPhotos']) && is_array($input['additionalPhotos'])) {
        $paths = [];
        foreach ($input['additionalPhotos'] as $index => $base64) {
            $path = saveBase64File($base64, 'car_extra_' . ($index + 1));
            if ($path) $paths[] = $path;
        }
        $additionalPhotosJson = json_encode($paths, JSON_UNESCAPED_UNICODE);
    }

    // الإدراج في قاعدة البيانات (مطابق للأعمدة التي أضفتها بالـ ALTER TABLE)
    $sql = "INSERT INTO `clients_requests` (
        `request_number`, `full_name`, `email`, `phone`, `governorate`, 
        `car_brand`, `car_model`, `manufacture_year`, `service_type`, 
        `preferred_branch`, `preferred_date`, `license_file`, `additional_photos`, `status`
    ) VALUES (
        :req_num, :name, :email, :phone, :gov, 
        :brand, :model, :year, :service, 
        :branch, :date, :lic_file, :extra_files, 'pending'
    )";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':req_num'    => $requestNumber,
        ':name'       => $fullName,
        ':email'      => $input['email'] ?? null,
        ':phone'      => $input['phone'],
        ':gov'        => $input['governorate'],
        ':brand'      => $input['carBrand'],
        ':model'      => $input['carModel'],
        ':year'       => $input['manufactureYear'],
        ':service'    => $input['serviceType'],
        ':branch'     => $input['preferredBranch'],
        ':date'       => $input['preferredDate'],
        ':lic_file'   => $licensePath,
        ':extra_files'=> $additionalPhotosJson
    ]);

    echo json_encode([
        'success' => true,
        'message' => 'تم استلام طلب الفحص بنجاح',
        'data' => [
            'full_name' => $fullName,
            'request_number' => $requestNumber
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في المعالجة: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}

// دالة حفظ الصور
function saveBase64File($base64Data, $prefix) {
    if (empty($base64Data) || !strpos($base64Data, ',')) return null;
    try {
        $parts = explode(',', $base64Data);
        $fileData = base64_decode($parts[1]);
        $ext = (strpos($parts[0], 'pdf') !== false) ? 'pdf' : 'jpg';
        $filename = $prefix . '_' . time() . '_' . rand(100, 999) . '.' . $ext;
        $uploadDir = __DIR__ . '/../../../uploads/clients/'; 
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
        file_put_contents($uploadDir . $filename, $fileData);
        return 'uploads/clients/' . $filename;
    } catch (Exception $e) { return null; }
}