<?php
// المسار: /api/client/endpoints/submit_request.php

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

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

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    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);
    
    // تنظيف البيانات
    $fullName = trim(strip_tags($input['fullName']));
    $phone = trim(strip_tags($input['phone']));
    $email = trim(strip_tags($input['email']));
    $city = trim(strip_tags($input['city']));
    $address = isset($input['address']) ? trim(strip_tags($input['address'])) : '';
    $carBrand = trim(strip_tags($input['carBrand']));
    $carModel = trim(strip_tags($input['carModel']));
    $carYear = intval($input['carYear']);
    $carColor = isset($input['carColor']) ? trim(strip_tags($input['carColor'])) : '';
    $plateNumber = isset($input['plateNumber']) ? trim(strip_tags($input['plateNumber'])) : '';
    $serviceType = trim(strip_tags($input['serviceType']));
    $serviceName = trim(strip_tags($input['serviceName']));
    $servicePrice = floatval($input['servicePrice']);
    $advanceAmount = isset($input['advanceAmount']) ? floatval($input['advanceAmount']) : 0;
    $remainingAmount = isset($input['remainingAmount']) ? floatval($input['remainingAmount']) : ($servicePrice - $advanceAmount);
    $appointmentDate = isset($input['appointmentDate']) ? trim($input['appointmentDate']) : null;
    $appointmentTime = isset($input['appointmentTime']) ? trim($input['appointmentTime']) : null;
    $centerName = isset($input['center']) ? trim(strip_tags($input['center'])) : '';
    $requestNumber = isset($input['request_number']) ? trim($input['request_number']) : ('REQ-' . date('Ymd-His') . '-' . rand(100, 999));
    
    // إدراج الطلب في الجدول الجديد
    $sql = "INSERT INTO inspection_requests_new (
        request_number, full_name, phone, email, city, address,
        car_brand, car_model, car_year, car_color, plate_number,
        service_type, service_name, service_price, advance_amount, remaining_amount,
        appointment_date, appointment_time, center_name,
        status, payment_status, created_at
    ) VALUES (
        :request_number, :full_name, :phone, :email, :city, :address,
        :car_brand, :car_model, :car_year, :car_color, :plate_number,
        :service_type, :service_name, :service_price, :advance_amount, :remaining_amount,
        :appointment_date, :appointment_time, :center_name,
        'pending', 'partial', NOW()
    )";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':request_number' => $requestNumber,
        ':full_name' => $fullName,
        ':phone' => $phone,
        ':email' => $email,
        ':city' => $city,
        ':address' => $address,
        ':car_brand' => $carBrand,
        ':car_model' => $carModel,
        ':car_year' => $carYear,
        ':car_color' => $carColor,
        ':plate_number' => $plateNumber,
        ':service_type' => $serviceType,
        ':service_name' => $serviceName,
        ':service_price' => $servicePrice,
        ':advance_amount' => $advanceAmount,
        ':remaining_amount' => $remainingAmount,
        ':appointment_date' => $appointmentDate,
        ':appointment_time' => $appointmentTime,
        ':center_name' => $centerName
    ]);
    
    $requestId = $pdo->lastInsertId();
    
    // إضافة إشعار للمشرف
    $notifSql = "INSERT INTO admin_notifications_new (title, message, request_number, request_id, created_at) 
                 VALUES (:title, :message, :request_number, :request_id, NOW())";
    $notifStmt = $pdo->prepare($notifSql);
    $notifStmt->execute([
        ':title' => 'طلب فحص جديد',
        ':message' => 'طلب فحص جديد من ' . $fullName . ' - ' . $serviceName,
        ':request_number' => $requestNumber,
        ':request_id' => $requestId
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'تم استلام طلب الفحص بنجاح',
        'request_number' => $requestNumber,
        'request_id' => $requestId
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}