<?php
session_start();
require_once '../../config/database.php';

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

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

// التحقق من وجود الجدول
try {
    $check = $db->query("SHOW TABLES LIKE 'stories'");
    if ($check->rowCount() == 0) {
        $message = '<div class="bg-yellow-50 border-r-4 border-yellow-400 p-4 mb-6 rounded-lg">
            <p class="text-sm text-yellow-700 font-medium">
                <i class="fas fa-exclamation-triangle ml-2"></i>
                يجب إنشاء جدول الاستوريز أولاً. 
                <a href="../../setup/create_stories_system.php" class="underline font-bold">اضغط هنا لإنشاء الجدول</a>
            </p>
        </div>';
        $stories = [];
    } else {
        // معالجة الإضافة/الحذف
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            try {
                if (isset($_POST['add_story']) && isset($_FILES['image'])) {
                    $title = $_POST['title'];
                    $link = $_POST['link'] ?? '';
                    $duration = $_POST['duration'] ?? 5;
                    
                    if ($_FILES['image']['error'] === 0) {
                        $upload_dir = '../../uploads/stories/';
                        if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);
                        
                        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                        $filename = 'story_' . time() . '.' . $ext;
                        
                        if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $filename)) {
                            // حفظ المسار فقط بدون ../
                            $image_path = 'uploads/stories/' . $filename;
                            $query = "INSERT INTO stories (title, image, link, duration, created_by) VALUES (?, ?, ?, ?, ?)";
                            $stmt = $db->prepare($query);
                            $stmt->execute([$title, $image_path, $link, $duration, $_SESSION['user_id']]);
                            $message = '<div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6 rounded-lg">
                                <p class="text-sm text-green-700 font-medium">تم إضافة الاستوري بنجاح!</p>
                            </div>';
                        }
                    }
                } elseif (isset($_POST['delete_story'])) {
                    $id = $_POST['story_id'];
                    $query = "DELETE FROM stories WHERE id = ?";
                    $stmt = $db->prepare($query);
                    $stmt->execute([$id]);
                    $message = '<div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6 rounded-lg">
                        <p class="text-sm text-green-700 font-medium">تم الحذف بنجاح!</p>
                    </div>';
                } elseif (isset($_POST['toggle_status'])) {
                    $id = $_POST['story_id'];
                    $query = "UPDATE stories SET is_active = NOT is_active WHERE id = ?";
                    $stmt = $db->prepare($query);
                    $stmt->execute([$id]);
                    $message = '<div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6 rounded-lg">
                        <p class="text-sm text-green-700 font-medium">تم التحديث!</p>
                    </div>';
                }
            } catch (Exception $e) {
                $message = '<div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6 rounded-lg">
                    <p class="text-sm text-red-700 font-medium">خطأ: ' . $e->getMessage() . '</p>
                </div>';
            }
        }
        
        // جلب الاستوريز
        $query = "SELECT * FROM stories ORDER BY created_at DESC";
        $stmt = $db->prepare($query);
        $stmt->execute();
        $stories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    $message = '<div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6 rounded-lg">
        <p class="text-sm text-red-700 font-medium">خطأ: ' . $e->getMessage() . '</p>
    </div>';
    $stories = [];
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>إدارة الاستوريز</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@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 p-6">
        <div class="max-w-7xl mx-auto">
            <?php 
            $base_path = '../';
            include '../includes/quick-actions-bar.php'; 
            ?>
            
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-4">
                    <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-3xl font-bold text-gray-900">
                        <i class="fas fa-circle-notch text-pink-500 ml-2"></i>
                        إدارة الاستوريز
                    </h1>
                </div>
                <div class="flex gap-3">
                    <a href="upload.php" class="bg-gradient-to-r from-purple-500 to-pink-600 text-white px-6 py-3 rounded-xl font-bold shadow-lg inline-flex items-center gap-2 hover:from-purple-600 hover:to-pink-700">
                        <i class="fas fa-mobile-alt"></i>
                        رفع سريع
                    </a>
                    <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                            class="bg-gradient-to-r from-pink-500 to-purple-600 text-white px-6 py-3 rounded-xl font-bold shadow-lg">
                        <i class="fas fa-plus ml-2"></i>إضافة استوري
                    </button>
                </div>
            </div>

            <?php echo $message; ?>

            <?php if (empty($stories)): ?>
                <div class="bg-white rounded-xl shadow-sm p-12 text-center">
                    <i class="fas fa-circle-notch text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-700 mb-2">لا توجد استوريز</h3>
                    <p class="text-gray-500 mb-6">ابدأ بإضافة أول استوري</p>
                    <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                            class="bg-pink-500 text-white px-6 py-3 rounded-lg font-bold">
                        <i class="fas fa-plus ml-2"></i>إضافة استوري
                    </button>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
                    <?php foreach ($stories as $story): ?>
                        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                            <div class="aspect-[9/16] bg-gradient-to-br from-pink-400 to-purple-600 relative">
                                <?php 
                                // المسار من admin/stories/ إلى uploads/
                                $image_path = '../../' . $story['image'];
                                ?>
                                <img src="<?php echo $image_path; ?>" class="w-full h-full object-cover" onerror="this.style.display='none'; this.parentElement.innerHTML='<div class=/'flex items-center justify-center h-full text-white\'><i class=/'fas fa-image text-4xl\'></i></div>'">
                                <div class="absolute top-2 right-2">
                                    <?php if ($story['is_active']): ?>
                                        <span class="bg-green-500 text-white px-2 py-1 rounded-full text-xs font-bold">نشط</span>
                                    <?php else: ?>
                                        <span class="bg-gray-500 text-white px-2 py-1 rounded-full text-xs font-bold">معطل</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="p-4">
                                <h3 class="font-bold text-gray-900 mb-2"><?php echo htmlspecialchars($story['title']); ?></h3>
                                <div class="flex items-center gap-2 text-sm text-gray-600 mb-3">
                                    <i class="fas fa-eye"></i>
                                    <span><?php echo $story['views_count']; ?> مشاهدة</span>
                                </div>
                                <div class="flex gap-2">
                                    <form method="POST" class="flex-1">
                                        <input type="hidden" name="story_id" value="<?php echo $story['id']; ?>">
                                        <button type="submit" name="toggle_status" class="w-full bg-yellow-50 text-yellow-600 px-3 py-2 rounded-lg text-sm hover:bg-yellow-100">
                                            <?php echo $story['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                                        </button>
                                    </form>
                                    <form method="POST" onsubmit="return confirm('هل أنت متأكد؟')">
                                        <input type="hidden" name="story_id" value="<?php echo $story['id']; ?>">
                                        <button type="submit" name="delete_story" class="bg-red-50 text-red-600 px-3 py-2 rounded-lg text-sm hover:bg-red-100">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Add Modal -->
    <div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-xl max-w-md w-full p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-bold">إضافة استوري جديد</h3>
                <button onclick="document.getElementById('addModal').classList.add('hidden')" class="text-gray-400">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <div>
                    <label class="block text-sm font-bold mb-2">العنوان</label>
                    <input type="text" name="title" required class="w-full border rounded-lg px-3 py-2">
                </div>
                <div>
                    <label class="block text-sm font-bold mb-2">الصورة (1080×1920)</label>
                    <input type="file" name="image" id="imageInput" accept="image/*" required class="w-full border rounded-lg px-3 py-2" onchange="previewImage(this)">
                    <div id="imagePreview" class="mt-3 hidden">
                        <img id="preview" class="w-full h-48 object-cover rounded-lg border-2 border-pink-200">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-bold mb-2">الرابط (اختياري)</label>
                    <input type="url" name="link" class="w-full border rounded-lg px-3 py-2">
                </div>
                <div>
                    <label class="block text-sm font-bold mb-2">المدة (ثواني)</label>
                    <input type="number" name="duration" value="5" min="1" max="30" class="w-full border rounded-lg px-3 py-2">
                </div>
                <button type="submit" name="add_story" class="w-full bg-gradient-to-r from-pink-500 to-purple-600 text-white px-6 py-3 rounded-lg font-bold">
                    <i class="fas fa-plus ml-2"></i>إضافة
                </button>
            </form>
        </div>
    </div>
    
    <script>
    function previewImage(input) {
        const preview = document.getElementById('preview');
        const previewContainer = document.getElementById('imagePreview');
        
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                preview.src = e.target.result;
                previewContainer.classList.remove('hidden');
            }
            
            reader.readAsDataURL(input.files[0]);
        }
    }
    </script>
</body>
</html>
