<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

session_start();
require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Handle deletion
if (isset($_GET['del'])) {
    if (!has_permission('manage_banners')) {
        $_SESSION['error'] = "You do not have permission to delete banners.";
        header('location: manage-banners.php');
        exit();
    }
    $bannerId = intval($_GET['id']);

    // Get image filename to delete from server
    $query = mysqli_query($con, "SELECT image FROM sliders WHERE id = $bannerId");
    $row = mysqli_fetch_array($query);
    if ($row) {
        $imagePath = "../assets/images/sliders/" . $row['image'];
        if (file_exists($imagePath)) {
            unlink($imagePath);
        }
    }

    mysqli_query($con, "DELETE FROM sliders WHERE id = $bannerId");
    $_SESSION['msg'] = "Banner deleted successfully!";
    header('location: manage-banners.php');
    exit();
}

// Handle upload
if (isset($_POST['submit'])) {
    if (!has_permission('manage_banners')) {
        $_SESSION['error'] = "You do not have permission to upload banners.";
        header('location: manage-banners.php');
        exit();
    }
    $title = mysqli_real_escape_string($con, $_POST['title']);
    $link = mysqli_real_escape_string($con, $_POST['link']);
    $image = $_FILES["banner"]["name"];

    // Create directory if not exists
    if (!file_exists("../assets/images/sliders/")) {
        mkdir("../assets/images/sliders/", 0777, true);
    }

    // Rename image to avoid conflicts
    $extension = substr($image, strrpos($image, '.'));
    $newImageName = time() . "_" . rand(1000, 9999) . $extension;

    move_uploaded_file($_FILES["banner"]["tmp_name"], "../assets/images/sliders/" . $newImageName);

    $query = mysqli_query($con, "INSERT INTO sliders (image, title, link) VALUES ('$newImageName', '$title', '$link')");
    if ($query) {
        $_SESSION['msg'] = "Banner uploaded successfully!";
    } else {
        $_SESSION['error'] = "Something went wrong. Please try again.";
    }
    header('location: manage-banners.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Manage Banners - Admin Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"
        crossorigin="anonymous"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-image me-2"></i> Manage Banners</h1>
                            <p>Control image carousel on the home page</p>
                        </div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadBannerModal">
                            <i class="fas fa-plus me-2"></i> Add New Banner
                        </button>
                    </div>

                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <?php if (isset($_SESSION['error'])) { ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?php echo $_SESSION['error'];
                            unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <div class="table-card">
                        <table class="table table-hover" id="datatablesSimple">
                            <thead>
                                <tr>
                                    <th width="5%">#</th>
                                    <th>Image Preview</th>
                                    <th>Title</th>
                                    <th>Link</th>
                                    <th>Created At</th>
                                    <th width="10%">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $query = mysqli_query($con, "SELECT * FROM sliders ORDER BY id DESC");
                                $cnt = 1;
                                while ($row = mysqli_fetch_array($query)) {
                                    ?>
                                    <tr>
                                        <td>
                                            <?php echo $cnt; ?>
                                        </td>
                                        <td>
                                            <img src="../assets/images/sliders/<?php echo htmlentities($row['image']); ?>"
                                                alt="Banner" style="max-height: 100px; border-radius: 8px;">
                                        </td>
                                        <td>
                                            <?php echo htmlentities($row['title']); ?>
                                        </td>
                                        <td><small class="text-muted">
                                                <?php echo htmlentities($row['link']); ?>
                                            </small></td>
                                        <td>
                                            <?php echo date('M d, Y', strtotime($row['creation_date'])); ?>
                                        </td>
                                        <td>
                                            <a href="manage-banners.php?id=<?php echo $row['id']; ?>&del=delete"
                                                class="btn btn-sm btn-outline-danger" title="Delete"
                                                onclick="return confirm('Are you sure you want to delete this banner?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php $cnt++;
                                } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>

            <!-- Upload Modal -->
            <div class="modal fade" id="uploadBannerModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Add New Banner Image</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <form method="post" enctype="multipart/form-data">
                            <div class="modal-body">
                                <div class="mb-3">
                                    <label class="form-label">Select Image <span class="text-danger">*</span></label>
                                    <input type="file" name="banner" class="form-control" required accept="image/*">
                                    <small class="text-muted">Recommended size: 1200x400px</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Banner Title (Optional)</label>
                                    <input type="text" name="title" class="form-control"
                                        placeholder="Flash Sale 50% Off">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Link URL (Optional)</label>
                                    <input type="text" name="link" class="form-control" placeholder="shop.php?cid=1">
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" name="submit" class="btn btn-primary">Upload Banner</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        crossorigin="anonymous"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" crossorigin="anonymous"></script>
    <script src="js/datatables-simple-demo.js"></script>
</body>

</html>
