<?php
session_start();
if (!isset($_SESSION['unohs'])) {
    header("location:index.php?msg=unauthorized");
    exit;
}
date_default_timezone_set("Asia/Kolkata");

include 'conn.php';

// ✅ Handle File Upload
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES['banner'])) {
    $banner = time() . "_" . basename($_FILES['banner']['name']);
    $target_dir = "/home/pcbt647z2qd0/public_html/tirnga.danzio.shop/banners/";
    $target_file = $target_dir . $banner;

    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($_FILES['banner']['type'], $allowed_types)) {
        exit;
    }

    if (move_uploaded_file($_FILES['banner']['tmp_name'], $target_file)) {
        $imagePath = "https://tirnga.danzio.shop/banners/" . $banner;
        $query = "INSERT INTO banners (bannerUrl, url) VALUES ('$imagePath', '')";
        mysqli_query($conn, $query);
    }
}

// ✅ Handle URL Update
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['updateLink'])) {
    $id = intval($_POST['id']);
    $redirectUrl = mysqli_real_escape_string($conn, $_POST['redirectUrl']);

    $query = "UPDATE banners SET url = '$redirectUrl' WHERE id = $id";
    mysqli_query($conn, $query);
}

// ✅ Handle Banner Delete
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['deleteBanner'])) {
    $id = intval($_POST['id']);

    // ✅ Get banner file path from database
    $result = mysqli_query($conn, "SELECT bannerUrl FROM banners WHERE id = $id");
    $row = mysqli_fetch_assoc($result);
    if ($row) {
        $filePath = str_replace("https://tirnga.danzio.shop/banners/", "/home/pcbt647z2qd0/public_html/tirnga.danzio.shop/banners/", $row['bannerUrl']);

        // ✅ Delete file from server
        if (file_exists($filePath)) {
            unlink($filePath);
        }

        // ✅ Delete record from database
        mysqli_query($conn, "DELETE FROM banners WHERE id = $id");
    }
}
?>



<?php include 'header.php'; ?>


    <body class="bg-light">
    <div class="container mt-5">
<!-- ✅ Upload New Banner -->
        <h2 class="mb-4 text-primary">Upload New Banner</h2>
        <form method="POST" enctype="multipart/form-data" class="p-4 bg-white shadow rounded">
            <div class="mb-3">
                <input type="file" name="banner" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>

        <!-- ✅ Update Only URL -->
        <h3 class="mt-5 text-success">Update Banner URL</h3>
        <form method="POST" class="p-4 bg-white shadow rounded">
            <div class="mb-3">
                <select name="id" class="form-select" required>
                    <option value="">Select Banner</option>
                    <?php
                    $banners = mysqli_query($conn, "SELECT * FROM banners ORDER BY id DESC");
                    while ($row = mysqli_fetch_assoc($banners)) {
                        echo '<option value="' . $row['id'] . '">' . $row['bannerUrl'] . '</option>';
                    }
                    ?>
                </select>
            </div>
            <div class="mb-3">
                <input type="text" name="redirectUrl" class="form-control" placeholder="Enter Redirect URL" required>
            </div>
            <button type="submit" name="updateLink" class="btn btn-success">Update</button>
        </form>

        <!-- ✅ Display All Banners with Delete Option -->
        <h3 class="mt-5 text-info">All Banners</h3>
        <div class="table-responsive bg-white shadow rounded p-3">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Banner</th>
                        <th>Redirect URL</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $banners = mysqli_query($conn, "SELECT * FROM banners ORDER BY id DESC");
                    while ($row = mysqli_fetch_assoc($banners)) { ?>
                        <tr>
                            <td><img src="<?php echo $row['bannerUrl']; ?>" alt="Banner" width="120"></td>
                            <td><a href="<?php echo $row['url']; ?>" target="_blank"><?php echo $row['url']; ?></a></td>
                            <td>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                    <button type="submit" name="deleteBanner" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')">Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    
    

<script>
    document.getElementById("bannerSelect").addEventListener("change", function() {
        let selectedOption = this.options[this.selectedIndex];
        let bannerUrl = selectedOption.getAttribute("data-url");
        document.getElementById("bannerUrl").value = bannerUrl;
    });
</script>

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