
<?php
include __DIR__ . '/../auth/guard.php';
 
 
include 'db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $id = $_POST['id'];
        
        // جلب البيانات الحالية للعقد
        $select_stmt = $conn->prepare("SELECT qr_code_path, barcode_path FROM contracts WHERE id = ?");
        $select_stmt->execute([$id]);
        $current_contract = $select_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$current_contract) {
            throw new Exception('العقد غير موجود');
        }

        $qr_code_path = $current_contract['qr_code_path'];
        $barcode_path = $current_contract['barcode_path'];

        // معالجة صورة QR Code
        if (isset($_FILES['qr_code_image']) && $_FILES['qr_code_image']['error'] == 0) {
            // حذف الصورة القديمة إذا كانت موجودة
            if ($qr_code_path && file_exists($qr_code_path)) {
                unlink($qr_code_path);
            }
            
            $file_tmp = $_FILES['qr_code_image']['tmp_name'];
            $file_name = $_FILES['qr_code_image']['name'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            
            $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array($file_ext, $allowed_types)) {
                $new_filename = 'qr_' . time() . '_' . uniqid() . '.' . $file_ext;
                $upload_path = UPLOAD_DIR . $new_filename;
                
                if (move_uploaded_file($file_tmp, $upload_path)) {
                    $qr_code_path = $upload_path;
                } else {
                    throw new Exception('فشل في رفع صورة QR');
                }
            } else {
                throw new Exception('نوع ملف QR غير مسموح به');
            }
        }

        // معالجة صورة Barcode
        if (isset($_FILES['barcode_image']) && $_FILES['barcode_image']['error'] == 0) {
            // حذف الصورة القديمة إذا كانت موجودة
            if ($barcode_path && file_exists($barcode_path)) {
                unlink($barcode_path);
            }
            
            $file_tmp = $_FILES['barcode_image']['tmp_name'];
            $file_name = $_FILES['barcode_image']['name'];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            
            $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array($file_ext, $allowed_types)) {
                $new_filename = 'barcode_' . time() . '_' . uniqid() . '.' . $file_ext;
                $upload_path = UPLOAD_DIR . $new_filename;
                
                if (move_uploaded_file($file_tmp, $upload_path)) {
                    $barcode_path = $upload_path;
                } else {
                    throw new Exception('فشل في رفع صورة Barcode');
                }
            } else {
                throw new Exception('نوع ملف Barcode غير مسموح به');
            }
        }

        // تحديث البيانات في قاعدة البيانات
        $stmt = $conn->prepare("UPDATE contracts 
                              SET 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 = ?, updated_at = CURRENT_TIMESTAMP 
                              WHERE id = ?");

        $result = $stmt->execute([
            $_POST['worker_name'],
            $_POST['worker_job'],
            $_POST['worker_id'],
            $_POST['worker_nationality'],
            $_POST['provider_name'],
            $_POST['provider_number'],
            $_POST['receiver_name'],
            $_POST['receiver_number'],
            $_POST['contract_summary'],
            $_POST['permit_start'],
            $_POST['permit_end'],
            $_POST['work_location'],
            $qr_code_path,
            $barcode_path,
            $id
        ]);

        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Contract updated successfully', 'redirect' => 'list.php']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update contract']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>