<?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 = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['story_image'])) {
    try {
        $title = $_POST['title'] ?? 'استوري جديد';
        $duration = $_POST['duration'] ?? 5;
        
        if ($_FILES['story_image']['error'] === 0) {
            $upload_dir = '../../uploads/stories/';
            if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $ext = pathinfo($_FILES['story_image']['name'], PATHINFO_EXTENSION);
            $filename = 'story_' . time() . '.' . $ext;
            
            if (move_uploaded_file($_FILES['story_image']['tmp_name'], $upload_dir . $filename)) {
                $query = "INSERT INTO stories (title, image, duration, created_by, is_active) VALUES (?, ?, ?, ?, 1)";
                $stmt = $db->prepare($query);
                $stmt->execute([$title, 'uploads/stories/' . $filename, $duration, $_SESSION['user_id']]);
                
                // إرجاع JSON للاستجابة السريعة
                if (isset($_POST['ajax'])) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'message' => 'تم الرفع بنجاح!']);
                    exit;
                }
                
                $message = 'success';
            }
        }
    } catch (Exception $e) {
        if (isset($_POST['ajax'])) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            exit;
        }
        $message = 'error';
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>رفع استوري</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.1/cropper.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .upload-container {
            background: white;
            border-radius: 20px;
            padding: 30px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .header h1 {
            font-size: 28px;
            color: #333;
            margin-bottom: 10px;
        }
        .header p {
            color: #666;
            font-size: 14px;
        }
        .upload-area {
            border: 3px dashed #ddd;
            border-radius: 15px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            position: relative;
            overflow: hidden;
        }
        .upload-area:hover {
            border-color: #667eea;
            background: #f8f9ff;
        }
        .upload-area.dragover {
            border-color: #667eea;
            background: #f0f3ff;
        }
        .upload-icon {
            font-size: 60px;
            color: #667eea;
            margin-bottom: 15px;
        }
        .upload-text {
            color: #666;
            font-size: 16px;
            margin-bottom: 10px;
        }
        .upload-hint {
            color: #999;
            font-size: 12px;
        }
        #fileInput {
            display: none;
        }
        .preview-container {
            display: none;
            margin-top: 20px;
        }
        .preview-image {
            width: 100%;
            max-height: 400px;
            object-fit: contain;
            border-radius: 15px;
            margin-bottom: 15px;
        }
        .crop-container {
            max-height: 400px;
            margin-bottom: 15px;
            border-radius: 15px;
            overflow: hidden;
        }
        .crop-tools {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        .crop-btn {
            padding: 8px 16px;
            border: 2px solid #667eea;
            background: white;
            color: #667eea;
            border-radius: 8px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .crop-btn:hover {
            background: #667eea;
            color: white;
        }
        .crop-btn.active {
            background: #667eea;
            color: white;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }
        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 16px;
            transition: border 0.3s;
        }
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }
        .btn-group {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        .btn {
            flex: 1;
            padding: 15px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }
        .btn-secondary {
            background: #f0f0f0;
            color: #666;
        }
        .btn-secondary:hover {
            background: #e0e0e0;
        }
        .progress-bar {
            display: none;
            height: 6px;
            background: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            margin-top: 15px;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s;
        }
        .success-message, .error-message {
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
            font-weight: 600;
        }
        .success-message {
            background: #d4edda;
            color: #155724;
        }
        .error-message {
            background: #f8d7da;
            color: #721c24;
        }
        @media (max-width: 600px) {
            .upload-container {
                padding: 20px;
            }
            .header h1 {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="upload-container">
        <div class="header">
            <h1>📸 رفع استوري</h1>
            <p>اختر صورة أو اسحبها هنا</p>
        </div>

        <?php if ($message === 'success'): ?>
            <div class="success-message">✅ تم رفع الاستوري بنجاح!</div>
        <?php elseif ($message === 'error'): ?>
            <div class="error-message">❌ حدث خطأ أثناء الرفع</div>
        <?php endif; ?>

        <form id="uploadForm" method="POST" enctype="multipart/form-data">
            <div class="upload-area" id="uploadArea" onclick="document.getElementById('fileInput').click()">
                <div class="upload-icon">📷</div>
                <div class="upload-text">اضغط للاختيار أو اسحب الصورة</div>
                <div class="upload-hint">JPG, PNG (أفضل مقاس: 1080×1920)</div>
                <input type="file" id="fileInput" name="story_image" accept="image/*" capture="environment">
            </div>

            <div class="preview-container" id="previewContainer">
                <div class="crop-container">
                    <img id="previewImage" class="preview-image">
                </div>
                
                <div class="crop-tools" id="cropTools">
                    <button type="button" class="crop-btn" onclick="setCropRatio(9/16)" title="استوري">
                        <span>📱 9:16</span>
                    </button>
                    <button type="button" class="crop-btn" onclick="setCropRatio(1)" title="مربع">
                        <span>⬜ 1:1</span>
                    </button>
                    <button type="button" class="crop-btn" onclick="setCropRatio(4/3)" title="عادي">
                        <span>📷 4:3</span>
                    </button>
                    <button type="button" class="crop-btn" onclick="setCropRatio(16/9)" title="عريض">
                        <span>🖼️ 16:9</span>
                    </button>
                    <button type="button" class="crop-btn" onclick="rotateCrop(-90)" title="تدوير يسار">
                        <span>↶</span>
                    </button>
                    <button type="button" class="crop-btn" onclick="rotateCrop(90)" title="تدوير يمين">
                        <span>↷</span>
                    </button>
                    <button type="button" class="crop-btn" onclick="flipCrop('horizontal')" title="قلب أفقي">
                        <span>↔️</span>
                    </button>
                    <button type="button" class="crop-btn" onclick="resetCrop()" title="إعادة تعيين">
                        <span>🔄</span>
                    </button>
                </div>
                
                <div class="form-group">
                    <label>العنوان</label>
                    <input type="text" name="title" id="titleInput" placeholder="عنوان الاستوري..." value="استوري جديد">
                </div>

                <div class="form-group">
                    <label>المدة (ثواني)</label>
                    <input type="number" name="duration" value="5" min="1" max="30">
                </div>

                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">إلغاء</button>
                    <button type="submit" class="btn btn-primary" id="uploadBtn">
                        <span id="btnText">نشر الاستوري</span>
                    </button>
                </div>

                <div class="progress-bar" id="progressBar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
            </div>
        </form>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.1/cropper.min.js"></script>
    <script>
        const fileInput = document.getElementById('fileInput');
        const uploadArea = document.getElementById('uploadArea');
        const previewContainer = document.getElementById('previewContainer');
        const previewImage = document.getElementById('previewImage');
        const uploadForm = document.getElementById('uploadForm');
        const progressBar = document.getElementById('progressBar');
        const progressFill = document.getElementById('progressFill');
        const uploadBtn = document.getElementById('uploadBtn');
        const btnText = document.getElementById('btnText');
        
        let cropper = null;
        let scaleX = 1;
        let scaleY = 1;

        // معالجة اختيار الملف
        fileInput.addEventListener('change', handleFileSelect);

        // Drag & Drop
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                handleFileSelect();
            }
        });

        function handleFileSelect() {
            const file = fileInput.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    previewImage.src = e.target.result;
                    uploadArea.style.display = 'none';
                    previewContainer.style.display = 'block';
                    
                    // تهيئة Cropper
                    if (cropper) {
                        cropper.destroy();
                    }
                    
                    cropper = new Cropper(previewImage, {
                        aspectRatio: 9 / 16, // نسبة الاستوري الافتراضية
                        viewMode: 1,
                        dragMode: 'move',
                        autoCropArea: 1,
                        restore: false,
                        guides: true,
                        center: true,
                        highlight: false,
                        cropBoxMovable: true,
                        cropBoxResizable: true,
                        toggleDragModeOnDblclick: false,
                    });
                };
                reader.readAsDataURL(file);
            }
        }
        
        // دوال التحكم بالقص
        function setCropRatio(ratio) {
            if (cropper) {
                cropper.setAspectRatio(ratio);
            }
        }
        
        function rotateCrop(degree) {
            if (cropper) {
                cropper.rotate(degree);
            }
        }
        
        function flipCrop(direction) {
            if (cropper) {
                if (direction === 'horizontal') {
                    scaleX = scaleX === 1 ? -1 : 1;
                    cropper.scaleX(scaleX);
                } else {
                    scaleY = scaleY === 1 ? -1 : 1;
                    cropper.scaleY(scaleY);
                }
            }
        }
        
        function resetCrop() {
            if (cropper) {
                cropper.reset();
                scaleX = 1;
                scaleY = 1;
            }
        }

        function resetForm() {
            if (cropper) {
                cropper.destroy();
                cropper = null;
            }
            fileInput.value = '';
            uploadArea.style.display = 'block';
            previewContainer.style.display = 'none';
            progressBar.style.display = 'none';
            progressFill.style.width = '0%';
            scaleX = 1;
            scaleY = 1;
        }

        // رفع بـ AJAX
        uploadForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            // الحصول على الصورة المقصوصة
            if (cropper) {
                const canvas = cropper.getCroppedCanvas({
                    maxWidth: 1080,
                    maxHeight: 1920,
                    fillColor: '#fff',
                    imageSmoothingEnabled: true,
                    imageSmoothingQuality: 'high',
                });
                
                // تحويل Canvas إلى Blob
                canvas.toBlob(async (blob) => {
                    const formData = new FormData();
                    formData.append('story_image', blob, 'story.jpg');
                    formData.append('title', document.getElementById('titleInput').value);
                    formData.append('duration', document.querySelector('input[name="duration"]').value);
                    formData.append('ajax', '1');
                    
                    await uploadImage(formData);
                }, 'image/jpeg', 0.9);
            } else {
                const formData = new FormData(uploadForm);
                formData.append('ajax', '1');
                await uploadImage(formData);
            }
        });
        
        async function uploadImage(formData) {
            
                uploadBtn.disabled = true;
                btnText.textContent = 'جاري الرفع...';
                progressBar.style.display = 'block';
                
                // محاكاة التقدم
                let progress = 0;
                const progressInterval = setInterval(() => {
                    progress += 10;
                    if (progress <= 90) {
                        progressFill.style.width = progress + '%';
                    }
                }, 200);
                
                try {
                    const response = await fetch('upload.php', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    clearInterval(progressInterval);
                    progressFill.style.width = '100%';
                    
                    if (result.success) {
                        btnText.textContent = '✅ تم الرفع!';
                        setTimeout(() => {
                            window.location.href = 'index.php';
                        }, 1000);
                    } else {
                        throw new Error(result.message);
                    }
                } catch (error) {
                    clearInterval(progressInterval);
                    alert('حدث خطأ: ' + error.message);
                    uploadBtn.disabled = false;
                    btnText.textContent = 'نشر الاستوري';
                    progressBar.style.display = 'none';
                }
        }
    </script>
</body>
</html>
