<?php
require_once '../../config/database.php';
require_once '../../models/user.php';

session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$database = new Database();
$db = $database->getConnection();

// Handle form submissions
$message = '';
$message_type = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['upload_document'])) {
        $document_type = $_POST['document_type'];
        $document_name = $_POST['document_name'];
        $expiry_date = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;
        $notes = $_POST['notes'] ?? '';

        // Handle file upload
        $upload_dir = '../../uploads/licenses/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $file_path = '';
        if (isset($_FILES['document_file']) && $_FILES['document_file']['error'] === UPLOAD_ERR_OK) {
            $file_extension = pathinfo($_FILES['document_file']['name'], PATHINFO_EXTENSION);
            $file_name = time() . '_' . uniqid() . '.' . $file_extension;
            $file_path = $upload_dir . $file_name;

            if (move_uploaded_file($_FILES['document_file']['tmp_name'], $file_path)) {
                // Save to database
                $query = "INSERT INTO business_licenses (document_type, document_name, document_path, expiry_date, notes, created_at) 
                          VALUES (?, ?, ?, ?, ?, NOW())";
                $stmt = $db->prepare($query);
                
                if ($stmt->execute([$document_type, $document_name, $file_path, $expiry_date, $notes])) {
                    $message = 'تم رفع المستند بنجاح!';
                    $message_type = 'success';
                } else {
                    $message = 'حدث خطأ أثناء حفظ المستند في قاعدة البيانات';
                    $message_type = 'error';
                }
            } else {
                $message = 'حدث خطأ أثناء رفع الملف';
                $message_type = 'error';
            }
        } else {
            $message = 'يرجى اختيار ملف للرفع';
            $message_type = 'error';
        }
    } elseif (isset($_POST['verify_document'])) {
        $document_id = $_POST['document_id'];
        $is_verified = isset($_POST['is_verified']) ? 1 : 0;

        $query = "UPDATE business_licenses SET is_verified = ?, verification_date = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        $verification_date = $is_verified ? date('Y-m-d H:i:s') : null;
        
        if ($stmt->execute([$is_verified, $verification_date, $document_id])) {
            $message = $is_verified ? 'تم التحقق من المستند بنجاح!' : 'تم إلغاء التحقق من المستند!';
            $message_type = 'success';
        } else {
            $message = 'حدث خطأ أثناء تحديث حالة المستند';
            $message_type = 'error';
        }
    } elseif (isset($_POST['delete_document'])) {
        $document_id = $_POST['document_id'];

        // Get document path
        $query = "SELECT document_path FROM business_licenses WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$document_id]);
        $document = $stmt->fetch(PDO::FETCH_ASSOC);

        // Delete file if exists
        if ($document && file_exists($document['document_path'])) {
            unlink($document['document_path']);
        }

        // Delete from database
        $query = "DELETE FROM business_licenses WHERE id = ?";
        $stmt = $db->prepare($query);

        if ($stmt->execute([$document_id])) {
            $message = 'تم حذف المستند بنجاح!';
            $message_type = 'success';
        } else {
            $message = 'حدث خطأ أثناء حذف المستند';
            $message_type = 'error';
        }
    }
}

// Get all business licenses
$query = "SELECT * FROM business_licenses ORDER BY created_at DESC";
$stmt = $db->prepare($query);
$stmt->execute();
$business_licenses = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Document type labels
$document_types = [
    'commercial_register' => 'السجل التجاري',
    'tax_card' => 'البطاقة الضريبية',
    'national_id' => 'بطاقة الهوية الوطنية',
    'business_address' => 'إثبات محل النشاط التجاري',
    'company_registration' => 'شهادة تسجيل الشركة',
    'health_license' => 'ترخيص صحي',
    'other' => 'أخرى'
];

