<?php
session_start();
require_once "config.php";

// Ensure only admin can access
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== 'admin') {
    header("Location: login.php");
    exit;
}

$admin_id = $_SESSION["user_id"];

// Fetch admin info
$admin_sql = $conn->prepare("SELECT first_name, last_name, email, phone, address, image, balance, currency 
                             FROM users WHERE id = ?");
$admin_sql->bind_param("i", $admin_id);
$admin_sql->execute();
$admin_result = $admin_sql->get_result();
$admin_info = $admin_result->fetch_assoc();

$admin_wallet = $admin_info['balance'];
$admin_currency = $admin_info['currency'];

// Fetch summary counts
$total_users = $conn->query("SELECT COUNT(*) AS cnt FROM users")->fetch_assoc()['cnt'];
$total_properties = $conn->query("SELECT COUNT(*) AS cnt FROM properties")->fetch_assoc()['cnt'];
$total_adverts = $conn->query("SELECT COUNT(*) AS cnt FROM adverts")->fetch_assoc()['cnt'];
$total_transactions = $conn->query("SELECT COUNT(*) AS cnt FROM transactions")->fetch_assoc()['cnt'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin Dashboard</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <style>
    /* Global Styling */
    * { scroll-behavior: smooth; }
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: #f8f9fa;
      margin: 0;
      overflow-x: hidden;
    }
    .content {
      margin-left: 250px;
      padding: 20px;
      transition: margin-left 0.3s;
    }
    @media (max-width: 768px) {
      .content { margin-left: 0; }
    }
    .top-nav {
      background: #fff;
      padding: 10px 20px;
      border-bottom: 1px solid #ddd;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      position: sticky;
      top: 0;
      z-index: 900;
    }
    .top-nav img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-left: 10px;
    }
    .section {
      padding: 40px 20px;
      background: #fff;
      border-radius: 12px;
      margin-bottom: 30px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.05);
    }
    .quick-action .card {
      cursor: pointer;
      transition: transform 0.2s;
    }
    .quick-action .card:hover {
      transform: translateY(-5px);
    }
  </style>
</head>
<body>

<!-- Sidebar -->
<section id="sidebar">
  <style>
    #sidebar {
      position: fixed;
      top: 0; left: 0;
      width: 250px;
      height: 100%;
      background: #1e1e2f;
      color: #fff;
      transition: all 0.3s;
      overflow-y: auto;
      z-index: 1000;
    }
    #sidebar.collapsed { width: 70px; }
    #sidebar .logo {
      display: flex;
      align-items: center;
      padding: 15px;
      background: #151523;
    }
    #sidebar .logo img {
      width: 40px;
      margin-right: 10px;
      border-radius: 8px;
    }
    #sidebar .logo span {
      font-weight: bold;
      font-size: 18px;
      white-space: nowrap;
    }
    #sidebar .menu-item {
      padding: 15px 20px;
      display: flex;
      align-items: center;
      text-decoration: none;
      color: #adb5bd;
      transition: background 0.3s, color 0.3s;
    }
    #sidebar .menu-item:hover,
    #sidebar .menu-item.active {
      background: #2b2b40;
      color: #fff;
    }
    #sidebar .menu-item i { margin-right: 12px; font-size: 18px; }
    #sidebar .badge { margin-left: auto; font-size: 12px; }

    /* Icon Colors */
    .fa-users { color: #4dabf7; }
    .fa-building { color: #51cf66; }
    .fa-bullhorn { color: #fcc419; }
    .fa-exchange-alt { color: #ff6b6b; }
    .fa-user { color: #9775fa; }
    .fa-sign-out-alt { color: #ffa94d; }

    /* Collapsed View */
    #sidebar.collapsed .menu-item span { display: none; }
    #sidebar.collapsed .logo span { display: none; }
    #sidebar.collapsed .menu-item { justify-content: center; }
    #sidebar.collapsed .badge { display: none; }

    /* Hamburger */
    #hamburger {
      position: fixed;
      top: 15px; left: 15px;
      font-size: 24px;
      color: #1e1e2f;
      z-index: 1100;
      cursor: pointer;
      display: none;
    }
    @media (max-width: 768px) {
      #hamburger { display: block; }
      #sidebar { left: -250px; }
      #sidebar.active { left: 0; }
    }
  </style>

  <div class="logo">
    <img src="images/limac.jpeg" alt="Limac Groups">
    <span>Limac Groups</span>
  </div>

  <nav>
    <a href="#dashboard" class="menu-item active"><i class="fas fa-home text-info"></i><span>Dashboard</span></a> <br>
    <a href="#users" class="menu-item"><i class="fas fa-users"></i><span>Users</span><span class="badge bg-primary"><?php echo $total_users; ?></span></a> <br>
    <a href="#properties" class="menu-item"><i class="fas fa-building"></i><span>Properties</span><span class="badge bg-success"><?php echo $total_properties; ?></span></a> <br>
    <a href="#adverts" class="menu-item"><i class="fas fa-bullhorn"></i><span>Adverts</span><span class="badge bg-warning"><?php echo $total_adverts; ?></span></a> <br>
    <a href="#transactions" class="menu-item"><i class="fas fa-exchange-alt"></i><span>Transactions</span><span class="badge bg-danger"><?php echo $total_transactions; ?></span></a> <br>
    <a href="#profile" class="menu-item"><i class="fas fa-user"></i><span>Profile</span></a> <br>
    <a href="logout.php" class="menu-item"><i class="fas fa-sign-out-alt"></i><span>Logout</span></a>
  </nav>

  <script>
    const hamburger = document.createElement("div");
    hamburger.id = "hamburger";
    hamburger.innerHTML = '<i class="fas fa-bars"></i>';
    document.body.appendChild(hamburger);

    const sidebar = document.getElementById("sidebar");
    hamburger.addEventListener("click", () => {
      sidebar.classList.toggle("active");
    });

    // Active menu highlight
    document.querySelectorAll('#sidebar .menu-item').forEach(item => {
      item.addEventListener('click', function() {
        document.querySelectorAll('#sidebar .menu-item').forEach(i => i.classList.remove('active'));
        this.classList.add('active');
      });
    });
  </script>
</section>

<!-- Main Content -->
<div class="content">
  <!-- Top Nav -->
  <div class="top-nav">
    <span>Welcome, <?php echo htmlspecialchars($admin_info['first_name']); ?></span>
    <img src="uploads/<?php echo htmlspecialchars($admin_info['image']); ?>" alt="Admin">
  </div>

  <!-- Dashboard Section -->
  <div id="dashboard" class="section">
    <h3>Dashboard Overview</h3>
    <p>Wallet Balance: <strong><?php echo $admin_currency . " " . number_format($admin_wallet, 2); ?></strong></p>
  </div>

  <!-- Quick Actions -->
<!-- Quick Actions Section -->
<section id="quick-actions" class="py-5">
  <style>
    /* Section background and padding */
    #quick-actions {
      background: #f8f9fa;
      border-radius: 12px;
      padding: 40px 20px;
      margin-bottom: 30px;
    }

    #quick-actions h4 {
      text-align: center;
      margin-bottom: 30px;
      font-weight: 700;
      font-size: 1.8rem;
      color: #000;
    }

    /* Cards layout */
    #quick-actions .row { 
      justify-content: center; 
      gap: 20px;
    }

    /* Individual cards */
    #quick-actions .action-card {
      background: #2b2b40;
      border-radius: 12px;
      padding: 25px 10px;
      text-align: center;
      cursor: pointer;
      transition: transform 0.3s, box-shadow 0.3s, background 0.3s;
      flex: 1 1 200px;
      min-width: 180px;
      color: #fff;
    }
    #quick-actions .action-card:hover {
      transform: translateY(-7px);
      box-shadow: 0 10px 25px rgba(0,0,0,0.2);
      background: #4a6cf7;
    }

    #quick-actions .action-card i {
      font-size: 2rem;
      margin-bottom: 10px;
      transition: transform 0.3s;
    }
    #quick-actions .action-card:hover i {
      transform: scale(1.2);
    }

    #quick-actions .action-card h6 {
      margin: 0;
      font-weight: 600;
    }

    @media (max-width: 768px) {
      #quick-actions .row {
        flex-direction: column;
        align-items: center;
      }
    }
  </style>

  <h4>Quick Actions</h4>
  <div class="row">
    <!-- Add Staff 
    <div class="action-card" data-bs-toggle="modal" data-bs-target="#addStaffModal">
      <i class="fas fa-user-plus text-primary"></i>
      <h6>Add Staff</h6>
    </div> -->

    <!-- Add Property Card -->
      <div class="action-card" data-bs-toggle="modal" data-bs-target="#addPropertyModal">
    <i class="fas fa-building text-success"></i>
    <h6>Add Property</h6>
      </div>

    <!-- Create Advert -->
    <button type="button" class="action-card" data-bs-toggle="modal" data-bs-target="#createAdminAdvertModal">
  <i class="fas fa-bullhorn text-warning"></i>
  <h6>Create Advert</h6>
