<?php
/**
 * Manage Popup Notice (Premium Light Green UI)
 */
require_once 'header.php';

$success = '';
$error = '';

$notice_dir = '../uploads/notices/';
if (!is_dir($notice_dir)) {
    mkdir($notice_dir, 0777, true);
}
@chmod($notice_dir, 0777);

// Form Submit Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_popup'])) {
    $content = trim($_POST['content']);
    $btn_text = trim($_POST['btn_text']);
    $btn_url = trim($_POST['btn_url']);
    $status = $_POST['status'];

    try {
        $stmt = $pdo->query("SELECT id, image FROM popup_notice ORDER BY id DESC LIMIT 1");
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        $image_name = $existing ? $existing['image'] : null;

        if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
            $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'])) {
                $new_name = 'popup_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['image']['tmp_name'], $notice_dir . $new_name)) {
                    @chmod($notice_dir . $new_name, 0644);
                    if ($existing && !empty($existing['image']) && file_exists($notice_dir . $existing['image'])) {
                        @unlink($notice_dir . $existing['image']);
                    }
                    $image_name = $new_name;
                } else {
                    $error = "Failed to upload image. Please check directory permissions.";
                }
            } else {
                $error = "Invalid image format. Allowed: JPG, PNG, WEBP, GIF.";
            }
        }

        if (isset($_POST['remove_image']) && $_POST['remove_image'] == '1') {
             if ($existing && !empty($existing['image']) && file_exists($notice_dir . $existing['image'])) {
                 @unlink($notice_dir . $existing['image']);
             }
             $image_name = null;
        }

        if (empty($error)) {
            if ($existing) {
                $update = $pdo->prepare("UPDATE popup_notice SET image=?, content=?, btn_text=?, btn_url=?, status=? WHERE id=?");
                $update->execute([$image_name, $content, $btn_text, $btn_url, $status, $existing['id']]);
            } else {
                $insert = $pdo->prepare("INSERT INTO popup_notice (image, content, btn_text, btn_url, status) VALUES (?, ?, ?, ?, ?)");
                $insert->execute([$image_name, $content, $btn_text, $btn_url, $status]);
            }
            $success = "Popup notice updated successfully!";
        }
    } catch (PDOException $e) {
        $error = "Database Error: " . $e->getMessage();
    }
}

// Fetch Current Data
try {
    $stmt = $pdo->query("SELECT * FROM popup_notice ORDER BY id DESC LIMIT 1");
    $popup = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $popup = false;
}

