<?php
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: index.php"); // Redirect to login page if not logged in
    exit();
}
include("db_config.php");
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Dashboard - </title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="assets/img/favicon.png" rel="icon">
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link
    href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"
    rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
</head>

<body>

  <!-- ======= Header ======= -->
  <header id="header" class="header fixed-top d-flex align-items-center">

    <div class="d-flex align-items-center justify-content-between">
      <a href="index.php" class="logo d-flex align-items-center">
        <img src="assets/img/logo.png" alt="">
        <span class="d-none d-lg-block">ScApps</span>
      </a>
      <i class="bi bi-list toggle-sidebar-btn"></i>
    </div><!-- End Logo -->

    <div class="search-bar">
      <form class="search-form d-flex align-items-center" method="POST" action="#">
        <input type="text" name="query" placeholder="Search" title="Enter search keyword">
        <button type="submit" title="Search"><i class="bi bi-search"></i></button>
      </form>
    </div><!-- End Search Bar -->

    <nav class="header-nav ms-auto">
      <ul class="d-flex align-items-center">

        <li class="nav-item d-block d-lg-none">
          <a class="nav-link nav-icon search-bar-toggle " href="#">
            <i class="bi bi-search"></i>
          </a>
        </li><!-- End Search Icon-->


      </ul>
    </nav><!-- End Icons Navigation -->

  </header><!-- End Header -->

  <!-- ======= Sidebar ======= -->
  <aside id="sidebar" class="sidebar">

    <ul class="sidebar-nav" id="sidebar-nav">

      <li class="nav-item">
        <a class="nav-link " href="dashboard.php">
          <i class="bi bi-grid"></i>
          <span>Dashboard</span>
        </a>
      </li><!-- End Dashboard Nav -->

      <li class="nav-item">
        <a class="nav-link " href="advertiser.php">
          <i class="bi bi-layout-text-window-reverse"></i><span>Add Category</span>
        </a>
      </li><!-- End Tables Nav -->


      <li class="nav-item">
        <a class="nav-link " href="app.php">
          <i class="bi bi-layout-text-window-reverse"></i><span>Wallpapers</span>
        </a>
      </li><!-- End Tables Nav -->

      <!-- End Profile Page Nav -->
      <li class="nav-item">
        <a class="nav-link collapsed" href="logout.php">
          <i class="bi bi-box-arrow-in-right"></i>
          <span>Logout</span>
        </a>
      </li>
    </ul>
  </aside><!-- End Sidebar-->
 <?php
include('db_config.php');

