<?php
// api/submit-request.php
header('Content-Type: application/json');
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';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في الاتصال بقاعدة البيانات']);
    exit;
}

// استقبال البيانات
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'لا توجد بيانات']);
    exit;
}

try {
    $pdo->beginTransaction();

    // التحقق من وجود العميل
    $stmt = $pdo->prepare("SELECT id FROM clients WHERE phone = ?");
    $stmt->execute([$data['phone']]);
    $client = $stmt->fetch();

    if (!$client) {
        // إنشاء عميل جديد
        $stmt = $pdo->prepare("INSERT INTO clients (full_name, phone, email, city, address) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['fullName'],
            $data['phone'],
            $data['email'] ?? '',
            $data['city'] ?? '',
            $data['address'] ?? ''
        ]);
        $client_id = $pdo->lastInsertId();
    } else {
        $client_id = $client['id'];
    }

    // إضافة السيارة
    $stmt = $pdo->prepare("INSERT INTO client_cars (client_id, brand, model, year, color, plate_number) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $client_id,
        $data['carBrand'],
        $data['carModel'],
        $data['carYear'],
        $data['carColor'] ?? '',
        $data['plateNumber'] ?? ''
    ]);
    $car_id = $pdo->lastInsertId();

    // تحديد نوع الفحص
    $type_map = [
        'comprehensive' => 1,
        'dyno' => 2,
        'brakes' => 3,
        'engine' => 4,
        'electrical' => 5,
        'pickup' => 6,
        'computer' => 7,
        'apps' => 8
    ];
    $type_id = $type_map[$data['serviceType']] ?? 1;

    // إنشاء رقم طلب
    $request_number = 'REQ-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

    // إضافة الطلب
    $stmt = $pdo->prepare("INSERT INTO inspection_requests (client_id, car_id, inspection_type_id, total_amount, status, request_number) VALUES (?, ?, ?, ?, 'pending', ?)");
    $stmt->execute([
        $client_id,
        $car_id,
        $type_id,
        $data['servicePrice'] ?? 850,
        $request_number
    ]);
    $request_id = $pdo->lastInsertId();

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => 'تم حفظ الطلب بنجاح',
        'request_number' => $request_number,
        'request_id' => $request_id
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode([
        'success' => false, 
        'message' => 'خطأ في حفظ البيانات: ' . $e->getMessage()
    ]);
}
?>