</button>


  </div>

  <!-- Modals -->
  <!-- Add Staff Modal -->
  <div class="modal fade" id="addStaffModal" tabindex="-1" aria-labelledby="addStaffModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <form action="process_users.php" method="POST">
          <div class="modal-header">
            <h5 class="modal-title" id="addStaffModalLabel">Add Staff</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <input type="hidden" name="role" value="staff">
            <div class="mb-3">
              <label>First Name</label>
              <input type="text" class="form-control" name="first_name" required>
            </div>
            <div class="mb-3">
              <label>Last Name</label>
              <input type="text" class="form-control" name="last_name" required>
            </div>
            <div class="mb-3">
              <label>Email</label>
              <input type="email" class="form-control" name="email" required>
            </div>
            <div class="mb-3">
              <label>Phone</label>
              <input type="text" class="form-control" name="phone" required>
            </div>
            <div class="mb-3">
              <label>Username</label>
              <input type="text" class="form-control" name="username" required>
            </div>
            <div class="mb-3">
              <label>Password</label>
              <input type="password" class="form-control" name="password" required>
            </div>
          </div>
          <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Add Staff</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Add Property Modal -->
<div class="modal fade" id="addPropertyModal" tabindex="-1" aria-labelledby="addPropertyModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form action="process_admin_property.php" method="POST" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title" id="addPropertyModalLabel">Add Admin Property</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <!-- Property Type -->
          <div class="mb-3">
            <label>Property Type</label>
            <select class="form-select" name="property_type" required>
              <option value="">Select type</option>
              <option value="estate">Estate</option>
              <option value="rental">Rental</option>
              <option value="sale">Sale</option>
            </select>
          </div>

          <!-- Description -->
          <div class="mb-3">
            <label>Description</label>
            <textarea class="form-control" name="description" rows="3" placeholder="Enter property description" required></textarea>
          </div>

          <!-- Main Property Image -->
          <div class="mb-3">
            <label>Main Property Image</label>
            <input type="file" class="form-control" name="property_image" accept="image/*" id="propertyImageInput" required>
            <img id="propertyImagePreview" src="" alt="Image Preview" style="display:none; width:100%; margin-top:10px; max-height:250px; object-fit:cover; border-radius:6px;">
          </div>

          <!-- Additional Images -->
          <div class="mb-3">
            <label>Additional Images (up to 5)</label>
            <input type="file" class="form-control" name="images[]" accept="image/*" id="additionalImagesInput" multiple>
            <div id="additionalImagesPreview" class="d-flex flex-wrap gap-2 mt-2"></div>
          </div>

          <!-- Video -->
          <div class="mb-3">
            <label>Property Video (optional)</label>
            <input type="file" class="form-control" name="video" accept="video/*" id="videoInput">
            <video id="videoPreview" style="display:none; width:100%; margin-top:10px; max-height:250px;" controls></video>
          </div>

          <!-- Price -->
          <div class="mb-3">
            <label>Price</label>
            <input type="number" class="form-control" name="price" placeholder="Enter price" required>
          </div>

          <!-- Location -->
          <div class="mb-3">
            <label>Location</label>
            <input type="text" class="form-control" name="location" placeholder="Enter location" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Add Property</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- JS for previews -->
