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

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

global $pdo;
$message = '';

// Handle Delete Banner
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    // Database se image ka naam nikal kar folder se delete karna achi practice hai
    $stmt = $pdo->prepare("SELECT image FROM banners WHERE id = ?");
    $stmt->execute([$id]);
    $img = $stmt->fetchColumn();
    
    if($img && file_exists("../assets/images/banners/" . $img)) {
        unlink("../assets/images/banners/" . $img);
    }
    
    $pdo->prepare("DELETE FROM banners WHERE id = ?")->execute([$id]);
    $message = "Banner Deleted Successfully!";
}

// Handle Upload Banner
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['banner_img'])) {
    $title = $_POST['title'];
    
    $fileName = time() . '_' . basename($_FILES['banner_img']['name']);
    $targetDir = "../assets/images/banners/";
    
    // Check if folder exists, if not create it
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $targetFilePath = $targetDir . $fileName;

    if (move_uploaded_file($_FILES['banner_img']['tmp_name'], $targetFilePath)) {
        $pdo->prepare("INSERT INTO banners (title, image, is_active) VALUES (?, ?, 1)")->execute([$title, $fileName]);
        $message = "Banner Uploaded Successfully!";
    } else {
        $message = "File upload failed. Check folder permissions (0755 or 0777).";
    }
}

// Fetch Banners
$banners = $pdo->query("SELECT * FROM banners ORDER BY id DESC")->fetchAll();

$pageTitle = 'Home Banners';
require_once 'includes/header.php';
?>
<style>.banner-preview { width: 140px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.08); }</style>
<div class="custom-card">
    <div class="custom-card-header"><i class="fas fa-images me-2"></i> Manage Home Banners</div>
    <div class="p-4">
        <?php if($message): ?>
            <div class="alert alert-info fw-bold"><i class="fas fa-info-circle"></i> <?= htmlspecialchars($message) ?></div>
        <?php endif; ?>

        <div class="p-4 mb-4 rounded-3" style="background:#f8f9fa;">
            <form method="POST" enctype="multipart/form-data" class="row align-items-end">
                <div class="col-md-4">
                    <label class="form-label fw-bold">Banner Title (Optional)</label>
                    <input type="text" name="title" class="form-control" placeholder="e.g. Welcome Bonus">
                </div>
                <div class="col-md-5">
                    <label class="form-label fw-bold">Select Image (Ratio 3:1 works best)</label>
                    <input type="file" name="banner_img" class="form-control" accept="image/png, image/jpeg, image/jpg" required>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-success w-100 fw-bold"><i class="fas fa-upload"></i> Upload Banner</button>
                </div>
            </form>
        </div>

        <div class="custom-card p-0 mt-4">
            <table class="table table-hover mb-0">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Preview</th>
                        <th>Title</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($banners)): foreach($banners as $b): ?>
                    <tr class="align-middle">
                        <td>#<?= $b['id'] ?></td>
                        <td><img src="../assets/images/banners/<?= htmlspecialchars($b['image']) ?>" class="banner-preview"></td>
                        <td class="fw-bold"><?= htmlspecialchars($b['title']) ?></td>
                        <td><span class="badge bg-success">Active</span></td>
                        <td>
                            <a href="banners.php?delete=<?= $b['id'] ?>" class="btn btn-sm btn-danger fw-bold" onclick="return confirm('Delete this banner?');"><i class="fas fa-trash"></i> Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                    <tr><td colspan="5" class="text-center py-4">No banners found. Upload one!</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php require_once 'includes/footer.php'; ?>