<?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">
  
  <style>
    .pagination {
      justify-content: center;
      margin-top: 20px;
    }
    .page-link {
      color: #495057;
    }
    .page-item.active .page-link {
      background-color: #0d6efd;
      border-color: #0d6efd;
    }
  </style>
</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">Wallpapers</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>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-->

  <main id="main" class="main">
    <div class="container-fluid mt-4">
      <h1 class="text-center text-md-start">Manage Wallpapers</h1>
      <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mb-3">
        <button class="btn btn-success btn-block" data-bs-toggle="modal" data-bs-target="#addModal">Add Wallpapers</button>
        <input type="text" id="searchInput" class="form-control w-50 mt-2 mt-md-0" placeholder="Search Ads..."
          onkeyup="searchTable()">
      </div>

      <div class="table-responsive">
        <table class="table table-bordered table-striped" id="adsTable">
          <thead class="table-dark">
            <tr>
              <th>ID</th>
              <th> Images</th>
              <th> Tittle</th>
              <th>Category Name</th>
              <th>Published date</th>
              <th>Publisher Name</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php
            // Enable error reporting for debugging
            error_reporting(E_ALL);
            ini_set('display_errors', 1);

            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }

            // Pagination configuration
            $records_per_page = 10;
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $offset = ($page - 1) * $records_per_page;

            // Get total number of records
            $count_sql = "SELECT COUNT(*) as total FROM appstores";
            $count_result = $conn->query($count_sql);
            $total_records = $count_result->fetch_assoc()['total'];
            $total_pages = ceil($total_records / $records_per_page);

            // Ensure page is within valid range
            if ($page < 1) $page = 1;
            if ($page > $total_pages && $total_pages > 0) $page = $total_pages;

            $sql = "SELECT id, name, advertiser_name, image1_clicks, image2_clicks, image1, image2, image1_link, image2_link, image1_long_url, image2_long_url FROM appstores LIMIT $offset, $records_per_page";
            $i = $offset + 1;

            if ($result = $conn->query($sql)) {
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        $id = $row['id'];
                        $name = htmlspecialchars($row['name']);
                        $image1 = htmlspecialchars($row['image1']);
                        $image2 = htmlspecialchars($row['image2']);
                        $advertiserName = htmlspecialchars($row['advertiser_name']);
                        $image1_link = htmlspecialchars($row['image1_link']);
                        $image2_link = htmlspecialchars($row['image2_link']);
                        $image1_clicks = $row['image1_clicks'];
                        $image2_clicks = $row['image2_clicks'];
                  ?>
            <tr>
              <td><?php echo $i; ?></td>
              <td class="text-center">
                <img src="upload/<?php echo $image1; ?>" alt="Image 1" class="img-fluid"
                  style="max-width: 80px; height: auto; margin-right: 5px;"></br>
                <?php 
                  // Ensure $image2 is not empty before exploding
                  if (!empty($image2)) {
                      $images2 = explode(",", $image2);

                      // Loop through and display each image
                      foreach ($images2 as $img) {
                          echo '<img src="upload/' . trim($img) . '" alt="Image 2" class="img-fluid" 
                              style="max-width: 80px; height: auto; margin-right: 5px;"><br>';
                      }
                  }
                ?>
              </td>
              <td class="text-break"><?php echo $name; ?></td>
              <td class="text-break"><?php echo !empty($advertiserName) ? $advertiserName : "N/A"; ?></td>
              <td class="text-break"><?php echo $image1_clicks; ?></td>
              <td class="text-break"><?php echo $image2_clicks; ?></td>
              <td class="d-flex flex-column flex-md-row">
                <button type="button" class="btn btn-warning btn-sm me-md-2 mb-2 mb-md-0" data-bs-toggle="modal"
                  data-bs-target="#editadsModal" data-id="<?php echo $id; ?>" data-name="<?php echo $name; ?>"
                  data-advertiser="<?php echo $advertiserName; ?>"
                  data-image1="<?php echo $image1; ?>" data-image2="<?php echo $image2; ?>"
                  data-image1_long_url="<?php echo htmlspecialchars($row['image1_long_url']); ?>"
                  data-image2_long_url="<?php echo htmlspecialchars($row['image2_long_url']); ?>">
                  Edit
                </button>
                <a href="delete.php?id=<?php echo $id; ?>" class="btn btn-danger btn-sm"
                  onclick="return confirm('Are you sure you want to delete this ad?');">
                  Delete
                </a>
              </td>
            </tr>
            <?php
                        $i++;
                    }
                } else {
                    echo "<tr><td colspan='7' class='text-center'>No records found.</td></tr>";
                }
            } else {
                echo "<tr><td colspan='7' class='text-center'>Error executing query: " . $conn->error . "</td></tr>";
            }
            ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <nav aria-label="Page navigation">
        <ul class="pagination">
          <!-- Previous Page Link -->
          <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
            <a class="page-link" href="?page=<?php echo $page - 1; ?>" aria-label="Previous">
              <span aria-hidden="true">&laquo;</span>
            </a>
          </li>

          <!-- Page Number Links -->
          <?php
          // Show page numbers
          $start_page = max(1, $page - 2);
          $end_page = min($total_pages, $page + 2);
          
          for ($p = $start_page; $p <= $end_page; $p++): 
          ?>
            <li class="page-item <?php echo $p == $page ? 'active' : ''; ?>">
              <a class="page-link" href="?page=<?php echo $p; ?>"><?php echo $p; ?></a>
            </li>
          <?php endfor; ?>

          <!-- Next Page Link -->
          <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
            <a class="page-link" href="?page=<?php echo $page + 1; ?>" aria-label="Next">
              <span aria-hidden="true">&raquo;</span>
            </a>
          </li>
        </ul>
      </nav>
      
      <!-- Page Info -->
      <div class="text-center text-muted">
        Page <?php echo $page; ?> of <?php echo $total_pages; ?> | 
        Showing <?php echo ($offset + 1); ?> - <?php echo min($offset + $records_per_page, $total_records); ?> of <?php echo $total_records; ?> records
      </div>
      <?php endif; ?>

      <script>
        function searchTable() {
          let input = document.getElementById("searchInput").value.toLowerCase();
          let table = document.getElementById("adsTable");
          let rows = table.getElementsByTagName("tr");

          for (let i = 1; i < rows.length; i++) { // Start from 1 to skip table header
            let cells = rows[i].getElementsByTagName("td");
            let found = false;

            for (let j = 0; j < cells.length; j++) {
              if (cells[j]) {
                let text = cells[j].textContent || cells[j].innerText;
                if (text.toLowerCase().indexOf(input) > -1) {
                  found = true;
                  break;
                }
              }
            }

            rows[i].style.display = found ? "" : "none";
          }
        }
      </script>

    </div>
  </main>

  <!-- Modal for adding an ad -->
  <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addeventLabel" aria-hidden="true">
    <div class="modal-dialog">
      <form action="crud.php" method="POST" enctype="multipart/form-data">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="addeventLabel">Add Wallpapers</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <!-- Image Input 1 -->
            <div class="mb-3">
              <label for="image1" class="form-label">Image </label>
              <input type="file" class="form-control" id="image1" name="image1" accept=".jpg,.jpeg,.png,.gif" required>
            </div>
            <div class="mb-3" id="imagePreviewContainer1" style="display:none;">
              <label class="form-label">Preview</label>
              <img id="imagePreview1" src="#" alt="Preview" style="width: 100px;">
            </div>

            <!-- Preview Container for Multiple Images -->
            <div class="mb-3" id="imagePreviewContainer2" style="display:none;">
              <label class="form-label">Preview</label>
              <div id="imagePreview2" style="display: flex; gap: 10px; flex-wrap: wrap;"></div>
            </div>

            <script>
              // Preview for Image 1
              document.getElementById('image1').addEventListener('change', function (event) {
                let previewContainer = document.getElementById('imagePreviewContainer1');
                let file = this.files[0];

                if (file) {
                  let reader = new FileReader();
                  reader.onload = function (e) {
                    document.getElementById('imagePreview1').src = e.target.result;
                    previewContainer.style.display = "block"; // Show preview container
                  };
                  reader.readAsDataURL(file);
                } else {
                  previewContainer.style.display = "none"; // Hide if no file is selected
                }
              });

              // Preview for Multiple Images (Image 2)
              document.getElementById('image2').addEventListener('change', function (event) {
                let previewContainer = document.getElementById('imagePreview2');
                let previewWrapper = document.getElementById('imagePreviewContainer2');
                previewContainer.innerHTML = ""; // Clear previous previews

                if (this.files.length > 0) {
                  previewWrapper.style.display = "block"; // Show preview container
                  Array.from(this.files).forEach(file => {
                    let reader = new FileReader();
                    reader.onload = function (e) {
                      let img = document.createElement('img');
                      img.src = e.target.result;
                      img.style.width = "100px";
                      img.style.marginRight = "10px";
                      previewContainer.appendChild(img);
                    };
                    reader.readAsDataURL(file);
                  });
                } else {
                  previewWrapper.style.display = "none"; // Hide if no files are selected
                }
              });
            </script>

            <!-- Package Name Input -->
            <div class="mb-3">
              <label for="name" class="form-label"> Name</label>
              <input type="text" class="form-control" id="name" name="name" placeholder="Enter Title " required>
            </div>

            <!-- Advertiser Name Input -->
            <div class="mb-3">
              <label for="advertiser" class="form-label">Category Name</label>
              <select class="form-control" id="advertiser" name="advertiser" required>
                <option value="">Select Advertiser</option>
                <?php
                include("db_config.php");
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }

                // Fetch names and short_codes from the advertiser table
                $sql = "SELECT name FROM advertiser";
                $result = $conn->query($sql);
                $shortCodes = [];

                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        echo '<option value="' . htmlspecialchars($row["name"]) . '" data-code="' . htmlspecialchars($row["short_code"]) . '">' . htmlspecialchars($row["name"]) . '</option>';
                    }
                }

                // Close the database connection
                $conn->close();
              ?>
              </select>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary" name="addads">Add Wallpapers</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <script>
    function previewImage(input, previewId, containerId) {
      const file = input.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
          document.getElementById(previewId).src = e.target.result;
          document.getElementById(containerId).style.display = 'block'; // Show preview container
        };
        reader.readAsDataURL(file);
      }
    }

    // Add event listeners to both file inputs
    document.getElementById('image1').addEventListener('change', function () {
      previewImage(this, 'imagePreview1', 'imagePreviewContainer1');
    });

    document.getElementById('image2').addEventListener('change', function () {
      previewImage(this, 'imagePreview2', 'imagePreviewContainer2');
    });
  </script>

  <!-- Edit ads Modal -->
  <div class="modal fade" id="editadsModal" tabindex="-1" aria-labelledby="editEventModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <form id="editEventForm" action="update.php" method="POST" enctype="multipart/form-data">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="editEventModalLabel">Edit</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <!-- Hidden field for ID -->
            <input type="hidden" id="editEventId" name="id">

            <!-- Image 1 -->
            <div class="mb-3">
              <label for="editEventImage1" class="form-label">Image 1</label>
              <input type="file" class="form-control" id="editEventImage1" name="image1" accept=".jpg,.jpeg,.png,.gif">
              <small>Current image: <img id="currentEventImage1" src="" style="width: 100px;"></small>
            </div>

            <!-- Title Input -->
            <div class="mb-3">
              <label for="editEventName" class="form-label">Title </label>
              <input type="text" class="form-control" id="editEventName" name="name">
            </div>

            <!-- Advertiser Name Input -->
            <div class="mb-3">
              <label for="advertiser" class="form-label">Category Name</label>
              <select class="form-control" id="advertiser" name="advertiser" required>
                <option value="">Select Advertiser</option>
                <?php
              include("db_config.php");
              // Check connection
              if ($conn->connect_error) {
                  die("Connection failed: " . $conn->connect_error);
              }

              // Fetch names and short_codes from the short_links table
              $sql = "SELECT name FROM advertiser";
              $result = $conn->query($sql);
              $shortCodes = [];

              if ($result->num_rows > 0) {
                  while ($row = $result->fetch_assoc()) {
                      echo '<option value="' . htmlspecialchars($row["name"]) . '" data-code="' . htmlspecialchars($row["short_code"]) . '">' . htmlspecialchars($row["name"]) . '</option>';
                  }
              }

              // Close the database connection
              $conn->close();
              ?>
              </select>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary" name="updateEvent">Update</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- Bootstrap JS and dependencies -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.0.9/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></script>

  <script>
    // Populate the modal with ads data
    $('#editadsModal').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget); // Button that triggered the modal
      var id = button.data('id');
      var name = button.data('name');
      var description = button.data('description');
      var advertiser = button.data('advertiser');
      var image1 = button.data('image1');
      var image2 = button.data('image2');
      var image1LongUrl = button.data('image1_long_url');
      var image2LongUrl = button.data('image2_long_url');

      var modal = $(this);
      modal.find('#editEventId').val(id);
      modal.find('#editEventName').val(name);
      modal.find('#editEventDescription').val(description);
      modal.find('#advertiser').val(advertiser);
      modal.find('#image1_long_url').val(image1LongUrl);
      modal.find('#image2_long_url').val(image2LongUrl);

      modal.find('#currentEventImage1').attr('src', 'upload/' + image1); // Set current image 1
      modal.find('#currentEventImage2').attr('src', 'upload/' + image2); // Set current image 2
    });
  </script>

  <!-- ======= 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>
</body>
</html>