<script>
document.addEventListener('DOMContentLoaded', function(){
  // Main image preview
  const imageInput = document.getElementById('propertyImageInput');
  const imagePreview = document.getElementById('propertyImagePreview');
  imageInput.addEventListener('change', function(){
    const file = this.files[0];
    if(file){
      const reader = new FileReader();
      reader.onload = function(e){
        imagePreview.src = e.target.result;
        imagePreview.style.display = 'block';
      }
      reader.readAsDataURL(file);
    } else {
      imagePreview.src = '';
      imagePreview.style.display = 'none';
    }
  });

  // Additional images preview
  const additionalInput = document.getElementById('additionalImagesInput');
  const additionalPreview = document.getElementById('additionalImagesPreview');
  additionalInput.addEventListener('change', function(){
    additionalPreview.innerHTML = '';
    const files = this.files;
    if(files.length > 5){
      alert('You can upload a maximum of 5 additional images.');
      this.value = '';
      return;
    }
    Array.from(files).forEach(file => {
      const reader = new FileReader();
      reader.onload = function(e){
        const img = document.createElement('img');
        img.src = e.target.result;
        img.style.width = '100px';
        img.style.height = '80px';
        img.style.objectFit = 'cover';
        img.style.borderRadius = '6px';
        additionalPreview.appendChild(img);
      }
      reader.readAsDataURL(file);
    });
  });

  // Video preview
  const videoInput = document.getElementById('videoInput');
  const videoPreview = document.getElementById('videoPreview');
  videoInput.addEventListener('change', function(){
    const file = this.files[0];
    if(file){
      const url = URL.createObjectURL(file);
      videoPreview.src = url;
      videoPreview.style.display = 'block';
    } else {
      videoPreview.src = '';
      videoPreview.style.display = 'none';
    }
  });
});
</script>



  <!-- Create Advert Modal -->
  <!-- Include jQuery first, then Select2 CSS & JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- Create Admin Advert Modal -->
<div class="modal fade" id="createAdminAdvertModal" tabindex="-1" aria-labelledby="createAdminAdvertModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form action="process_admin_advert.php" method="POST">
        <div class="modal-header">
          <h5 class="modal-title" id="createAdminAdvertModalLabel">Create Admin Advert</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

          <!-- Property Select with Select2 -->
          <div class="mb-3">
            <label>Select Property</label>
            <select name="admin_property_id" id="adminPropertySelect" required>
              <option value="" disabled selected>Choose a property</option>
              <?php
              $res = $conn->query("SELECT id, description, property_type, property_image, price, location FROM admin_properties ORDER BY created_at DESC");
              while($row = $res->fetch_assoc()):
              ?>
                <option 
                  value="<?= $row['id'] ?>" 
                  data-desc="<?= htmlspecialchars($row['description']) ?>"
                  data-price="<?= htmlspecialchars(number_format($row['price'],2)) ?>"
                  data-loc="<?= htmlspecialchars($row['location']) ?>"
                  data-img="<?= htmlspecialchars($row['property_image']) ?>"
                >
                  <?= htmlspecialchars($row['property_type'] . ' - ' . $row['description']) ?>
                </option>
              <?php endwhile; ?>
            </select>
          </div>

          <!-- Advert Location -->
          <div class="mb-3">
            <label for="location">Advert Location</label>
            <select class="form-select" name="location" id="location" required>
              <option value="homepage">Homepage</option>
              <option value="property_details">Property Details</option>
              <option value="dashboard">Dashboard</option>
            </select>
          </div>

          <!-- Start Date -->
          <div class="mb-3">
            <label for="start_date">Start Date</label>
            <input type="date" class="form-control" name="start_date" id="start_date" required>
          </div>

          <!-- End Date -->
          <div class="mb-3">
            <label for="end_date">End Date</label>
            <input type="date" class="form-control" name="end_date" id="end_date" required>
          </div>

          <!-- Preview -->
          <div id="advertPreview" style="display:none; margin-top:20px;">
            <h6>Preview:</h6>
            <div class="card border-warning p-3 d-flex flex-column flex-md-row align-items-center">
              <img id="previewImg" src="" alt="Property" style="width:150px; height:150px; object-fit:cover; margin-right:20px; margin-bottom:10px;">
              <div>
                <p id="previewProperty" class="mb-2"><strong>Description:</strong></p>
                <p id="previewPrice" class="mb-2"><strong>Price:</strong></p>
                <p id="previewPropLocation" class="mb-0"><strong>Location:</strong></p>
              </div>
            </div>
          </div>

        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-warning">Create Advert</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- JS for Select2 and Preview -->
<script>
$(document).ready(function() {
    // Initialize Select2
    $('#adminPropertySelect').select2({
        templateResult: formatProperty,
        templateSelection: formatProperty,
        dropdownParent: $('#createAdminAdvertModal')
    });

    function formatProperty(state) {
        if (!state.id) return state.text;
        var img = $(state.element).data('img');
        if(img){
            var $state = $('<span><img src="'+img+'" style="width:40px; height:40px; object-fit:cover; margin-right:8px;">'+state.text+'</span>');
            return $state;
        }
        return state.text;
    }

    // Update preview
    $('#adminPropertySelect').on('change', function() {
        var selected = $(this).find('option:selected');
        $('#advertPreview').show();
        $('#previewProperty').html("<strong>Description:</strong> " + selected.data('desc'));
        $('#previewPrice').html("<strong>Price:</strong> " + selected.data('price'));
        $('#previewPropLocation').html("<strong>Location:</strong> " + selected.data('loc'));
        $('#previewImg').attr('src', selected.data('img'));
    });
});
</script>


</section>



  <!-- Users Section -->
