<?php
ob_start();

include __DIR__ . '/../auth/guard.php';
 

include 'db.php';
require_once '../inc/SecureIdHandler.php';
require_once '../phpqrcode/qrlib.php';

// السماح فقط بـ POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die('طلب غير صالح');
}

// الاتصال بقاعدة البيانات
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    die('خطأ اتصال بقاعدة البيانات');
}

// ---------------------------
// استلام البيانات
// ---------------------------
$data = [
    'worker_name'        => $_POST['worker_name'] ?? '',
    'worker_job'         => $_POST['worker_job'] ?? '',
    'worker_id'          => $_POST['worker_id'] ?? '',
    'worker_nationality' => $_POST['worker_nationality'] ?? '',
    'provider_name'      => $_POST['provider_name'] ?? '',
    'provider_number'    => $_POST['provider_number'] ?? '',
    'receiver_name'      => $_POST['receiver_name'] ?? '',
    'receiver_number'    => $_POST['receiver_number'] ?? '',
    'contract_summary'   => $_POST['contract_summary'] ?? '',
    'permit_start'       => $_POST['permit_start'] ?? '',
    'permit_end'         => $_POST['permit_end'] ?? '',
    'work_location'      => $_POST['work_location'] ?? '',
];

// ---------------------------
// QR الأول (بيانات JSON)
// ---------------------------
$qr_code_path = null;

$qrData = json_encode([
    'worker_name' => $data['worker_name'],
    'worker_id'   => $data['worker_id'],
    'permit_end'  => $data['permit_end']
], JSON_UNESCAPED_UNICODE);

$qrFolder = 'uploads/qrcodes/';
if (!is_dir($qrFolder)) {
    mkdir($qrFolder, 0777, true);
}

$qrFile = $qrFolder . 'data_' . uniqid() . '.png';
QRcode::png($qrData, $qrFile, QR_ECLEVEL_L, 6);
$qr_code_path = $qrFile;

// ---------------------------
// إدخال العقد أولًا
// ---------------------------
$sql = "INSERT INTO contracts (
    worker_name, worker_job, worker_id, worker_nationality,
    provider_name, provider_number, receiver_name, receiver_number,
    contract_summary, permit_start, permit_end, work_location,
    qr_code_path, barcode_path
) VALUES (
    :worker_name, :worker_job, :worker_id, :worker_nationality,
    :provider_name, :provider_number, :receiver_name, :receiver_number,
    :contract_summary, :permit_start, :permit_end, :work_location,
    :qr_code_path, ''
)";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    'worker_name'        => $data['worker_name'],
    'worker_job'         => $data['worker_job'],
    'worker_id'          => $data['worker_id'],
    'worker_nationality' => $data['worker_nationality'],
    'provider_name'      => $data['provider_name'],
    'provider_number'    => $data['provider_number'],
    'receiver_name'      => $data['receiver_name'],
    'receiver_number'    => $data['receiver_number'],
    'contract_summary'   => $data['contract_summary'],
    'permit_start'       => $data['permit_start'],
    'permit_end'         => $data['permit_end'],
    'work_location'      => $data['work_location'],
    'qr_code_path'       => $qr_code_path
]);

// ---------------------------
// 🔐 تشفير ID الحقيقي
// ---------------------------
$contract_id = $pdo->lastInsertId();










// -----------------------------------------------------------
// 🔐 نسخة احتياطية للرقابة والمحاسبة (تنسيق مطور)
// -----------------------------------------------------------
$log_sql = "INSERT INTO contracts_log (
    original_driver_id, 
    driver_name, 
    id_number, 
    created_by_user, 
    service_path, 
    payment_status
) VALUES (
    :oid, 
    :wn, 
    :wi, 
    :user_id, 
    :path, 
    :pm
)";

$log_stmt = $pdo->prepare($log_sql);

// تنفيذ الإدخال باستخدام البيانات من مصفوفة $data المعرفة في ملفك
$log_stmt->execute([
    'oid'     => $contract_id,                    // المعرف الذي تم جلبه بـ lastInsertId
    'wn'      => $data['worker_name'],            // اسم العامل
    'wi'      => $data['worker_id'],              // رقم الهوية
    'user_id' => $_SESSION['user_id'] ?? 0,       // معرف المستخدم من الجلسة
    'path'    => "عقد: " . $data['worker_job'],    // المسمى الوظيفي كمسار للخدمة
    'pm'      => 1                                // الحالة 1 تعني بانتظار التسديد
]);















$encrypted_id = SecureIdHandler::encryptId($contract_id);

// ---------------------------
// QR الثاني (الرابط المشفر)
// ---------------------------
$base_url = "https://ajeer-hrs-giwa.com/agiar/index.php";
$link = $base_url . "?id=" . urlencode($encrypted_id);

$barcodeFolder = 'uploads/barcodes/';
if (!is_dir($barcodeFolder)) {
    mkdir($barcodeFolder, 0777, true);
}

$barcodeFile = $barcodeFolder . 'link_' . uniqid() . '.png';
QRcode::png($link, $barcodeFile, QR_ECLEVEL_L, 6);

// ---------------------------
// تحديث مسار الباركود
// ---------------------------
$update = $pdo->prepare("UPDATE contracts SET barcode_path = ? WHERE id = ?");
$update->execute([$barcodeFile, $contract_id]);

// ---------------------------
// نجاح
// ---------------------------
header("Location: list.php");
exit;

ob_end_flush();