<?php
/**
 * IBVTE Admin - Manage Website Popup
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$flash = getFlashMessage();

// Ensure the popup_settings table exists
try {
    $db->query("CREATE TABLE IF NOT EXISTS popup_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        image_path VARCHAR(255) NULL,
        is_active TINYINT(1) DEFAULT 0,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {
    // Ignore if connection failed or table creation failed
}

// Fetch existing popup setting, or create a default one
try {
    $popup = $db->fetchOne("SELECT * FROM popup_settings ORDER BY id DESC LIMIT 1");
    if (!$popup) {
        $db->insert('popup_settings', ['image_path' => '', 'is_active' => 0]);
        $popup = $db->fetchOne("SELECT * FROM popup_settings ORDER BY id DESC LIMIT 1");
    }
} catch (Exception $e) {
    $popup = null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Auth()->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        redirectWithMessage('popup.php', 'Security session expired. Please try again.', 'danger');
    }

    $is_active = isset($_POST['is_active']) && $_POST['is_active'] === '1' ? 1 : 0;
    
    $updateData = ['is_active' => $is_active];

    // Handle File Upload (Image)
    $uploadDir = '../uploads/popup/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
    
    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowed)) {
            $imageName = time() . '_popup_' . bin2hex(random_bytes(4)) . '.' . $ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $imageName)) {
                $updateData['image_path'] = 'uploads/popup/' . $imageName;
            }
        } else {
            redirectWithMessage('popup.php', 'Invalid image format.', 'danger');
        }
    }

    if ($popup && isset($popup['id'])) {
        $db->update('popup_settings', $updateData, ['id' => $popup['id']]);
        redirectWithMessage('popup.php', 'Popup settings updated successfully.', 'success');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Website Popup - <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
</head>
<body>
    <?php include __DIR__ . '/../includes/admin_header.php'; ?>
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-window-restore me-2 text-primary"></i>Manage Website Popup</h2>
                </div>

                <?php if ($flash): ?>
                    <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm">
                        <?= htmlspecialchars($flash['message']) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="row">
                    <div class="col-lg-6">
                        <div class="card shadow-sm border-0 rounded-4">
                            <div class="card-header bg-white border-bottom py-3">
                                <h5 class="mb-0 fw-bold">Popup Configuration</h5>
                            </div>
                            <div class="card-body p-4">
                                <form method="POST" enctype="multipart/form-data">
                                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                                    
                                    <div class="mb-4">
                                        <label class="form-label fw-bold">Popup Status</label>
                                        <div class="form-check form-switch fs-5">
                                            <input class="form-check-input" type="checkbox" role="switch" name="is_active" value="1" id="popupActiveSwitch" <?= ($popup['is_active'] ?? 0) == 1 ? 'checked' : '' ?>>
                                            <label class="form-check-label fs-6 ms-2 mt-1" for="popupActiveSwitch">Enable Website Popup</label>
                                        </div>
                                        <small class="text-muted d-block mt-2">When enabled, the popup image will appear once per user session on the website.</small>
                                    </div>
                                    
                                    <hr>
                                    
                                    <div class="mb-4 mt-3">
                                        <label class="form-label fw-bold">Popup Image</label>
                                        <input type="file" name="image" class="form-control" accept="image/*">
                                        <small class="text-muted d-block mt-2">Leave empty to keep the current image. Supported formats: JPG, PNG, WEBP, GIF.</small>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary px-4 fw-bold">Save Settings</button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-6 mt-4 mt-lg-0">
                        <div class="card shadow-sm border-0 rounded-4">
                            <div class="card-header bg-white border-bottom py-3">
                                <h5 class="mb-0 fw-bold">Current Popup Preview</h5>
                            </div>
                            <div class="card-body p-4 text-center">
                                <?php if (!empty($popup['image_path'])): ?>
                                    <div class="position-relative d-inline-block border p-2 rounded bg-light">
                                        <img src="../<?= htmlspecialchars($popup['image_path']) ?>" class="img-fluid rounded shadow-sm" style="max-height: 400px;" alt="Current Popup Image">
                                        <?php if (($popup['is_active'] ?? 0) == 0): ?>
                                            <div class="position-absolute top-0 start-0 w-100 h-100 bg-dark bg-opacity-50 rounded d-flex align-items-center justify-content-center">
                                                <span class="badge bg-danger fs-5">Currently Inactive</span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="py-5 text-muted">
                                        <i class="fas fa-image fa-4x mb-3 text-light"></i>
                                        <h5>No image uploaded yet</h5>
                                        <p>Upload an image to see the preview here.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