<div id="users" class="section">
  <h4 class="mb-4">Users</h4>

  <!-- Summary Cards -->
  <div class="row g-3 mb-4">
    <?php
      $staff_count   = $conn->query("SELECT COUNT(*) AS cnt FROM users WHERE subscription_plan='staff'")->fetch_assoc()['cnt'];
      $basic_count   = $conn->query("SELECT COUNT(*) AS cnt FROM users WHERE subscription_plan='basic'")->fetch_assoc()['cnt'];
      $gold_count    = $conn->query("SELECT COUNT(*) AS cnt FROM users WHERE subscription_plan='gold'")->fetch_assoc()['cnt'];
      $premium_count = $conn->query("SELECT COUNT(*) AS cnt FROM users WHERE subscription_plan='premium'")->fetch_assoc()['cnt'];
    ?>
   <!-- <div class="col-sm-6 col-md-3">
      <div class="card text-center shadow-sm p-3 bg-info text-white">
        <i class="fas fa-user-tie fa-2x mb-2"></i>
        <h6>Staff</h6>
        <p class="mb-0 fs-5"><?= $staff_count ?></p>
      </div>
    </div> -->
    <div class="col-sm-6 col-md-3">
      <div class="card text-center shadow-sm p-3 bg-primary text-white">
        <i class="fas fa-user fa-2x mb-2"></i>
        <h6>Basic</h6>
        <p class="mb-0 fs-5"><?= $basic_count ?></p>
      </div>
    </div>
    <div class="col-sm-6 col-md-3">
      <div class="card text-center shadow-sm p-3 bg-warning text-dark">
        <i class="fas fa-user-check fa-2x mb-2"></i>
        <h6>Gold</h6>
        <p class="mb-0 fs-5"><?= $gold_count ?></p>
      </div>
    </div>
    <div class="col-sm-6 col-md-3">
      <div class="card text-center shadow-sm p-3 bg-success text-white">
        <i class="fas fa-user-shield fa-2x mb-2"></i>
        <h6>Premium</h6>
        <p class="mb-0 fs-5"><?= $premium_count ?></p>
      </div>
    </div>
  </div>

  <!-- Filter -->
  <div class="mb-3 d-flex justify-content-between align-items-center">
    <span>Total Users: <?= $total_users - 1 ?></span>
    <select id="planFilter" class="form-select w-auto">
      <option value="">All Plans</option>
      <!--<option value="staff">Staff</option> -->
      <option value="basic">Basic</option>
      <option value="gold">Gold</option>
      <option value="premium">Premium</option>
    </select>
  </div>

  <!-- Users Table -->
  <div class="table-responsive">
    <table class="table table-striped table-bordered align-middle text-center" id="usersTable">
      <thead class="table-dark">
        <tr>
          <th>ID</th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Subscription</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody id="usersTableBody">
        <?php
        $perPage = 10;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $start = ($page - 1) * $perPage;

        $users_sql = $conn->prepare("SELECT id, first_name, last_name, subscription_plan, email, phone 
                                     FROM users WHERE id != ? ORDER BY id ASC LIMIT ?, ?");
        $users_sql->bind_param("iii", $admin_id, $start, $perPage);
        $users_sql->execute();
        $users_result = $users_sql->get_result();
        $counter = $start + 1;

        while($user = $users_result->fetch_assoc()):
        ?>
        <tr data-plan="<?= $user['subscription_plan'] ?>">
          <td><?= $counter++ ?></td>
          <td><?= htmlspecialchars($user['first_name']) ?></td>
          <td><?= htmlspecialchars($user['last_name']) ?></td>
          <td><?= ucfirst($user['subscription_plan']) ?></td>
          <td><?= htmlspecialchars($user['email']) ?></td>
          <td><?= htmlspecialchars($user['phone']) ?></td>
          <td>
            <button class="btn btn-sm btn-info me-1 view-btn" data-user='<?= json_encode($user) ?>'>View</button>
            <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $user['id'] ?>">Delete</button>

          </td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <nav>
    <ul class="pagination justify-content-center">
      <?php
        $totalUsersCount = $conn->query("SELECT COUNT(*) AS cnt FROM users WHERE id != $admin_id")->fetch_assoc()['cnt'];
        $totalPages = ceil($totalUsersCount / $perPage);

        for($i=1; $i<=$totalPages; $i++):
      ?>
        <li class="page-item <?= ($i==$page)?'active':'' ?>">
          <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
        </li>
      <?php endfor; ?>
    </ul>
  </nav>

  <!-- View Modal -->
  <div class="modal fade" id="viewModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header bg-info text-white">
          <h5 class="modal-title">User Details</h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <p><strong>Name:</strong> <span id="modalName"></span></p>
          <p><strong>Email:</strong> <span id="modalEmail"></span></p>
          <p><strong>Phone:</strong> <span id="modalPhone"></span></p>
          <p><strong>Subscription:</strong> <span id="modalPlan"></span></p>
        </div>
      </div>
    </div>
  </div>

  <script>
    // Filter by subscription plan
    const planFilter = document.getElementById('planFilter');
    planFilter.addEventListener('change', () => {
      const selected = planFilter.value;
      document.querySelectorAll('#usersTableBody tr').forEach(tr => {
        tr.style.display = (selected === '' || tr.dataset.plan === selected) ? '' : 'none';
      });
    });

    // View modal
    document.querySelectorAll('.view-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        const user = JSON.parse(btn.dataset.user);
        document.getElementById('modalName').innerText = user.first_name + ' ' + user.last_name;
        document.getElementById('modalEmail').innerText = user.email;
        document.getElementById('modalPhone').innerText = user.phone;
        document.getElementById('modalPlan').innerText = user.subscription_plan;
        new bootstrap.Modal(document.getElementById('viewModal')).show();
      });
    });

  </script>
  <script>
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const userId = this.getAttribute('data-id');
        if (!confirm("Are you sure you want to delete this user?")) return;

        fetch('delete_user.php?id=' + userId)
            .then(response => response.text())
            .then(data => {
                alert(data); // shows success or error message
                // Remove row from table without reload
                const row = this.closest('tr');
                if (row) row.remove();
            })
            .catch(err => alert('Error: ' + err));
    });
});
</script>

</div>


  <!-- Properties Section -->