// Handle Add/Update Advertiser (POST)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];

    // Validate input
    if (empty($name)) {
        echo "Please fill in all the fields.";
        exit();
    }

    // Check if it's an update or insert
    if (isset($_POST['id']) && !empty($_POST['id'])) {
        // Update existing record
        $id = $_POST['id'];
        $sql = "UPDATE advertiser SET name='$name' WHERE id=$id";
    } else {
        // Insert new record
        $sql = "INSERT INTO advertiser (name) VALUES ('$name')";
    }

    if ($conn->query($sql) === TRUE) {
        header('Location: advertiser.php');
        exit();
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Handle Delete functionality
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
    $id = $_GET['id'];
    
    // Delete the advertiser record from the database
    $sql = "DELETE FROM advertiser WHERE id=$id";
    
    if ($conn->query($sql) === TRUE) {
        header('Location: advertiser.php');
        exit();
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
?>

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

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advertiser Management</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
  </head>

  <body>
    <main id="main" class="main">
      <div class="container-fluid mt-10">
        <div class="container mt-5">
        <h1 class="text-center text-md-start">Add Category</h1>
          <div class="row mb-3">
            <!-- Button (Col for Small Screens) -->
             <div class="col-12 col-md-4 mb-2 mb-md-0">
               <button class="btn btn-success w-80" data-bs-toggle="modal" data-bs-target="#addAdvertiserModal">
                 Add Category
              </button>
            </div>

            <!-- Search Bar (Col for Small Screens) -->
             <div class="col-12 col-md-8">
              <input type="text" id="searchInput" class="form-control" placeholder="Search advertiser..." onkeyup="searchAdvertisers()">
             </div>
          </div>



          <!-- Add Advertiser Modal -->
          <div class="modal fade" id="addAdvertiserModal" tabindex="-1" aria-labelledby="addAdvertiserModalLabel"
            aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="addAdvertiserModalLabel">Add Category</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <!-- Form for adding new advertiser -->
                  <form action="advertiser.php" method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                      <label for="name" class="form-label">Categpry Name</label>
                      <input type="text" class="form-control" id="name" name="name" required />
                    </div>
                    <!-- <div class="mb-3">
                      <label for="image" class="form-label">Image</label>
                      <input type="file" class="form-control" id="image" name="image" required />
                    </div> -->
                    <button type="submit" class="btn btn-primary">Submit</button>
                  </form>
                </div>
              </div>
            </div>
          </div>

          <!-- Edit Advertiser Modal -->
          <div class="modal fade" id="editAdvertiserModal" tabindex="-1" aria-labelledby="editAdvertiserModalLabel"
            aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-body">
                  <!-- Form for editing advertiser -->
                  <form action="advertiser.php" method="POST" enctype="multipart/form-data">
                    <input type="hidden" id="edit-id" name="id" />
                    <div class="mb-3">
                      <label for="edit-name" class="form-label">Category Name</label>
                      <input type="text" class="form-control" id="edit-name" name="name" required />
                    </div>
                    <!-- <div class="mb-3">
                      <label for="edit-image" class="form-label">Image</label>
                      <input type="file" class="form-control" id="edit-image" name="image" />
                    </div> -->
                    <button type="submit" class="btn btn-primary">Submit</button>
                  </form>
                </div>
              </div>
            </div>
          </div>

          <hr>
<!-- Search Bar -->
<div class="mb-3">
 
</div>

<!-- Display Advertisers List -->
<h3>Advertisers List</h3>
<div class="table-responsive">
  <table class="table table-bordered" id="advertisersTable">
    <thead>
      <tr>
        <th>ID</th>
        <th>Caegory Name</th>
        <!-- <th>Image</th> -->
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
    <?php
// Fetch records from the database
$sql = "SELECT * FROM advertiser";
$result = $conn->query($sql);
$counter = 1;
while ($row = $result->fetch_assoc()) {
    echo "<tr>
        <td>{$counter}</td>
        <td class='advertiser-name'>{$row['name']}</td>
        <td>
            <button type='button' class='btn btn-warning btn-sm me-md-2 mb-2 mb-md-0' data-bs-toggle='modal' data-bs-target='#editAdvertiserModal'
                data-id='{$row['id']}' data-name='{$row['name']}'>
                Edit
            </button>
            <a href='advertiser.php?action=delete&id={$row['id']}' class='btn btn-danger btn-sm'>Delete</a>
        </td>
    </tr>";
    $counter++;
}
?>
    </tbody>
  </table>
</div>

<!-- JavaScript for Search -->
<script>
function searchAdvertisers() {
  let input = document.getElementById("searchInput").value.toLowerCase();
  let rows = document.querySelectorAll("#advertisersTable tbody tr");

  rows.forEach(row => {
    let name = row.querySelector(".advertiser-name").textContent.toLowerCase();
    if (name.includes(input)) {
      row.style.display = "";
    } else {
      row.style.display = "none";
    }
  });
}
</script>
        </div>
      </div>
    </main>

    <script>
      var editAdvertiserModal = document.getElementById('editAdvertiserModal');
      editAdvertiserModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget; // Button that triggered the modal
        var id = button.getAttribute('data-id');
        var name = button.getAttribute('data-name');
        var image = button.getAttribute('data-image');

        var modalId = editAdvertiserModal.querySelector('#edit-id');
        var modalName = editAdvertiserModal.querySelector('#edit-name');
        var modalImage = editAdvertiserModal.querySelector('#edit-image');

        modalId.value = id;
        modalName.value = name;
        modalImage.value = ''; // Reset the file input when editing

        // Optional: Update the image preview here if needed
        // You could show the current image in the modal (you can add an <img> tag for preview).
      });
    </script>

    <!-- Bootstrap JS and dependencies -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>

  </body>

  </html>

  <?php
$conn->close();
?>

  <!-- ======= Footer ======= -->
  <footer id="footer" class="footer">
    <div class="copyright">
      &copy; Copyright <strong><span>CodingSuresh</span></strong>. All Rights Reserved
    </div>
    <div class="credits">

      Designed by <a href="#">CodingSuresh</a>
    </div>
  </footer><!-- End Footer -->

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i
      class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/chart.js/chart.umd.js"></script>
  <script src="assets/vendor/echarts/echarts.min.js"></script>
  <script src="assets/vendor/quill/quill.js"></script>
  <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="assets/vendor/php-email-form/validate.js"></script>

  <!-- Template Main JS File -->
  <script src="assets/js/main.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <!-- Sweet Alert Script -->
  <script>
    function confirmDelete(id) {
      Swal.fire({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#d33",
        cancelButtonColor: "#3085d6",
        confirmButtonText: "Yes, delete it!"
      }).then((result) => {
        if (result.isConfirmed) {
          window.location.href = "advertiser.php?id=" + id + "&action=delete";
        }
      });
    }
  </script>


</body>

</html>