$document_icons = [
    'commercial_register' => 'fas fa-file-contract',
    'tax_card' => 'fas fa-file-invoice-dollar',
    'national_id' => 'fas fa-id-card',
    'business_address' => 'fas fa-map-marker-alt',
    'company_registration' => 'fas fa-building',
    'health_license' => 'fas fa-briefcase-medical',
    'other' => 'fas fa-file'
];

$document_colors = [
    'commercial_register' => 'bg-blue-50 border-blue-200',
    'tax_card' => 'bg-green-50 border-green-200',
    'national_id' => 'bg-purple-50 border-purple-200',
    'business_address' => 'bg-orange-50 border-orange-200',
    'company_registration' => 'bg-red-50 border-red-200',
    'health_license' => 'bg-pink-50 border-pink-200',
    'other' => 'bg-gray-50 border-gray-200'
];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة التراخيص والمستندات - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            font-family: 'Tajawal', sans-serif;
        }
        .document-card {
            transition: all 0.3s ease;
        }
        .document-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">

    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
        <div class="flex items-center justify-between px-6 py-4">
            <div class="flex items-center space-x-4 space-x-reverse">
                <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                    <i class="fas fa-arrow-right text-xl"></i>
                </a>
                <div>
                    <h1 class="text-2xl font-bold text-gray-900">إدارة التراخيص والمستندات</h1>
                    <p class="text-sm text-gray-500">إدارة المستندات القانونية والتراخيص التجارية</p>
                </div>
            </div>
            <div class="flex items-center space-x-4 space-x-reverse">
                <a href="../../public/index.php" class="text-gray-600 hover:text-gray-900" title="المتجر">
                    <i class="fas fa-store text-xl"></i>
                </a>
                <a href="../logout.php" class="text-gray-600 hover:text-red-600" title="تسجيل الخروج">
                    <i class="fas fa-sign-out-alt text-xl"></i>
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto p-6">
        <!-- Success/Error Message Display -->
        <?php if ($message): ?>
            <div class="mb-6 p-4 rounded-lg border-r-4 <?php echo $message_type === 'success' ? 'bg-green-50 border-green-400' : 'bg-red-50 border-red-400'; ?>">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fas <?php echo $message_type === 'success' ? 'fa-check-circle text-green-400' : 'fa-exclamation-circle text-red-400'; ?> text-xl"></i>
                    </div>
                    <div class="mr-3">
                        <p class="text-sm <?php echo $message_type === 'success' ? 'text-green-700' : 'text-red-700'; ?>"><?php echo $message; ?></p>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <?php
            $total_docs = count($business_licenses);
            $verified_docs = count(array_filter($business_licenses, fn($doc) => $doc['is_verified']));
            $expired_docs = count(array_filter($business_licenses, fn($doc) => 
                $doc['expiry_date'] && strtotime($doc['expiry_date']) < time()
            ));
            $expiring_soon = count(array_filter($business_licenses, fn($doc) => 
                $doc['expiry_date'] && 
                strtotime($doc['expiry_date']) > time() && 
                strtotime($doc['expiry_date']) < strtotime('+30 days')
            ));
            ?>
            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">إجمالي المستندات</p>
                        <p class="text-3xl font-bold text-gray-900"><?php echo $total_docs; ?></p>
                    </div>
                    <div class="bg-blue-50 p-3 rounded-lg">
                        <i class="fas fa-file-alt text-blue-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">موثقة</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo $verified_docs; ?></p>
                    </div>
                    <div class="bg-green-50 p-3 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">تنتهي قريباً</p>
                        <p class="text-3xl font-bold text-orange-600"><?php echo $expiring_soon; ?></p>
                    </div>
                    <div class="bg-orange-50 p-3 rounded-lg">
                        <i class="fas fa-clock text-orange-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">منتهية</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo $expired_docs; ?></p>
                    </div>
                    <div class="bg-red-50 p-3 rounded-lg">
                        <i class="fas fa-exclamation-triangle text-red-600 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Upload New Document -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 sticky top-24">
                    <h2 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                        <i class="fas fa-upload text-blue-600 ml-3"></i>
                        رفع مستند جديد
                    </h2>

                    <form method="POST" enctype="multipart/form-data" class="space-y-4" id="uploadForm">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">نوع المستند *</label>
                            <select name="document_type" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <option value="">اختر نوع المستند</option>
                                <?php foreach ($document_types as $key => $label): ?>
                                    <option value="<?php echo $key; ?>"><?php echo $label; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">اسم المستند *</label>
                            <input type="text" name="document_name" required placeholder="مثال: السجل التجاري 2025"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">تاريخ الانتهاء</label>
                            <input type="date" name="expiry_date"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">الملف *</label>
                            <input type="file" name="document_file" accept=".pdf,.jpg,.jpeg,.png" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <p class="text-xs text-gray-500 mt-1">الملفات المسموحة: PDF, JPG, PNG (حجم أقصى: 5MB)</p>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">ملاحظات</label>
                            <textarea name="notes" rows="3" placeholder="أي ملاحظات إضافية..."
                                      class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"></textarea>
                        </div>

                        <button type="submit" name="upload_document"
                                class="w-full bg-blue-600 hover:bg-blue-700 text-white px-4 py-3 rounded-lg font-medium transition-colors duration-150 inline-flex items-center justify-center">
                            <i class="fas fa-upload ml-2"></i>
                            رفع المستند
                        </button>
                    </form>
                </div>
            </div>

            <!-- Documents List -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-lg font-semibold text-gray-900 flex items-center">
                            <i class="fas fa-folder-open text-green-600 ml-3"></i>
                            المستندات المرفوعة
                        </h2>
                        <span class="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded-full"><?php echo count($business_licenses); ?> مستند</span>
                    </div>

                    <?php if (!empty($business_licenses)): ?>
                        <div class="space-y-4">
                            <?php foreach ($business_licenses as $license): ?>
                                <div class="document-card border rounded-lg p-4 <?php echo $document_colors[$license['document_type']] ?? 'bg-gray-50 border-gray-200'; ?>">
                                    <div class="flex items-start justify-between">
                                        <div class="flex items-start space-x-3 space-x-reverse flex-1">
                                            <div class="flex-shrink-0 mt-1">
                                                <i class="<?php echo $document_icons[$license['document_type']] ?? 'fas fa-file'; ?> text-2xl text-gray-600"></i>
                                            </div>
                                            <div class="flex-1 min-w-0">
                                                <h3 class="font-semibold text-gray-900 mb-1"><?php echo htmlspecialchars($license['document_name']); ?></h3>
                                                <p class="text-sm text-gray-600 mb-2"><?php echo $document_types[$license['document_type']] ?? $license['document_type']; ?></p>

                                                <?php if ($license['expiry_date']): ?>
                                                    <p class="text-xs text-gray-500 mb-2">
                                                        <i class="fas fa-calendar-alt ml-1"></i>
                                                        ينتهي في: <?php echo date('d/m/Y', strtotime($license['expiry_date'])); ?>
                                                        <?php
                                                        $days_until_expiry = floor((strtotime($license['expiry_date']) - time()) / (60*60*24));
                                                        if ($days_until_expiry <= 30 && $days_until_expiry > 0) {
                                                            echo '<span class="text-orange-600 font-medium">(متبقي ' . $days_until_expiry . ' يوم)</span>';
                                                        } elseif ($days_until_expiry <= 0) {
                                                            echo '<span class="text-red-600 font-medium">(منتهي الصلاحية)</span>';
                                                        }
                                                        ?>
                                                    </p>
                                                <?php endif; ?>

                                                <?php if ($license['notes']): ?>
                                                    <p class="text-xs text-gray-500 mb-2 bg-white bg-opacity-50 p-2 rounded">
                                                        <i class="fas fa-sticky-note ml-1"></i>
                                                        <?php echo htmlspecialchars($license['notes']); ?>
                                                    </p>
                                                <?php endif; ?>

                                                <div class="flex items-center space-x-2 space-x-reverse mt-2">
                                                    <?php if ($license['is_verified']): ?>
                                                        <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                            <i class="fas fa-check-circle ml-1"></i>
                                                            موثق
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                                            <i class="fas fa-clock ml-1"></i>
                                                            في انتظار التوثيق
                                                        </span>
                                                    <?php endif; ?>

                                                    <span class="text-xs text-gray-500">
                                                        <i class="fas fa-clock ml-1"></i>
                                                        <?php echo date('d/m/Y H:i', strtotime($license['created_at'])); ?>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="flex items-center space-x-2 space-x-reverse mr-3">
                                            <?php if ($license['document_path']): ?>
                                                <a href="<?php echo htmlspecialchars($license['document_path']); ?>" target="_blank"
                                                   class="text-blue-600 hover:text-blue-800 p-2 rounded hover:bg-blue-50" title="عرض">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <a href="<?php echo htmlspecialchars($license['document_path']); ?>" download
                                                   class="text-green-600 hover:text-green-800 p-2 rounded hover:bg-green-50" title="تحميل">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                            <?php endif; ?>

                                            <form method="POST" class="inline" onsubmit="return confirm('هل أنت متأكد من حذف هذا المستند؟')">
                                                <input type="hidden" name="document_id" value="<?php echo $license['id']; ?>">
                                                <button type="submit" name="delete_document"
                                                        class="text-red-600 hover:text-red-800 p-2 rounded hover:bg-red-50" title="حذف">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </div>

                                    <!-- Verification Actions -->
                                    <div class="mt-3 pt-3 border-t border-gray-200">
                                        <form method="POST" class="flex items-center">
                                            <input type="hidden" name="document_id" value="<?php echo $license['id']; ?>">
                                            <input type="hidden" name="verify_document" value="1">
                                            <label class="flex items-center space-x-2 space-x-reverse cursor-pointer">
                                                <input type="checkbox" name="is_verified" value="1" 
                                                       <?php echo $license['is_verified'] ? 'checked' : ''; ?>
                                                       onchange="this.form.submit()"
                                                       class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500">
                                                <span class="text-sm font-medium text-gray-700">مستند موثق ومعتمد</span>
                                            </label>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-16">
                            <div class="text-gray-300 mb-4">
                                <i class="fas fa-folder-open text-6xl"></i>
                            </div>
                            <h3 class="text-lg font-medium text-gray-600 mb-2">لا توجد مستندات مرفوعة</h3>
                            <p class="text-gray-500">ابدأ برفع المستندات المطلوبة لإدارة أعمالك</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // File validation
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.querySelector('input[name="document_file"]');
            const maxSize = 5 * 1024 * 1024; // 5MB
            const allowedTypes = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];

            if (fileInput) {
                fileInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        if (file.size > maxSize) {
                            Swal.fire({
                                icon: 'error',
                                title: 'خطأ!',
                                text: 'حجم الملف يجب أن يكون أقل من 5 ميجابايت',
                            });
                            e.target.value = '';
                            return;
                        }

                        if (!allowedTypes.includes(file.type)) {
                            Swal.fire({
                                icon: 'error',
                                title: 'خطأ!',
                                text: 'نوع الملف غير مسموح. يرجى رفع ملف PDF أو صورة',
                            });
                            e.target.value = '';
                            return;
                        }
                    }
                });
            }
        });

        // Success message with SweetAlert2
        <?php if ($message && $message_type === 'success'): ?>
        Swal.fire({
            icon: 'success',
            title: 'تم بنجاح!',
            text: '<?php echo addslashes($message); ?>',
            timer: 3000,
            showConfirmButton: false
        });
        <?php endif; ?>
    </script>
</body>
</html>