<div id="properties" class="section">
  <h4>Properties</h4>

  <?php
  // Summary counts
  $total_properties = $conn->query("SELECT COUNT(*) AS cnt FROM properties")->fetch_assoc()['cnt'];
  $sale_count       = $conn->query("SELECT COUNT(*) AS cnt FROM properties WHERE type='sale'")->fetch_assoc()['cnt'];
  $rent_count       = $conn->query("SELECT COUNT(*) AS cnt FROM properties WHERE type='rent'")->fetch_assoc()['cnt'];
  $residential_count= $conn->query("SELECT COUNT(*) AS cnt FROM properties WHERE category='residential'")->fetch_assoc()['cnt'];
  $commercial_count = $conn->query("SELECT COUNT(*) AS cnt FROM properties WHERE category='commercial'")->fetch_assoc()['cnt'];
  $land_count       = $conn->query("SELECT COUNT(*) AS cnt FROM properties WHERE category='land'")->fetch_assoc()['cnt'];
  ?>

  <!-- Summary Cards -->
  <div class="row g-3 mb-4">
    <?php 
      $summary = [
        'Total'=>$total_properties,
        'Sale'=>$sale_count,
        'Rent'=>$rent_count,
        'Residential'=>$residential_count,
        'Commercial'=>$commercial_count,
        'Land'=>$land_count
      ];
      $colors = ['primary','success','warning','info','danger','secondary'];
      $i=0;
      foreach($summary as $k=>$v):
    ?>
      <div class="col-sm-6 col-md-2">
        <div class="card text-center p-2 bg-<?= $colors[$i++] ?> text-white shadow-sm">
          <h6><?= $k ?></h6>
          <h5><?= $v ?></h5>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <!-- Filter -->
  <div class="mb-3">
    <label>Filter by Type / Category:</label>
    <select id="propertyFilter" class="form-select w-auto">
      <option value="all">All Properties</option>
      <option value="sale">Sale</option>
      <option value="rent">Rent</option>
      <option value="residential">Residential</option>
      <option value="commercial">Commercial</option>
      <option value="land">Land</option>
    </select>
  </div>

  <!-- Properties Table -->
  <div class="table-responsive">
    <table class="table table-bordered table-hover">
      <thead class="table-dark">
        <tr>
          <th>ID</th>
          <th>Title</th>
          <th>Type</th>
          <th>Category</th>
          <th>Price</th>
          <th>Location</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody id="propertiesTable">
        <!-- AJAX content will load here -->
      </tbody>
    </table>
  </div>

  <!-- Pagination Links -->
  <nav>
    <ul class="pagination justify-content-center" id="propPagination"></ul>
  </nav>

  <script>
    document.addEventListener('DOMContentLoaded', function(){
      const tableBody = document.getElementById('propertiesTable');
      const pagination = document.getElementById('propPagination');
      const filter = document.getElementById('propertyFilter');
      let currentPage = 1;

      function loadProperties(page=1, filterVal='all'){
        fetch(`fetch_properties.php?page=${page}&filter=${filterVal}`)
          .then(res => res.json())
          .then(data => {
            // Populate table
            tableBody.innerHTML = '';
            if(data.properties.length === 0){
              tableBody.innerHTML = '<tr><td colspan="8" class="text-center">No properties found</td></tr>';
            } else {
              let count = (data.currentPage-1)*10 + 1;
              data.properties.forEach(prop => {
                tableBody.innerHTML += `
                  <tr>
                    <td>${count++}</td>
                    <td>${prop.title}</td>
                    <td>${prop.type}</td>
                    <td>${prop.category}</td>
                    <td>${parseFloat(prop.price).toLocaleString()}</td>
                    <td>${prop.location}</td>
                    <td>${prop.status}</td>
                    <td>
                      <a href="view_property.php?id=${prop.id}" class="btn btn-sm btn-info">View</a>
                      <a href="delete_property.php?id=${prop.id}" class="btn btn-sm btn-danger" onclick="return confirm('Delete this property?');">Delete</a>
                    </td>
                  </tr>`;
              });
            }

            // Pagination
            pagination.innerHTML = '';
            for(let i=1;i<=data.totalPages;i++){
              pagination.innerHTML += `
                <li class="page-item ${i===data.currentPage?'active':''}">
                  <a class="page-link" href="#" onclick="loadProperties(${i}, '${filterVal}'); return false;">${i}</a>
                </li>`;
            }
          });
      }

      filter.addEventListener('change', ()=> {
        loadProperties(1, filter.value);
      });

      loadProperties(); // Initial load
    });
  </script>

  <style>
    #properties { background: #f1f3f6; }
    #properties h4 { margin-bottom: 20px; }
    #properties .card h6 { margin-bottom: 5px; }
    #properties .table th, #properties .table td { vertical-align: middle; }
  </style>
</div>


  <!-- Adverts Section -->
<div id="adverts" class="section">
  <h4 class="text-center mb-4">Adverts Dashboard</h4>

  <?php
  // Fetch summary counts
  $summary = $conn->query("
    SELECT 
      SUM(status='active') AS active_adverts,
      SUM(status='expired') AS expired_adverts,
      COUNT(*) AS total_adverts
    FROM adverts
  ")->fetch_assoc();

  // Fetch adverts for table
  $adverts_query = $conn->query("
    SELECT a.*, u.first_name, u.last_name, u.subscription_plan
    FROM adverts a
    JOIN users u ON u.id = a.user_id
    ORDER BY a.created_at DESC
    LIMIT 50
  ");
  ?>

  <!-- Summary Cards -->
  <div class="row g-3 mb-4 justify-content-center text-center">
    <div class="col-4 col-md-2">
      <div class="card shadow-sm text-white bg-success p-3">
        <i class="fas fa-bullhorn fa-2x mb-2"></i>
        <h6>Active</h6>
        <h4><?= $summary['active_adverts'] ?></h4>
      </div>
    </div>
    <div class="col-4 col-md-2">
      <div class="card shadow-sm text-white bg-danger p-3">
        <i class="fas fa-clock fa-2x mb-2"></i>
        <h6>Expired</h6>
        <h4><?= $summary['expired_adverts'] ?></h4>
      </div>
    </div>
    <div class="col-4 col-md-2">
      <div class="card shadow-sm text-white bg-primary p-3">
        <i class="fas fa-list fa-2x mb-2"></i>
        <h6>Total</h6>
        <h4><?= $summary['total_adverts'] ?></h4>
      </div>
    </div>
  </div>

  <!-- Filter Buttons -->
  <div class="text-center mb-4">
    <button class="btn btn-outline-primary filter-btn active" data-filter="all">All</button>
    <button class="btn btn-outline-primary filter-btn" data-filter="active">Active</button>
    <button class="btn btn-outline-primary filter-btn" data-filter="expired">Expired</button>
  </div>

  <!-- Adverts Table -->
  <div class="table-responsive">
    <table class="table table-striped table-bordered">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Property ID</th>
          <th>Status</th>
          <th>Agent Name</th>
          <th>Subscription Plan</th>
          <th>Created At</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody id="advertsTableBody">
        <?php
        if($adverts_query->num_rows > 0):
          $i = 1;
          while($ad = $adverts_query->fetch_assoc()):
        ?>
          <tr data-status="<?= $ad['status'] ?>">
            <td><?= $i ?></td>
            <td><?= $ad['property_id'] ?></td>
            <td><?= ucfirst($ad['status']) ?></td>
            <td><?= htmlspecialchars($ad['first_name'] . ' ' . $ad['last_name']) ?></td>
            <td><?= htmlspecialchars($ad['subscription_plan']) ?></td>
            <td><?= $ad['created_at'] ?></td>
            <td>
  <button class="btn btn-sm btn-danger delete-advert-btn" data-id="<?= $ad['id'] ?>">Delete</button>
</td>

          </tr>
        <?php
            $i++;
          endwhile;
        else:
          echo "<tr><td colspan='7' class='text-center'>No adverts found</td></tr>";
        endif;
        ?>
      </tbody>
    </table>
  </div>
  <script>
  // Filter table without page reload
  const filterBtns = document.querySelectorAll('#adverts .filter-btn');
  const advertRows = document.querySelectorAll('#advertsTableBody tr');

  filterBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      filterBtns.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');

      const status = btn.getAttribute('data-filter');
      advertRows.forEach(row => {
        if(status === 'all' || row.dataset.status === status){
          row.style.display = '';
        } else {
          row.style.display = 'none';
        }
      });
    });
  });

  // AJAX delete functionality
  document.querySelectorAll('.delete-advert-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      if(!confirm('Are you sure you want to delete this advert?')) return;

      const advertId = btn.getAttribute('data-id');
      fetch('delete_advert.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'id=' + advertId
      })
      .then(res => res.text())
      .then(data => {
        if(data.trim() === 'success') {
          // remove row from table
          btn.closest('tr').remove();
        } else {
          alert('Failed to delete advert.');
        }
      })
      .catch(err => alert('Error deleting advert.'));
    });
  });