if (!$popup) {
    $popup = ['image' => '', 'content' => '', 'btn_text' => '', 'btn_url' => '', 'status' => 'inactive'];
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
    :root {
        --primary: #84cc16;
        --primary-hover: #65a30d;
        --bg-light: #f8fafc;
        --card-bg: #ffffff;
        --border: #e2e8f0;
        --text-main: #1e293b;
        --text-muted: #64748b;
    }

    body { background: var(--bg-light); color: var(--text-main); font-family: 'Inter', sans-serif; margin: 0;}
    
    .settings-container { max-width: 800px; margin: 0 auto; padding: 20px; }

    .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 15px; }
    .page-title { font-size: 1.5rem; font-weight: 800; color: var(--text-main); margin: 0; }
    
    .admin-card { 
        background: var(--card-bg); border-radius: 12px; padding: 25px; 
        border: 1px solid var(--border); margin-bottom: 20px; box-shadow: none; 
    }

    .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 5px; }
    .form-group { margin-bottom: 20px; }
    .form-label { display: block; font-size: 0.9rem; font-weight: 700; margin-bottom: 8px; color: var(--text-main); }
    
    .form-control { 
        width: 100%; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; 
        font-size: 0.95rem; transition: 0.2s; box-sizing: border-box; background: transparent;
    }
    .form-control:focus { border-color: var(--primary); outline: none; }
    
    .file-upload-box {
        border: 2px dashed var(--border); padding: 20px 15px; border-radius: 8px;
        text-align: center; background: #fafafa; cursor: pointer; position: relative; transition: 0.3s ease;
    }
    .file-upload-box:hover { border-color: var(--primary); background: #f4fce3; }
    .file-upload-box input[type="file"] {
        position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer;
    }
    .file-icon { color: var(--text-muted); margin-bottom: 10px; transition: 0.3s; }
    .file-upload-box:hover .file-icon { color: var(--primary); }

    .current-img { max-width: 100%; max-height: 150px; object-fit: contain; border-radius: 6px; border: 1px solid var(--border); margin-top: 10px; display: block; background: #fff;}
    .new-preview-img { max-width: 100%; max-height: 150px; object-fit: contain; border-radius: 6px; border: 2px solid var(--primary); display: block; background: #fff; margin-top: 10px;}

    .checkbox-wrap { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 0.85rem; color: #ef4444; font-weight: 600; }

    .btn-submit { 
        background: var(--primary); color: white; padding: 14px 28px; border: none; 
        border-radius: 8px; font-weight: 700; font-size: 1rem; cursor: pointer; 
        display: flex; align-items: center; justify-content: center; gap: 8px; 
        transition: 0.3s; width: 100%; margin-top: 10px; box-shadow: none;
    }
    .btn-submit:hover { background: var(--primary-hover); transform: none; }

    @media (max-width: 768px) {
        .form-grid { grid-template-columns: 1fr; gap: 0; }
        .page-header { flex-direction: column; align-items: flex-start; }
        .admin-card { padding: 20px 15px; }
        .settings-container { padding: 15px; }
    }
</style>

<div class="settings-container">
    <div class="page-header">
        <h1 class="page-title">Manage Popup Notice</h1>
    </div>

    <div class="admin-card">
        <form action="" method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
            <input type="hidden" name="update_popup" value="1">
            
            <div class="form-group">
                <label class="form-label">Popup Status</label>
                <select name="status" class="form-control" required>
                    <option value="active" <?php echo ($popup['status'] == 'active') ? 'selected' : ''; ?>>Active (Show to users)</option>
                    <option value="inactive" <?php echo ($popup['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive (Hidden)</option>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">Popup Image (Optional)</label>
                <div class="file-upload-box">
                    <svg class="file-icon" width="30" height="30" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                    <div style="font-weight: 600; font-size: 0.9rem; color: var(--text-main);">Click to Upload Image</div>
                    <input type="file" id="image_input" name="image" accept="image/*">
                </div>
                <div id="image_preview"></div>
                
                <?php if(!empty($popup['image'])): ?>
                    <img src="../uploads/notices/<?php echo htmlspecialchars($popup['image']); ?>" class="current-img" alt="Current Image">
                    <div class="checkbox-wrap">
                        <input type="checkbox" name="remove_image" value="1" id="remove_img">
                        <label for="remove_img">Delete current image</label>
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label class="form-label">Popup Content Text (Optional)</label>
                <textarea name="content" class="form-control" rows="4" style="resize: vertical;" placeholder="Write your announcement or notice here..."><?php echo htmlspecialchars($popup['content'], ENT_QUOTES, 'UTF-8'); ?></textarea>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Button Name (Optional)</label>
                    <input type="text" name="btn_text" class="form-control" value="<?php echo htmlspecialchars($popup['btn_text'], ENT_QUOTES, 'UTF-8'); ?>" placeholder="e.g. Join Now">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Button URL (Optional)</label>
                    <input type="url" name="btn_url" class="form-control" value="<?php echo htmlspecialchars($popup['btn_url'], ENT_QUOTES, 'UTF-8'); ?>" placeholder="https://example.com">
                </div>
            </div>

            <button type="submit" class="btn-submit">
                <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                Save Settings
            </button>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script>
    <?php if($success): ?>
    Toastify({
        text: "<?php echo addslashes($success); ?>",
        duration: 3000,
        gravity: "top", 
        position: "center",
        className: "toast-success",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    <?php if($error): ?>
    Toastify({
        text: "<?php echo addslashes($error); ?>",
        duration: 4000,
        gravity: "top", 
        position: "center",
        className: "toast-error",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    document.getElementById('image_input').addEventListener('change', function(e) {
        const preview = document.getElementById('image_preview');
        preview.innerHTML = '';
        if (this.files && this.files[0]) {
            const file = this.files[0];
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.className = 'new-preview-img';
                    preview.appendChild(img);
                }
                reader.readAsDataURL(file);
            }
        }
    });
</script>

<?php require_once 'footer.php'; ?>
