<?php
// ============================================
// إعدادات الخطأ - مهم جداً لظهور الأخطاء
// ============================================
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

// ============================================
// دالة موحدة للإرسال
// ============================================
function sendJsonResponse($success, $message, $data = null) {
    $response = [
        'success' => $success,
        'message' => $message,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit();
}

// ============================================
// إعدادات قاعدة البيانات
// ============================================
$host = "localhost";
$db_name = "digitals_cyber-scan-system";
$username = "digitals_digitals";
$password = "bassam.bassam";

// محاولة الاتصال بقاعدة البيانات
try {
    $pdo = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    sendJsonResponse(false, 'Database connection failed: ' . $e->getMessage());
}

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

if (!$input) {
    sendJsonResponse(false, 'No data received. Please send JSON data.');
}

// التحقق من وجود البيانات الأساسية
$requiredFields = ['client_name', 'client_phone', 'car_brand', 'car_model', 'car_year'];
$missing = [];
foreach ($requiredFields as $field) {
    if (empty($input[$field])) {
        $missing[] = $field;
    }
}

if (!empty($missing)) {
    sendJsonResponse(false, 'Missing required fields: ' . implode(', ', $missing));
}

try {
    // إنشاء جدول الطلبات إذا لم يكن موجوداً
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS `inspection_requests` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `request_number` varchar(50) NOT NULL,
            `client_name` varchar(100) NOT NULL,
            `client_phone` varchar(20) NOT NULL,
            `client_email` varchar(100) DEFAULT NULL,
            `car_brand` varchar(50) NOT NULL,
            `car_model` varchar(50) NOT NULL,
            `car_year` int(4) NOT NULL,
            `car_color` varchar(30) DEFAULT NULL,
            `plate_number` varchar(50) DEFAULT NULL,
            `service_type` varchar(50) DEFAULT NULL,
            `service_name` varchar(100) DEFAULT NULL,
            `total_price` decimal(10,2) DEFAULT '0.00',
            `advance_paid` decimal(10,2) DEFAULT '0.00',
            `remaining_amount` decimal(10,2) DEFAULT '0.00',
            `appointment_date` date DEFAULT NULL,
            `appointment_time` time DEFAULT NULL,
            `address` text DEFAULT NULL,
            `latitude` decimal(10,8) DEFAULT NULL,
            `longitude` decimal(11,8) DEFAULT NULL,
            `payment_image` longtext DEFAULT NULL,
            `status` varchar(20) DEFAULT 'pending',
            `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `request_number` (`request_number`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
    
    // إنشاء رقم طلب
    $requestNumber = $input['request_number'] ?? ('REQ-' . date('Ymd') . '-' . rand(1000, 9999));
    
    // حساب المبلغ المتبقي
    $totalPrice = floatval($input['total_price'] ?? 0);
    $advancePaid = floatval($input['advance_paid'] ?? 0);
    $remainingAmount = $totalPrice - $advancePaid;
    
    // إدراج الطلب
    $stmt = $pdo->prepare("
        INSERT INTO inspection_requests (
            request_number, client_name, client_phone, client_email,
            car_brand, car_model, car_year, car_color, plate_number,
            service_type, service_name, total_price, advance_paid, remaining_amount,
            appointment_date, appointment_time, address, latitude, longitude,
            payment_image, status, created_at
        ) VALUES (
            ?, ?, ?, ?,
            ?, ?, ?, ?, ?,
            ?, ?, ?, ?, ?,
            ?, ?, ?, ?, ?,
            ?, 'pending', NOW()
        )
    ");
    
    $stmt->execute([
        $requestNumber,
        $input['client_name'],
        $input['client_phone'],
        $input['client_email'] ?? '',
        $input['car_brand'],
        $input['car_model'],
        intval($input['car_year']),
        $input['car_color'] ?? '',
        $input['plate_number'] ?? '',
        $input['service_type'] ?? '',
        $input['service_name'] ?? '',
        $totalPrice,
        $advancePaid,
        $remainingAmount,
        $input['appointment_date'] ?? null,
        $input['appointment_time'] ?? null,
        $input['address'] ?? '',
        $input['latitude'] ?? null,
        $input['longitude'] ?? null,
        $input['payment_image'] ?? null
    ]);
    
    $requestId = $pdo->lastInsertId();
    
    // إرسال الرد بنجاح
    sendJsonResponse(true, 'تم إرسال الطلب بنجاح', [
        'request_id' => $requestId,
        'request_number' => $requestNumber
    ]);
    
} catch(PDOException $e) {
    sendJsonResponse(false, 'Database error: ' . $e->getMessage());
} catch(Exception $e) {
    sendJsonResponse(false, 'Error: ' . $e->getMessage());
}
?>