</script>


  <style>
    #adverts { background: #f8f9fa; padding-bottom: 30px; }
    #adverts .card i { color: #fff; }
    #adverts .card h6 { margin-bottom: 10px; }
    #adverts table th, #adverts table td { vertical-align: middle; }
    #adverts .filter-btn.active { background-color: #0d6efd; color: #fff; border-color: #0d6efd; }
    #adverts .table-responsive { max-height: 500px; overflow-y: auto; }
  </style>

  <script>
    // Filter table without page reload
    const filterBtns = document.querySelectorAll('#adverts .filter-btn');
    const advertRows = document.querySelectorAll('#advertsTableBody tr');

    filterBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        filterBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');

        const status = btn.getAttribute('data-filter');
        advertRows.forEach(row => {
          if(status === 'all' || row.dataset.status === status){
            row.style.display = '';
          } else {
            row.style.display = 'none';
          }
        });
      });
    });
  </script>
</div>


<?php
require_once "config.php";

// Fetch all admin properties
$admin_props_res = $conn->query("SELECT * FROM admin_properties ORDER BY created_at DESC");
$admin_props = [];
if($admin_props_res && $admin_props_res->num_rows > 0){
    while($row = $admin_props_res->fetch_assoc()){
        $admin_props[] = $row;
    }
}
?>

<section id="admin-properties" class="py-5" style="background:#f8f9fa;">
    <div class="container">
        <h4 class="mb-4 text-center">Uploaded Admin Properties</h4>

        <?php if(!empty($admin_props)): ?>
        <div class="row g-4">
            <?php foreach($admin_props as $prop): 
                // Handle additional images
                $extra_images = $prop['images'] ? explode(',', $prop['images']) : [];
            ?>
            <div class="col-sm-6 col-md-4 col-lg-3">
                <div class="card h-100 shadow-sm">
                    <img src="<?= htmlspecialchars($prop['property_image']) ?>" class="card-img-top" style="height:200px; object-fit:cover;" alt="Property Image">
                    <div class="card-body d-flex flex-column justify-content-between">
                        <p class="mb-2"><strong>Type:</strong> <?= htmlspecialchars(ucfirst($prop['property_type'])) ?></p>
                        <p class="mb-2"><strong>Price:</strong> ₦<?= number_format($prop['price'], 2) ?></p>
                        <p class="mb-2"><strong>Location:</strong> <?= htmlspecialchars($prop['location']) ?></p>

                        <div class="mt-2">
                            <!-- View Button triggers modal -->
                            <button class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#viewPropertyModal<?= $prop['id'] ?>">View</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal -->
            <div class="modal fade" id="viewPropertyModal<?= $prop['id'] ?>" tabindex="-1" aria-labelledby="viewPropertyModalLabel<?= $prop['id'] ?>" aria-hidden="true">
                <div class="modal-dialog modal-lg modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="viewPropertyModalLabel<?= $prop['id'] ?>">Property Details</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <!-- Main Image -->
                            <img src="<?= htmlspecialchars($prop['property_image']) ?>" class="img-fluid mb-3" alt="Property Image">

                            <!-- Extra Images -->
                            <?php if(!empty($extra_images)): ?>
                                <div class="mb-3 d-flex flex-wrap gap-2">
                                    <?php foreach($extra_images as $img): ?>
                                        <img src="<?= htmlspecialchars($img) ?>" style="width:80px; height:80px; object-fit:cover; border-radius:4px;" alt="Extra Image">
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>

                            <!-- Video -->
                            <?php if(!empty($prop['video'])): ?>
                                <div class="mb-3">
                                    <video controls style="width:100%; max-height:400px; border-radius:6px;">
                                        <source src="<?= htmlspecialchars($prop['video']) ?>" type="video/mp4">
                                        Your browser does not support the video tag.
                                    </video>
                                </div>
                            <?php endif; ?>

                            <p><strong>Description:</strong></p>
                            <p><?= nl2br(htmlspecialchars($prop['description'])) ?></p>
                            <p><small class="text-muted">Uploaded: <?= date('d M Y', strtotime($prop['created_at'])) ?></small></p>
                        </div>
                        <div class="modal-footer">
                            <form action="process_admin_property.php" method="POST" onsubmit="return confirm('Are you sure you want to delete this property?');">
                                <input type="hidden" name="delete_property_id" value="<?= $prop['id'] ?>">
                                <button type="submit" class="btn btn-danger">Delete</button>
                            </form>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>

            <?php endforeach; ?>
        </div>
        <?php else: ?>
            <p class="text-center text-muted">No properties uploaded yet.</p>
        <?php endif; ?>
    </div>
</section>

<style>
#admin-properties .card {
    transition: transform 0.2s;
}
#admin-properties .card:hover {
    transform: scale(1.03);
}
</style>


