<?php
session_start();

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

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $query = "SELECT ip.*, p.name as product_name 
              FROM identity_profiles ip 
              LEFT JOIN products p ON ip.product_id = p.id 
              ORDER BY ip.created_at DESC";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $all_profiles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $all_profiles = [];
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete_profile'])) {
        try {
            $profile_id = $_POST['profile_id'];
            $query = "DELETE FROM identity_profiles WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$profile_id]);
            
            header("Location: index.php?deleted=1");
            exit;
        } catch (Exception $e) {
            $message = "خطأ في الحذف: " . $e->getMessage();
        }
    } elseif (isset($_POST['toggle_status'])) {
        try {
            $profile_id = $_POST['profile_id'];
            $query = "UPDATE identity_profiles SET is_active = NOT is_active WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$profile_id]);
            
            header("Location: index.php?updated=1");
            exit;
        } catch (Exception $e) {
            $message = "خطأ في التحديث: " . $e->getMessage();
        }
    }
}

if (isset($_GET['deleted'])) {
    $message = 'تم حذف الملف الشخصي بنجاح!';
} elseif (isset($_GET['updated'])) {
    $message = 'تم تحديث حالة الملف الشخصي بنجاح!';
}
?>
<!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">
    <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; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <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>
                    <h1 class="text-2xl font-bold text-gray-900">إدارة الملفات الشخصية</h1>
                </div>
                <a href="add.php" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                    <i class="fas fa-plus ml-2"></i>
                    إضافة ملف شخصي
                </a>
            </div>
        </header>

        <div class="p-6">
            <?php if (isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700"><?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <p class="text-sm text-green-700"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <?php
                $stats = [
                    'total' => count($all_profiles),
                    'active' => count(array_filter($all_profiles, fn($p) => $p['is_active'])),
                    'with_products' => count(array_filter($all_profiles, fn($p) => !empty($p['product_id'])))
                ];
            ?>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي الملفات</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $stats['total']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-id-card text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">الملفات النشطة</p>
                            <p class="text-2xl font-bold text-green-600"><?php echo $stats['active']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">مرتبطة بمنتجات</p>
                            <p class="text-2xl font-bold text-blue-600"><?php echo $stats['with_products']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-link text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php if (!empty($all_profiles)): ?>
                    <?php foreach ($all_profiles as $profile): ?>
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow">
                            <?php if (!empty($profile['profile_image'])): ?>
                                <img src="../../<?php echo htmlspecialchars($profile['profile_image']); ?>" 
                                     alt="<?php echo htmlspecialchars($profile['title']); ?>" 
                                     class="w-full h-48 object-cover">
                            <?php else: ?>
                                <div class="w-full h-48 bg-gradient-to-br from-purple-100 to-purple-200 flex items-center justify-center">
                                    <i class="fas fa-id-card text-purple-400 text-5xl"></i>
                                </div>
                            <?php endif; ?>
                            
                            <div class="p-4">
                                <div class="flex items-center justify-between mb-2">
                                    <h3 class="text-xl font-semibold text-gray-900">
                                        <?php echo htmlspecialchars($profile['title']); ?>
                                    </h3>
                                    <?php if ($profile['is_active']): ?>
                                        <span class="inline-flex items-center px-2 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 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                            <i class="fas fa-times-circle ml-1"></i>معطل
                                        </span>
                                    <?php endif; ?>
                                </div>
                                
                                <p class="text-gray-600 text-sm mb-3">
                                    <?php echo htmlspecialchars(substr($profile['description'] ?? '', 0, 100)); ?>
                                    <?php if (strlen($profile['description'] ?? '') > 100) echo '...'; ?>
                                </p>
                                
                                <?php if (!empty($profile['product_name'])): ?>
                                    <div class="mb-3">
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                            <i class="fas fa-box ml-1"></i><?php echo htmlspecialchars($profile['product_name']); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="flex items-center gap-2">
                                    <a href="add.php?id=<?php echo $profile['id']; ?>" 
                                       class="flex-1 bg-blue-50 text-blue-600 px-3 py-2 rounded-md text-sm text-center hover:bg-blue-100">
                                        <i class="fas fa-edit ml-1"></i>تعديل
                                    </a>
                                    <form method="POST" class="flex-1">
                                        <input type="hidden" name="profile_id" value="<?php echo $profile['id']; ?>">
                                        <button type="submit" name="toggle_status" 
                                                class="w-full bg-yellow-50 text-yellow-600 px-3 py-2 rounded-md text-sm hover:bg-yellow-100">
                                            <i class="fas fa-toggle-on ml-1"></i>تبديل
                                        </button>
                                    </form>
                                    <form method="POST" onsubmit="return confirm('هل أنت متأكد من حذف هذا الملف؟');">
                                        <input type="hidden" name="profile_id" value="<?php echo $profile['id']; ?>">
                                        <button type="submit" name="delete_profile" 
                                                class="bg-red-50 text-red-600 px-3 py-2 rounded-md text-sm hover:bg-red-100">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-span-3 bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
                        <div class="max-w-md mx-auto">
                            <div class="w-24 h-24 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-id-card text-4xl text-purple-400"></i>
                            </div>
                            <h3 class="text-xl font-semibold text-gray-700 mb-2">لا توجد ملفات شخصية</h3>
                            <p class="text-gray-500 mb-6">ابدأ بإضافة ملفات شخصية لعرض هوية علامتك التجارية</p>
                            <a href="add.php" class="inline-flex items-center bg-purple-600 text-white px-6 py-3 rounded-lg hover:bg-purple-700">
                                <i class="fas fa-plus ml-2"></i>
                                إضافة ملف شخصي جديد
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>
