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

// Admin Auth Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

global $pdo;
$message = '';
$msg_type = 'success';

// Handle Form Submit for Poster Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['promo_poster'])) {
    
    $uploadDir = '../assets/images/';
    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0777, true);
    }

    if ($_FILES['promo_poster']['error'] === UPLOAD_ERR_OK) {
        $fileName = 'poster_' . time() . '_' . basename($_FILES['promo_poster']['name']);
        $targetFilePath = $uploadDir . $fileName;
        
        $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
        $allowTypes = array('jpg', 'png', 'jpeg', 'webp');
        
        if (in_array($fileType, $allowTypes)) {
            if (move_uploaded_file($_FILES['promo_poster']['tmp_name'], $targetFilePath)) {
                $dbPath = 'assets/images/' . $fileName; 
                
                // Update or Insert into site_settings
                $stmt = $pdo->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_key = 'promo_poster'");
                $stmt->execute([$dbPath]);
                if ($stmt->rowCount() == 0) {
                    $pdo->prepare("INSERT IGNORE INTO site_settings (setting_key, setting_value) VALUES ('promo_poster', ?)")->execute([$dbPath]);
                }
                $message = "Promotion Poster uploaded successfully!";
            } else {
                $message = "Failed to upload image.";
                $msg_type = "error";
            }
        } else {
            $message = "Only JPG, JPEG, PNG, WEBP files are allowed.";
            $msg_type = "error";
        }
    }
}

// Fetch Current Poster
$stmt = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'promo_poster'");
$current_poster = $stmt->fetchColumn();

$pageTitle = "Manage Promotion Poster";
require_once 'includes/header.php';
?>

<div class="container-fluid px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold text-dark mb-0"><i class="fas fa-bullhorn text-danger me-2"></i> Manage Promotion Poster</h4>
    </div>

    <?php if($message): ?>
        <div class="alert alert-<?= $msg_type === 'success' ? 'success' : 'danger' ?> fw-bold">
            <i class="fas fa-info-circle"></i> <?= $message ?>
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm rounded-4">
                <div class="card-header bg-dark text-white fw-bold py-3">
                    <i class="fas fa-image text-warning"></i> Upload Invite Poster
                </div>
                <div class="card-body p-4">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="mb-4">
                            <label class="form-label fw-bold">Select Background Poster Image</label>
                            <input type="file" name="promo_poster" class="form-control" accept="image/*" required>
                            <small class="text-muted d-block mt-2">Recommended size: 800x1200px (Portrait). System will automatically generate and place the user's QR code in the middle of this poster.</small>
                        </div>
                        <button type="submit" class="btn btn-primary fw-bold px-4 py-2 w-100">
                            <i class="fas fa-upload"></i> Upload & Save
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card border-0 shadow-sm rounded-4">
                <div class="card-header bg-white fw-bold py-3">
                    Current Poster Preview
                </div>
                <div class="card-body text-center bg-light">
                    <?php if($current_poster): ?>
                        <img src="../<?= htmlspecialchars($current_poster) ?>" style="max-width: 100%; max-height: 400px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.2);">
                    <?php else: ?>
                        <div class="py-5 text-muted">
                            <i class="fas fa-image fs-1 mb-3 opacity-25"></i>
                            <h5>No poster uploaded yet.</h5>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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