<section id="inspection-requests" class="container py-5">
  <h4 class="mb-4 text-center">Property Inspection Requests</h4>

  <?php
  require_once "config.php";

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

  // Count total inspections
  $count_res = $conn->query("SELECT COUNT(*) as total FROM property_inspections");
  $total_rows = $count_res->fetch_assoc()['total'];
  $total_pages = ceil($total_rows / $limit);

  // Fetch inspection requests with property info
  $inspections_res = $conn->query("
      SELECT pi.*, ap.property_type, ap.property_image, ap.images, ap.video, ap.price, ap.location
      FROM property_inspections pi
      JOIN admin_properties ap ON pi.property_id = ap.id
      ORDER BY pi.created_at DESC
      LIMIT $offset, $limit
  ");
  $inspections = [];
  if($inspections_res && $inspections_res->num_rows > 0){
      while($row = $inspections_res->fetch_assoc()){
          $inspections[] = $row;
      }
  }
  ?>

  <?php if(!empty($inspections)): ?>
  <div class="table-responsive">
      <table class="table table-bordered table-striped align-middle text-center">
          <thead class="table-dark">
              <tr>
                  <th>#</th>
                  <th>Property</th>
                  <th>Type</th>
                  <th>Name</th>
                  <th>Phone</th>
                  <th>Email</th>
                  <th>Preferred Date</th>
                  <th>Requested At</th>
                  <th>Action</th>
              </tr>
          </thead>
          <tbody>
              <?php foreach($inspections as $i => $ins): 
                $extra_images = $ins['images'] ? explode(',', $ins['images']) : [];
              ?>
              <tr>
                  <td><?= $offset + $i + 1 ?></td>
                  <td><img src="<?= htmlspecialchars($ins['property_image']) ?>" alt="Property"></td>
                  <td><?= htmlspecialchars(ucfirst($ins['property_type'])) ?></td>
                  <td><?= htmlspecialchars($ins['name']) ?></td>
                  <td><?= htmlspecialchars($ins['phone']) ?></td>
                  <td><?= htmlspecialchars($ins['email']) ?: 'N/A' ?></td>
                  <td><?= htmlspecialchars($ins['inspection_date']) ?></td>
                  <td><?= htmlspecialchars($ins['created_at']) ?></td>
                  <td>
                      <!-- View Property Button -->
                      <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#viewPropertyModal<?= $ins['id'] ?>">View</button>
                      
                      <!-- Delete Button -->
                      <form action="process_delete_inspection.php" method="POST" style="display:inline-block;" onsubmit="return confirm('Are you sure you want to delete this inspection request?');">
                        <input type="hidden" name="inspection_id" value="<?= $ins['id'] ?>">
                        <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                      </form>
                  </td>
              </tr>

              <!-- Property Details Modal -->
              <div class="modal fade" id="viewPropertyModal<?= $ins['id'] ?>" tabindex="-1" aria-labelledby="viewPropertyModalLabel<?= $ins['id'] ?>" aria-hidden="true">
                <div class="modal-dialog modal-lg modal-dialog-centered">
                  <div class="modal-content">
                    <div class="modal-header">
                      <h5 class="modal-title" id="viewPropertyModalLabel<?= $ins['id'] ?>">Property Details</h5>
                      <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                      <!-- Main Image -->
                      <img src="<?= htmlspecialchars($ins['property_image']) ?>" class="img-fluid mb-3" alt="Property Image">

                      <!-- Extra Images -->
                      <?php if(!empty($extra_images)): ?>
                      <div class="mb-3 d-flex flex-wrap gap-2">
                        <?php foreach($extra_images as $img): ?>
                        <img src="<?= htmlspecialchars($img) ?>" style="width:80px; height:80px; object-fit:cover; border-radius:4px;" alt="Extra Image">
                        <?php endforeach; ?>
                      </div>
                      <?php endif; ?>

                      <!-- Video -->
                      <?php if(!empty($ins['video'])): ?>
                      <div class="mb-3">
                        <video controls style="width:100%; max-height:400px; border-radius:6px;">
                          <source src="<?= htmlspecialchars($ins['video']) ?>" type="video/mp4">
                          Your browser does not support the video tag.
                        </video>
                      </div>
                      <?php endif; ?>

                      <p><strong>Type:</strong> <?= htmlspecialchars(ucfirst($ins['property_type'])) ?></p>
                      <p><strong>Price:</strong> ₦<?= number_format($ins['price'],2) ?></p>
                      <p><strong>Location:</strong> <?= htmlspecialchars($ins['location']) ?></p>
                      <p><strong>Description:</strong></p>
                      <p><?= nl2br(htmlspecialchars($ins['description'])) ?></p>
                    </div>
                    <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                  </div>
                </div>
              </div>

              <?php endforeach; ?>
          </tbody>
      </table>
  </div>

  <!-- Pagination -->
  <nav aria-label="Inspection Pagination">
      <ul class="pagination justify-content-center mt-3">
          <?php for($p = 1; $p <= $total_pages; $p++): ?>
          <li class="page-item <?= ($p==$page)?'active':'' ?>">
              <a class="page-link" href="?inspection_page=<?= $p ?>"><?= $p ?></a>
          </li>
          <?php endfor; ?>
      </ul>
  </nav>

  <?php else: ?>
      <p class="text-center">No inspection requests yet.</p>
  <?php endif; ?>

  <style>
    #inspection-requests {
        background-color: #f8f9fa;
        border-radius: 10px;
        padding: 30px 15px;
    }

    #inspection-requests table img {
        height: 60px;
        width: auto;
        object-fit: cover;
        border-radius: 5px;
    }

    #inspection-requests table th, 
    #inspection-requests table td {
        vertical-align: middle;
        padding: 0.75rem;
    }

    @media(max-width:768px){
        #inspection-requests table th, 
        #inspection-requests table td {
            font-size: 0.85rem;
            padding: 0.5rem;
        }
        #inspection-requests table img {
            height: 50px;
        }
    }
  </style>
</section>





  <!-- Transactions Section -->
