<?php
/**
 * Prince VIP System - Contracts AJAX Handler
 * معالج AJAX للعقود
 */
require_once __DIR__ . '/../config/database.php';

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'غير مصرح']);
    exit;
}

$db = getDB();
$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    
    // ======= إنشاء عقد جديد =======
    case 'create':
        try {
            $clientType = $_POST['client_type'] ?? 'existing';
            $clientId = null;
            
            // معالجة العميل
            if ($clientType === 'new') {
                $clientName = clean($_POST['client_name'] ?? '');
                $clientIdNumber = clean($_POST['client_id_number'] ?? '');
                $clientPhone = clean($_POST['client_phone'] ?? '');
                
                if (empty($clientName) || empty($clientIdNumber) || empty($clientPhone)) {
                    echo json_encode(['success' => false, 'message' => 'يرجى إكمال بيانات العميل']);
                    exit;
                }
                
                // التحقق من عدم تكرار العميل
                $checkStmt = $db->prepare("SELECT id FROM clients WHERE id_number = ?");
                $checkStmt->execute([$clientIdNumber]);
                $existing = $checkStmt->fetch();
                
                if ($existing) {
                    $clientId = $existing['id'];
                } else {
                    $insertClient = $db->prepare("INSERT INTO clients (full_name, id_number, phone, created_by) VALUES (?, ?, ?, ?)");
                    $insertClient->execute([$clientName, $clientIdNumber, $clientPhone, $_SESSION['user_id']]);
                    $clientId = $db->lastInsertId();
                }
            } else {
                $clientId = (int)($_POST['client_id'] ?? 0);
                if (!$clientId) {
                    echo json_encode(['success' => false, 'message' => 'يرجى اختيار العميل']);
                    exit;
                }
            }
            
            // رفع المرفقات
            $attachments = [null, null, null];
            for ($i = 1; $i <= 3; $i++) {
                if (isset($_FILES["attachment$i"]) && $_FILES["attachment$i"]['size'] > 0) {
                    $result = uploadFile($_FILES["attachment$i"], 'contracts');
                    if (isset($result['success'])) {
                        $attachments[$i - 1] = $result['filename'];
                    }
                }
            }
            
            $contractNumber = clean($_POST['contract_number']);
            $status = clean($_POST['status'] ?? 'draft');
            
            $stmt = $db->prepare("INSERT INTO contracts 
                (contract_number, card_number, client_id, agent_id, plate_type, classification, car_number, 
                 license_type, car_type, car_color, production_year, usage_type, insurance_type, chassis_number,
                 start_date, end_date, notes, status, attachment1, attachment2, attachment3, policy_number,
                 package_id, price, payment_status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            $packageId = !empty($_POST['package_id']) ? (int)$_POST['package_id'] : null;
            $price = !empty($_POST['price']) ? (float)$_POST['price'] : null;
            
            $stmt->execute([
                $contractNumber,
                clean($_POST['card_number'] ?? ''),
                $clientId,
                $_SESSION['user_id'],
                clean($_POST['plate_type'] ?? ''),
                clean($_POST['classification'] ?? ''),
                clean($_POST['car_number'] ?? ''),
                clean($_POST['license_type'] ?? ''),
                clean($_POST['car_type'] ?? ''),
                clean($_POST['car_color'] ?? ''),
                $_POST['production_year'] ?? null,
                clean($_POST['usage_type'] ?? ''),
                clean($_POST['insurance_type'] ?? ''),
                clean($_POST['chassis_number'] ?? ''),
                $_POST['start_date'],
                $_POST['end_date'],
                clean($_POST['notes'] ?? ''),
                $status,
                $attachments[0],
                $attachments[1],
                $attachments[2],
                'POL-' . $contractNumber,
                $packageId,
                $price,
                'unpaid'
            ]);
            
            $newContractId = $db->lastInsertId();
            
            // تسجيل النشاط
            $db->prepare("INSERT INTO activity_log (user_id, action, description, target_type, target_id, ip_address) VALUES (?, 'create_contract', ?, 'contract', ?, ?)")
               ->execute([$_SESSION['user_id'], "إنشاء عقد جديد رقم $contractNumber", $newContractId, $_SERVER['REMOTE_ADDR']]);
            
            // إشعار للمدير إذا تم إرسال العقد للمراجعة
            if ($status === 'pending') {
                $admins = $db->query("SELECT id FROM users WHERE role = 'admin' AND is_active = 1")->fetchAll();
                foreach ($admins as $admin) {
                    $db->prepare("INSERT INTO notifications (user_id, title, message, link) VALUES (?, ?, ?, ?)")
                       ->execute([$admin['id'], 'عقد جديد للمراجعة', "عقد جديد رقم $contractNumber من الوكيل " . $_SESSION['full_name'], "contract_view.php?id=$newContractId"]);
                }
            }
            
            $msg = $status === 'draft' ? 'تم حفظ العقد كمسودة' : 'تم إرسال العقد للمراجعة';
            echo json_encode(['success' => true, 'message' => $msg, 'contract_id' => $newContractId]);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'حدث خطأ: ' . $e->getMessage()]);
        }
        break;
    
    // ======= قائمة العقود =======
    case 'list':
        $page = max(1, (int)($_POST['page'] ?? 1));
        $perPage = 15;
        $offset = ($page - 1) * $perPage;
        
        $where = [];
        $params = [];
        
        // فلترة حسب الدور
        if (!isAdmin()) {
            $where[] = "c.agent_id = ?";
            $params[] = $_SESSION['user_id'];
        }
        
        // بحث
        $search = clean($_POST['search'] ?? '');
        if ($search) {
            $where[] = "(c.contract_number LIKE ? OR cl.full_name LIKE ? OR c.car_number LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        
        // فلترة الحالة
        $status = clean($_POST['status'] ?? '');
        if ($status) {
            $where[] = "c.status = ?";
            $params[] = $status;
        }
        
        // فلترة الوكيل (للمدير)
        $agentId = (int)($_POST['agent_id'] ?? 0);
        if ($agentId && isAdmin()) {
            $where[] = "c.agent_id = ?";
            $params[] = $agentId;
        }
        
        // فلترة الفترة
        $period = clean($_POST['period'] ?? '');
        if ($period === 'month') {
            $where[] = "c.created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
        } elseif ($period === '3months') {
            $where[] = "c.created_at >= DATE_SUB(NOW(), INTERVAL 3 MONTH)";
        } elseif ($period === 'year') {
            $where[] = "c.created_at >= DATE_SUB(NOW(), INTERVAL 1 YEAR)";
        }
        
        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
        
        // عد النتائج
        $countSql = "SELECT COUNT(*) FROM contracts c JOIN clients cl ON c.client_id = cl.id $whereClause";
        $countStmt = $db->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetchColumn();
        $pages = ceil($total / $perPage);
        
        // جلب البيانات
        $sql = "SELECT c.*, cl.full_name as client_name, u.full_name as agent_name,
                p.name as package_name
                FROM contracts c 
                JOIN clients cl ON c.client_id = cl.id 
                JOIN users u ON c.agent_id = u.id 
                LEFT JOIN packages p ON c.package_id = p.id
                $whereClause 
                ORDER BY c.created_at DESC 
                LIMIT $perPage OFFSET $offset";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $contracts = $stmt->fetchAll();
        
        echo json_encode([
            'success' => true,
            'data' => $contracts,
            'total' => $total,
            'pages' => $pages,
            'current_page' => $page
        ]);
        break;
    
    // ======= تحديث العقد =======
    case 'update':
    case 'resubmit':
        try {
            $contractId = (int)($_POST['contract_id'] ?? 0);
            
            // التحقق من الصلاحية
            $checkStmt = $db->prepare("SELECT * FROM contracts WHERE id = ?");
            $checkStmt->execute([$contractId]);
            $contract = $checkStmt->fetch();
            
            if (!$contract) {
                echo json_encode(['success' => false, 'message' => 'العقد غير موجود']);
                exit;
            }
            
            if (!isAdmin() && $contract['agent_id'] != $_SESSION['user_id']) {
                echo json_encode(['success' => false, 'message' => 'غير مصرح بالتعديل']);
                exit;
            }
            
            $newStatus = $action === 'resubmit' ? 'pending' : $contract['status'];
            
            $updatePackageId = !empty($_POST['package_id']) ? (int)$_POST['package_id'] : $contract['package_id'];
            $updatePrice = !empty($_POST['price']) ? (float)$_POST['price'] : $contract['price'];
            
            $updateStmt = $db->prepare("UPDATE contracts SET 
                plate_type = ?, classification = ?, car_number = ?, license_type = ?, car_type = ?,
                car_color = ?, production_year = ?, usage_type = ?, insurance_type = ?, chassis_number = ?,
                start_date = ?, end_date = ?, status = ?, admin_notes = NULL,
                package_id = ?, price = ?
                WHERE id = ?");
            
            $updateStmt->execute([
                clean($_POST['plate_type'] ?? $contract['plate_type']),
                clean($_POST['classification'] ?? $contract['classification']),
                clean($_POST['car_number'] ?? $contract['car_number']),
                clean($_POST['license_type'] ?? $contract['license_type']),
                clean($_POST['car_type'] ?? $contract['car_type']),
                clean($_POST['car_color'] ?? $contract['car_color']),
                $_POST['production_year'] ?? $contract['production_year'],
                clean($_POST['usage_type'] ?? $contract['usage_type']),
                clean($_POST['insurance_type'] ?? $contract['insurance_type']),
                clean($_POST['chassis_number'] ?? $contract['chassis_number']),
                $_POST['start_date'] ?? $contract['start_date'],
                $_POST['end_date'] ?? $contract['end_date'],
                $newStatus,
                $updatePackageId,
                $updatePrice,
                $contractId
            ]);
            
            $msg = $action === 'resubmit' ? 'تم إعادة إرسال العقد للمراجعة' : 'تم تحديث العقد بنجاح';
            
            // إشعار للمدير عند إعادة الإرسال
            if ($action === 'resubmit') {
                $admins = $db->query("SELECT id FROM users WHERE role = 'admin' AND is_active = 1")->fetchAll();
                foreach ($admins as $admin) {
                    $db->prepare("INSERT INTO notifications (user_id, title, message, link) VALUES (?, ?, ?, ?)")
                       ->execute([$admin['id'], 'عقد مُعاد للمراجعة', "العقد رقم " . $contract['contract_number'] . " تم تعديله وإعادة إرساله", "contract_view.php?id=$contractId"]);
                }
            }
            
            echo json_encode(['success' => true, 'message' => $msg]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'خطأ: ' . $e->getMessage()]);
        }
        break;
    
    // ======= موافقة على العقد =======
    case 'approve':
        if (!isAdmin()) {
            echo json_encode(['success' => false, 'message' => 'غير مصرح']);
            exit;
        }
        
        $contractId = (int)($_POST['contract_id'] ?? 0);
        $db->prepare("UPDATE contracts SET status = 'active', policy_issued_at = NOW() WHERE id = ?")->execute([$contractId]);
        
        // إشعار الوكيل
        $contract = $db->prepare("SELECT * FROM contracts WHERE id = ?");
        $contract->execute([$contractId]);
        $c = $contract->fetch();
        
        $db->prepare("INSERT INTO notifications (user_id, title, message, link) VALUES (?, ?, ?, ?)")
           ->execute([$c['agent_id'], 'تمت الموافقة على العقد', "تمت الموافقة على العقد رقم " . $c['contract_number'], "contract_view.php?id=$contractId"]);
        
        // تسجيل النشاط
        $db->prepare("INSERT INTO activity_log (user_id, action, description, target_type, target_id, ip_address) VALUES (?, 'approve_contract', ?, 'contract', ?, ?)")
           ->execute([$_SESSION['user_id'], "موافقة على العقد رقم " . $c['contract_number'], $contractId, $_SERVER['REMOTE_ADDR']]);
        
        echo json_encode(['success' => true, 'message' => 'تمت الموافقة على العقد بنجاح']);
        break;
    
    // ======= رفض العقد =======
    case 'reject':
        if (!isAdmin()) {
            echo json_encode(['success' => false, 'message' => 'غير مصرح']);
            exit;
        }
        
        $contractId = (int)($_POST['contract_id'] ?? 0);
        $adminNotes = clean($_POST['admin_notes'] ?? '');
        
        $db->prepare("UPDATE contracts SET status = 'rejected', admin_notes = ? WHERE id = ?")->execute([$adminNotes, $contractId]);
        
        // إشعار الوكيل
        $contract = $db->prepare("SELECT * FROM contracts WHERE id = ?");
        $contract->execute([$contractId]);
        $c = $contract->fetch();
        
        $db->prepare("INSERT INTO notifications (user_id, title, message, link) VALUES (?, ?, ?, ?)")
           ->execute([$c['agent_id'], 'تم رفض العقد', "تم رفض العقد رقم " . $c['contract_number'] . ": $adminNotes", "contract_view.php?id=$contractId"]);
        
        echo json_encode(['success' => true, 'message' => 'تم رفض العقد']);
        break;
    
    // ======= تحديث حالة الدفع =======
    case 'update_payment':
        if (!isAdmin()) {
            echo json_encode(['success' => false, 'message' => 'غير مصرح']);
            exit;
        }
        
        $contractId = (int)($_POST['contract_id'] ?? 0);
        $paymentStatus = clean($_POST['payment_status'] ?? 'unpaid');
        $paymentNotes = clean($_POST['payment_notes'] ?? '');
        
        if (!in_array($paymentStatus, ['unpaid', 'paid', 'partial'])) {
            echo json_encode(['success' => false, 'message' => 'حالة دفع غير صالحة']);
            exit;
        }
        
        $paidAt = ($paymentStatus === 'paid') ? date('Y-m-d H:i:s') : null;
        
        $db->prepare("UPDATE contracts SET payment_status = ?, payment_notes = ?, paid_at = ? WHERE id = ?")
           ->execute([$paymentStatus, $paymentNotes, $paidAt, $contractId]);
        
        $statusText = ['unpaid' => 'غير مدفوع', 'paid' => 'مدفوع', 'partial' => 'مدفوع جزئياً'];
        
        // تسجيل النشاط
        $db->prepare("INSERT INTO activity_log (user_id, action, description, target_type, target_id, ip_address) VALUES (?, 'update_payment', ?, 'contract', ?, ?)")
           ->execute([$_SESSION['user_id'], "تحديث حالة الدفع إلى: " . $statusText[$paymentStatus], $contractId, $_SERVER['REMOTE_ADDR']]);
        
        echo json_encode(['success' => true, 'message' => 'تم تحديث حالة الدفع بنجاح']);
        break;
    
    // ======= حذف العقد =======
    case 'delete':
        $contractId = (int)($_POST['contract_id'] ?? 0);
        $checkStmt = $db->prepare("SELECT * FROM contracts WHERE id = ?");
        $checkStmt->execute([$contractId]);
        $contract = $checkStmt->fetch();
        
        if (!$contract) {
            echo json_encode(['success' => false, 'message' => 'العقد غير موجود']);
            exit;
        }
        
        if (!isAdmin() && $contract['agent_id'] != $_SESSION['user_id']) {
            echo json_encode(['success' => false, 'message' => 'غير مصرح']);
            exit;
        }
        
        if (!in_array($contract['status'], ['draft'])) {
            echo json_encode(['success' => false, 'message' => 'لا يمكن حذف عقد بهذه الحالة']);
            exit;
        }
        
        $db->prepare("DELETE FROM contracts WHERE id = ?")->execute([$contractId]);
        echo json_encode(['success' => true, 'message' => 'تم حذف العقد']);
        break;
    
    default:
        echo json_encode(['success' => false, 'message' => 'إجراء غير معروف']);
}