<div id="transactions" class="section">
  <h4>Transactions</h4>

  <?php
  // Fetch transaction counts
  $completed_txns = $conn->query("SELECT COUNT(*) AS cnt FROM transactions WHERE status='completed'")->fetch_assoc()['cnt'];
  $pending_txns   = $conn->query("SELECT COUNT(*) AS cnt FROM transactions WHERE status='pending'")->fetch_assoc()['cnt'];
  $failed_txns    = $conn->query("SELECT COUNT(*) AS cnt FROM transactions WHERE status='failed'")->fetch_assoc()['cnt'];
  $total_txns     = $conn->query("SELECT COUNT(*) AS cnt FROM transactions")->fetch_assoc()['cnt'];
  ?>

  <!-- Transaction Cards -->
  <div class="row g-4 mt-3">
    <div class="col-sm-6 col-md-3">
      <div class="card shadow-sm text-white bg-success p-3 text-center">
        <i class="fas fa-check-circle fa-2x mb-2"></i>
        <h6>Completed</h6>
        <h4><?= $completed_txns ?></h4>
      </div>
    </div>
    <div class="col-sm-6 col-md-3">
      <div class="card shadow-sm text-white bg-warning p-3 text-center">
        <i class="fas fa-hourglass-half fa-2x mb-2"></i>
        <h6>Pending</h6>
        <h4><?= $pending_txns ?></h4>
      </div>
    </div>
    <div class="col-sm-6 col-md-3">
      <div class="card shadow-sm text-white bg-danger p-3 text-center">
        <i class="fas fa-times-circle fa-2x mb-2"></i>
        <h6>Failed</h6>
        <h4><?= $failed_txns ?></h4>
      </div>
    </div>
    <div class="col-sm-6 col-md-3">
      <div class="card shadow-sm text-white bg-primary p-3 text-center">
        <i class="fas fa-list fa-2x mb-2"></i>
        <h6>Total</h6>
        <h4><?= $total_txns ?></h4>
      </div>
    </div>
  </div>

  <!-- Filter -->
  <div class="mt-4">
    <label for="txnFilter" class="form-label">Filter by status:</label>
    <select id="txnFilter" class="form-select w-auto">
      <option value="">All</option>
      <option value="completed">Completed</option>
      <option value="pending">Pending</option>
      <option value="failed">Failed</option>
    </select>
  </div>

  <!-- Transactions Table -->
  <div class="table-responsive mt-3">
    <table class="table table-striped table-hover">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>User ID</th>
          <th>Type</th>
          <th>Amount</th>
          <th>Currency</th>
          <th>Status</th>
          <th>Reference</th>
          <th>Description</th>
          <th>Created At</th>
        </tr>
      </thead>
      <tbody id="txnTableBody">
        <?php
        $limit = 10; // rows per page
        $page = isset($_GET['txn_page']) ? intval($_GET['txn_page']) : 1;
        $offset = ($page - 1) * $limit;

        $txn_filter = isset($_GET['status']) ? $_GET['status'] : '';
        $where_clause = $txn_filter ? "WHERE status='$txn_filter'" : '';

        $txns_sql = "SELECT * FROM transactions $where_clause ORDER BY created_at DESC LIMIT $offset, $limit";
        $txns_result = $conn->query($txns_sql);

        if ($txns_result->num_rows > 0) {
          $sn = $offset + 1;
          while ($txn = $txns_result->fetch_assoc()) {
            echo "<tr>
              <td>$sn</td>
              <td>{$txn['user_id']}</td>
              <td>{$txn['type']}</td>
              <td>{$txn['amount']}</td>
              <td>{$txn['currency']}</td>
              <td>{$txn['status']}</td>
              <td>{$txn['reference']}</td>
              <td>{$txn['description']}</td>
              <td>{$txn['created_at']}</td>
            </tr>";
            $sn++;
          }
        } else {
          echo "<tr><td colspan='9' class='text-center'>No transactions found</td></tr>";
        }
        ?>
      </tbody>
    </table>
  </div>

  <?php
  // Pagination
  $total_rows = $conn->query("SELECT COUNT(*) AS cnt FROM transactions $where_clause")->fetch_assoc()['cnt'];
  $total_pages = ceil($total_rows / $limit);
  if ($total_pages > 1) {
    echo '<nav><ul class="pagination">';
    for ($i = 1; $i <= $total_pages; $i++) {
      $active = $i == $page ? 'active' : '';
      $status_param = $txn_filter ? "&status=$txn_filter" : '';
      echo "<li class='page-item $active'><a class='page-link' href='?txn_page=$i$status_param'>$i</a></li>";
    }
    echo '</ul></nav>';
  }
  ?>

  <style>
    #transactions { background: #f8f9fa; }
    #transactions .card { border-radius: 12px; }
    #transactions .card i { color: #fff; }
    #transactions .table-responsive { max-height: 400px; overflow-y: auto; }
  </style>

  <script>
    document.getElementById('txnFilter').addEventListener('change', function() {
      const status = this.value;
      let url = window.location.pathname + '?txn_page=1';
      if (status) url += '&status=' + status;
      window.location.href = url;
    });
  </script>
</div>


  <!-- Profile Section -->
<div id="profile" class="section">
    <h4>Profile</h4>

    <!-- Profile Card -->
    <div class="card shadow-sm p-4" style="max-width:600px;">
        <div class="d-flex align-items-center mb-3">
            <img src="uploads/<?php echo htmlspecialchars($admin_info['image']); ?>" alt="Admin Image" class="rounded-circle me-3" style="width:80px; height:80px; object-fit:cover;">
            <div>
                <h5 class="mb-1"><?php echo htmlspecialchars($admin_info['first_name'] . " " . $admin_info['last_name']); ?></h5>
                <p class="mb-0"><strong>Email:</strong> <?php echo htmlspecialchars($admin_info['email']); ?></p>
                <p class="mb-0"><strong>Phone:</strong> <?php echo htmlspecialchars($admin_info['phone']); ?></p>
                <p class="mb-0"><strong>Address:</strong> <?php echo htmlspecialchars($admin_info['address']); ?></p>
            </div>
        </div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editProfileModal">
            <i class="fas fa-edit me-1"></i> Edit Profile
        </button>
    </div>

    <!-- Edit Profile Modal -->
    <div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <form action="update_profile.php" method="POST" enctype="multipart/form-data">
              <div class="modal-header">
                <h5 class="modal-title" id="editProfileModalLabel">Edit Profile</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                  <!-- Image Upload -->
                  <div class="mb-3 text-center">
                      <img src="uploads/<?php echo htmlspecialchars($admin_info['image']); ?>" id="previewImageModal" class="rounded-circle mb-2" style="width:100px; height:100px; object-fit:cover;">
                      <input type="file" name="profile_image" class="form-control" accept="image/*" onchange="previewImgModal(event)">
                  </div>

                  <!-- Change Password -->
                  <div class="mb-3">
                      <label for="current_password" class="form-label">Current Password</label>
                      <input type="password" name="current_password" id="current_password" class="form-control">
                  </div>
                  <div class="mb-3">
                      <label for="new_password" class="form-label">New Password</label>
                      <input type="password" name="new_password" id="new_password" class="form-control">
                  </div>
                  <div class="mb-3">
                      <label for="confirm_password" class="form-label">Confirm New Password</label>
                      <input type="password" name="confirm_password" id="confirm_password" class="form-control">
                  </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" name="update_profile" class="btn btn-success">Save Changes</button>
              </div>
          </form>
        </div>
      </div>
    </div>

    <script>
      function previewImgModal(event) {
          const reader = new FileReader();
          reader.onload = function(){
              document.getElementById('previewImageModal').src = reader.result;
          };
          reader.readAsDataURL(event.target.files[0]);
      }
    </script>

    <style>
        #profile { background: #f8f9fa; padding: 20px; border-radius: 12px; }
        #profile h4 { margin-bottom: 20px; }
        #editProfileModal img { display: block; margin: 0 auto; }
    </style>
</div>


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

</body>
</html>
