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

// ✅ Ensure logged-in user
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$agent_id = $_SESSION['user_id'];

// ✅ Fetch agent details
$stmt = $conn->prepare("
    SELECT id, first_name, last_name, email, phone, address, image, username,
           role, subscription_plan, balance, currency, status, created_at, last_login
    FROM users
    WHERE id = ? AND role IN ('basic','gold','premium') 
    LIMIT 1
");
$stmt->bind_param("i", $agent_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header("Location: login.php");
    exit;
}

$agent_info = $result->fetch_assoc();

// ✅ Fetch properties count
$stmt = $conn->prepare("SELECT COUNT(*) as total_properties FROM properties WHERE user_id = ?");
$stmt->bind_param("i", $agent_id);
$stmt->execute();
$properties_count = $stmt->get_result()->fetch_assoc()['total_properties'];

// ✅ Fetch adverts count
$stmt = $conn->prepare("SELECT COUNT(*) as total_adverts FROM adverts WHERE user_id = ?");
$stmt->bind_param("i", $agent_id);
$stmt->execute();
$adverts_count = $stmt->get_result()->fetch_assoc()['total_adverts'];

// ✅ Fetch profile visits count
$stmt = $conn->prepare("SELECT COUNT(*) as total_visits FROM profile_visits WHERE visited_user_id = ?");
$stmt->bind_param("i", $agent_id);
$stmt->execute();
$profile_visits = $stmt->get_result()->fetch_assoc()['total_visits'];

// ✅ Fetch transactions count & sum
$stmt = $conn->prepare("SELECT COUNT(*) as txn_count, COALESCE(SUM(amount),0) as txn_total 
                        FROM transactions WHERE user_id = ?");
$stmt->bind_param("i", $agent_id);
$stmt->execute();
$txn_data = $stmt->get_result()->fetch_assoc();
$transactions_count = $txn_data['txn_count'];
$transactions_total = $txn_data['txn_total'];

// ✅ Agent dashboard data (ready to use in HTML)
$dashboard_data = [
    'properties' => $properties_count,
    'adverts' => $adverts_count,
    'profile_visits' => $profile_visits,
    'transactions' => $transactions_count,
    'transactions_total' => $transactions_total,
];
?>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Agent Dashboard</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <!-- Load Font Awesome properly -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

  <style>
    body {
      font-family: 'Segoe UI', sans-serif;
      overflow-x: hidden;
    }

    /* Sidebar */
    #sidebar {
      position: fixed;
      top: 0;
      left: 0;
      width: 250px;
      height: 100vh;
      background-color: #2b2b40;
      color: #fff;
      transition: all 0.3s;
      z-index: 1000;
      padding-top: 20px;
    }

    #sidebar.collapsed {
      left: -250px;
    }

    #sidebar .logo {
      text-align: center;
      margin-bottom: 30px;
    }

    #sidebar .logo img {
      max-width: 120px;
      border-radius: 8px;
      margin-bottom: 5px;
    }

    #sidebar .menu a {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px 20px;
      color: #fff;
      text-decoration: none;
      transition: background 0.3s;
      border-radius: 6px;
      font-size: 15px;
    }

    #sidebar .menu a:hover {
      background: #4a6cf7;
    }

    /* Top nav */
    #top-nav {
      position: fixed;
      top: 0;
      left: 250px;
      right: 0;
      height: 60px;
      background-color: #fff;
      border-bottom: 1px solid #ddd;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      transition: left 0.3s;
      z-index: 999;
    }

    #top-nav.collapsed {
      left: 0;
    }

    #top-nav .agent-info {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    #top-nav .agent-info img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
    }

    /* Main content */
    #main-content {
      margin-left: 250px;
      padding: 80px 20px 20px 20px;
      transition: margin-left 0.3s;
    }

    #main-content.collapsed {
      margin-left: 0;
    }

    section {
      padding: 40px 0;
      border-bottom: 1px solid #eee;
    }

    section h4 {
      margin-bottom: 20px;
    }

    /* Hamburger */
    #sidebarToggle {
      display: none;
      font-size: 1.5rem;
      cursor: pointer;
    }

    @media (max-width: 992px){
      #sidebar {
        left: -250px;
      }

      #sidebar.collapsed {
        left: 0;
      }

      #top-nav {
        left: 0;
      }

      #top-nav.collapsed {
        left: 250px;
      }

      #main-content {
        margin-left: 0;
      }

      #main-content.collapsed {
        margin-left: 250px;
      }

      #sidebarToggle {
        display: block;
        color: #2b2b40;
      }
    }
  </style>
</head>
<body>

  <!-- Sidebar -->
<nav id="sidebar">
    <div class="logo">
      <img src="images/limac.jpeg" alt="Limac Group Logo">
      <div>Limac Group</div>
    </div>
    <div class="menu">
      <a href="#dashboard"><i class="fas fa-home text-primary"></i> Dashboard</a> <br>
      <a href="#properties"><i class="fas fa-building text-success"></i> My Properties</a> <br>
      <a href="#adverts"><i class="fas fa-bullhorn text-warning"></i> Adverts</a> <br>
      <a href="#transactions"><i class="fas fa-file-alt text-danger"></i> Transactions</a> <br>
      <a href="#profile"><i class="fas fa-user text-secondary"></i> Profile</a> <br>
      <a href="logout.php"><i class="fas fa-sign-out-alt text-light"></i> Logout</a>
    </div>
</nav>

  <!-- Top nav -->
<div id="top-nav">
    <div>
      <button class="btn btn-light" id="sidebarToggle">
        <i class="fa-solid fa-bars"></i>
      </button>
    </div>
    <div class="dropdown agent-info d-flex align-items-center">
  <span class="me-2 d-none d-md-inline">Welcome, <?= htmlspecialchars($agent_info['first_name']) ?></span>

  <!-- Use a button trigger (reliable) -->
  <button id="profileDropdown" class="btn btn-sm btn-light p-0 border-0 d-flex align-items-center" data-bs-toggle="dropdown" aria-expanded="false" title="Open menu">
    <img src="<?= !empty($agent_info['image']) ? 'uploads/' . htmlspecialchars($agent_info['image']) : 'images/default-avatar.png' ?>"
         alt="Profile Image"
         id="profileImage"
         class="rounded-circle border"
         style="width:40px; height:40px; object-fit:cover;">
  </button>

  <!-- Dropdown menu -->
  <ul class="dropdown-menu dropdown-menu-end shadow-sm mt-2" aria-labelledby="profileDropdown" style="min-width:210px;">
    <li>
      <a class="dropdown-item d-flex align-items-center" href="#dashboard">
        <span class="me-2 text-primary"><i class="fas fa-tachometer-alt"></i></span> Dashboard
      </a>
    </li>
    <li>
      <a class="dropdown-item d-flex align-items-center" href="#properties">
        <span class="me-2 text-success"><i class="fas fa-home"></i></span> Properties
      </a>
    </li>
    <li>
      <a class="dropdown-item d-flex align-items-center" href="#adverts">
        <span class="me-2 text-warning"><i class="fas fa-bullhorn"></i></span> Adverts
      </a>
    </li>
    <li>
      <a class="dropdown-item d-flex align-items-center" href="#transactions">
        <span class="me-2 text-info"><i class="fas fa-exchange-alt"></i></span> Transactions
      </a>
    </li>
    <li>
      <a class="dropdown-item d-flex align-items-center" href="#profile">
        <span class="me-2 text-secondary"><i class="fas fa-user"></i></span> Profile
      </a>
    </li>
    <li><hr class="dropdown-divider"></li>
    <li>
      <a class="dropdown-item d-flex align-items-center text-danger" href="logout.php">
        <span class="me-2"><i class="fas fa-sign-out-alt"></i></span> Logout
      </a>
    </li>
  </ul>
</div>

<!-- ====== Optional small CSS to tweak the menu ====== -->
<style>
  .dropdown .dropdown-item i { width: 18px; text-align: center; }
  .agent-info .btn:focus { box-shadow: none; }
</style>
</div>


  <!-- Main content -->
<div id="main-content">

<section id="dashboard" class="container py-4">
  <h4 class="mb-3">Dashboard</h4>
  <p>
    Welcome to your dashboard, <?= htmlspecialchars($agent_info['first_name']) ?>!
  </p>

  <!-- Wallet Balance -->
  <div class="card shadow-sm mt-3 mb-4" style="max-width: 200px;">
  <div class="card-body text-center">
    <h6 class="card-title">Wallet Balance</h6>
    <p class="card-text fs-5 fw-bold text-success mb-0">
      <?= htmlspecialchars($agent_info['currency']) ?> <?= number_format($agent_info['balance'], 2) ?>
    </p>
    <!-- Deposit Button -->
    <button class="btn btn-primary btn-sm mt-3" onclick="openDepositModal()">Deposit</button>
  </div>
</div>

<!-- Deposit Modal -->
<div class="modal fade" id="depositModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title">Deposit Funds</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label for="depositAmount" class="form-label">Enter Amount (₦)</label>
        <input type="number" class="form-control" id="depositAmount" min="500" placeholder="Min ₦500">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-success" onclick="payWithPaystack()">Proceed</button>
      </div>
    </div>
  </div>
</div>

<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
function openDepositModal() {
  var depositModal = new bootstrap.Modal(document.getElementById('depositModal'));
  depositModal.show();
}

function payWithPaystack() {
  let amount = document.getElementById("depositAmount").value;
  if (amount < 500) {
    alert("Minimum deposit is ₦500");
    return;
  }

  var handler = PaystackPop.setup({
    key: 'pk_test_0a322a48a1a5440c6f75622f3c541ef67e45dc23',
    email: "<?= $agent_info['email'] ?>", // agent email from DB
    amount: amount * 100, // convert to kobo
    currency: "NGN",
    callback: function(response) {
      // Send reference to backend to verify and credit wallet
      window.location.href = "verify_payment.php?reference=" + response.reference;
    },
    onClose: function() {
      alert('Transaction cancelled.');
    }
  });
  handler.openIframe();
}
</script>


  <!-- Quick Actions -->
  <div class="quick-actions">
    <h5 class="mb-3">Quick Actions</h5>
    <div class="row g-3">
      <!-- Properties -->
      <div class="col-6 col-md-3">
        <div class="action-card text-center p-3 shadow-sm h-100" data-target="#properties">
          <i class="fas fa-building fa-2x text-primary mb-2"></i>
          <h6 class="fw-semibold">Properties</h6>
        </div>
      </div>

      <!-- Adverts -->
      <div class="col-6 col-md-3">
        <div class="action-card text-center p-3 shadow-sm h-100" data-target="#adverts">
          <i class="fas fa-bullhorn fa-2x text-warning mb-2"></i>
          <h6 class="fw-semibold">Adverts</h6>
        </div>
      </div>

      <!-- Profile Visits -->
      <div class="col-6 col-md-3">
        <div class="action-card text-center p-3 shadow-sm h-100" data-target="#profile">
          <i class="fas fa-user-friends fa-2x text-success mb-2"></i>
          <h6 class="fw-semibold">Profile Visits</h6>
        </div>
      </div>

      <!-- Transactions -->
      <div class="col-6 col-md-3">
        <div class="action-card text-center p-3 shadow-sm h-100" data-target="#transactions">
          <i class="fas fa-wallet fa-2x text-danger mb-2"></i>
          <h6 class="fw-semibold">Transactions</h6>
        </div>
      </div>
    </div>
  </div>

  <!-- Self-contained CSS -->
  <style>
    #dashboard .quick-actions .action-card {
      border-radius: 12px;
      transition: all 0.3s ease;
      background: #fff;
      cursor: pointer;
    }
    #dashboard .quick-actions .action-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 15px rgba(0,0,0,0.15);
    }
    #dashboard .quick-actions i {
      display: block;
    }
  </style>

  <!-- Self-contained JS -->
  <script>
    document.querySelectorAll('#dashboard .action-card').forEach(card => {
      card.addEventListener('click', function() {
        const targetSelector = this.getAttribute('data-target');
        const target = document.querySelector(targetSelector);
        if (target) {
          target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
      });
    });
  </script>
</section>


<!-- PROPERTIES SECTION -->
<section id="properties" class="container py-5">
  <h4 class="mb-3">My Properties</h4>

  <!-- Summary -->
  <div class="row g-3 mb-4">
    <div class="col-4">
      <div class="card shadow-sm text-center p-3">
        <h6>Total</h6>
        <p id="totalProperties" class="fw-bold fs-5">0</p>
      </div>
    </div>
    <div class="col-4">
      <div class="card shadow-sm text-center p-3">
        <h6>For Sale</h6>
        <p id="saleProperties" class="fw-bold fs-5 text-success">0</p>
      </div>
    </div>
    <div class="col-4">
      <div class="card shadow-sm text-center p-3">
        <h6>Rentals</h6>
        <p id="rentProperties" class="fw-bold fs-5 text-primary">0</p>
      </div>
    </div>
  </div>

  <!-- Actions -->
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <select id="propertyFilter" class="form-select">
        <option value="all">All</option>
        <option value="sale">For Sale</option>
        <option value="rent">Rentals</option>
        <option value="residential">Residential</option>
        <option value="commercial">Commercial</option>
        <option value="land">Land</option>
        <option value="other">Other</option>
      </select>
    </div>
    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addPropertyModal">
      <i class="fas fa-plus"></i> Add Property
    </button>
  </div>

  <!-- Property Table -->
  <div class="table-responsive">
    <table class="table table-striped table-bordered">
      <thead class="table-dark">
        <tr>
          <th>Title</th>
          <th>Type</th>
          <th>Category</th>
          <th>Price/Package</th>
          <th>Location</th>
          <th>Status</th>
          <th>Created</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody id="propertyTableBody">
        <!-- JS will populate -->
      </tbody>
    </table>
  </div>

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

  <!-- Add Property Modal -->
  <div class="modal fade" id="addPropertyModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
      <div class="modal-content">
        <form id="addPropertyForm" enctype="multipart/form-data">
          <div class="modal-header">
            <h5 class="modal-title">Add Property</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" style="max-height:70vh; overflow-y:auto;">
            
            <!-- Title -->
            <div class="mb-3">
              <label class="form-label">Property Title</label>
              <input type="text" name="title" class="form-control" required>
            </div>

            <!-- Type -->
            <div class="mb-3">
              <label class="form-label">Type</label>
              <select name="type" id="propertyType" class="form-select" required>
                <option value="">-- Select Type --</option>
                <option value="sale">Sale</option>
                <option value="rent">Rent</option>
              </select>
            </div>

            <!-- Category -->
            <div class="mb-3">
              <label class="form-label">Category</label>
              <select name="category" class="form-select" required>
                <option value="residential">Residential</option>
                <option value="commercial">Commercial</option>
                <option value="land">Land</option>
                <option value="other">Other</option>
              </select>
            </div>

            <!-- Sale Fields -->
            <div id="saleFields" class="d-none">
              <div class="mb-3">
                <label class="form-label">Sale Price</label>
                <input type="number" step="0.01" name="price" class="form-control">
              </div>
            </div>

            <!-- Rental Fields -->
            <div id="rentalFields" class="d-none">
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">Monthly Fee</label>
                  <input type="number" step="0.01" id="monthlyFee" name="monthly_fee" class="form-control">
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">Yearly Fee</label>
                  <input type="number" step="0.01" id="yearlyFee" name="yearly_fee" class="form-control" readonly>
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">Agency Fee</label>
                  <input type="number" step="0.01" id="agencyFee" name="agency_fee" class="form-control">
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">Other Fees</label>
                  <input type="number" step="0.01" id="otherFees" name="other_fees" class="form-control">
                </div>
                <div class="col-md-12 mb-3">
                  <label class="form-label">Total Package</label>
                  <input type="number" step="0.01" id="totalPackage" name="total_package" class="form-control" readonly>
                </div>
              </div>
            </div>

            <!-- Location -->
            <div class="mb-3">
              <label class="form-label">Location</label>
              <input type="text" name="location" class="form-control" required>
            </div>

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

            <!-- Images -->
            <div class="mb-3">
              <label class="form-label">Upload Images (max 5)</label>
              <input type="file" name="images[]" class="form-control" accept="image/*" multiple required>
            </div>

            <!-- Video -->
            <div class="mb-3">
              <label class="form-label">Upload Video (optional)</label>
              <input type="file" name="video" class="form-control" accept="video/*">
            </div>

          </div>
          <small class="text-danger">Note: A service charge of ₦200 applies per upload.</small>
          <div class="modal-footer">

            <button type="submit" class="btn btn-success">Save Property</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- View Property Modal -->
  <div class="modal fade" id="viewPropertyModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Property Details</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body" id="viewPropertyContent">
          Loading...
        </div>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script>
  document.addEventListener("DOMContentLoaded", () => {
    // Auto-calc yearly & total package
    function calcTotals() {
      const monthly = parseFloat(document.getElementById("monthlyFee").value) || 0;
      const yearly = monthly * 12;
      document.getElementById("yearlyFee").value = yearly.toFixed(2);

      const agency = parseFloat(document.getElementById("agencyFee").value) || 0;
      const other = parseFloat(document.getElementById("otherFees").value) || 0;
      const total = yearly + agency + other;
      document.getElementById("totalPackage").value = total.toFixed(2);
    }

    ["monthlyFee","agencyFee","otherFees"].forEach(id=>{
      document.getElementById(id).addEventListener("input", calcTotals);
    });

    // Toggle Sale/Rent fields
    document.getElementById("propertyType").addEventListener("change", function() {
      document.getElementById("saleFields").classList.toggle("d-none", this.value !== "sale");
      document.getElementById("rentalFields").classList.toggle("d-none", this.value !== "rent");
    });

    // ✅ Fetch & populate table
    function fetchProperties(filter = 'all', page = 1) {
      fetch(`fetch_agent_properties.php?filter=${filter}&page=${page}`)
        .then(res => res.json())
        .then(data => {
          if (data.error) {
            alert(data.error);
            return;
          }

          // Update table
          const tbody = document.getElementById("propertyTableBody");
          tbody.innerHTML = "";
          data.properties.forEach(prop => {
            tbody.innerHTML += `
              <tr>
                <td>${prop.title}</td>
                <td>${prop.type}</td>
                <td>${prop.category}</td>
                <td>${prop.type === 'rent' ? (prop.total_package || '-') : (prop.price || '-')}</td>
                <td>${prop.location || '-'}</td>
                <td>${prop.status}</td>
                <td>${prop.created_at}</td>
                <td>
                  <a href="view_property.php?id=${prop.id}" class="btn btn-sm btn-info">View</a>
                  <button class="btn btn-sm btn-danger deleteBtn" data-id="${prop.id}">Delete</button>
                </td>
              </tr>
            `;
          });

          // ✅ Update summary cards
          document.getElementById("totalProperties").textContent = data.stats.total;
          document.getElementById("saleProperties").textContent = data.stats.sale;
          document.getElementById("rentProperties").textContent = data.stats.rent;

          // Pagination
          const pagination = document.getElementById("pagination");
          pagination.innerHTML = "";
          for (let i = 1; i <= data.totalPages; i++) {
            pagination.innerHTML += `
              <li class="page-item ${i === data.currentPage ? 'active' : ''}">
                <button class="page-link pageBtn" data-page="${i}">${i}</button>
              </li>
            `;
          }
        });
    }

    // Add Property Form Submit
    document.getElementById("addPropertyForm").addEventListener("submit", function(e) {
      e.preventDefault();
      const formData = new FormData(this);

      fetch("pro_property.php", {
        method: "POST",
        body: formData
      })
      .then(res => res.json())
      .then(data => {
        alert(data.message);
        if (data.success) {
          document.getElementById("addPropertyForm").reset();
          bootstrap.Modal.getInstance(document.getElementById("addPropertyModal")).hide();
          fetchProperties(); // ✅ reload table properly
        }
      })
      .catch(err => console.error(err));
    });

    // Initial load
    fetchProperties();

    // Filter change
    document.getElementById("propertyFilter").addEventListener("change", function() {
      fetchProperties(this.value, 1);
    });

    // Pagination click
    document.addEventListener("click", function(e) {
      if (e.target.classList.contains("pageBtn")) {
        fetchProperties(document.getElementById("propertyFilter").value, parseInt(e.target.dataset.page));
      }
    });

    // Delete property
    document.addEventListener("click", function(e) {
      if (e.target.classList.contains("deleteBtn")) {
        const id = e.target.dataset.id;
        if (confirm("Are you sure you want to delete this property?")) {
          fetch("delete_property.php", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "id=" + encodeURIComponent(id)
          })
          .then(res => res.json())
          .then(data => {
            alert(data.message);
            if (data.success) {
              fetchProperties(); // ✅ refresh list
            }
          })
          .catch(err => console.error("Error:", err));
        }
      }
    });
  });
  </script>
</section>

<section id="adverts" class="my-5">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4>Adverts</h4>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createAdvertModal">
      + Create Advert
    </button>
  </div>

  <!-- Summary Cards -->
  <div class="row g-3 mb-4">
    <div class="col-md-4">
      <div class="card shadow-sm text-center p-3">
        <h6>Total Adverts</h6>
        <p id="totalAdverts" class="fw-bold fs-5">0</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card shadow-sm text-center p-3">
        <h6>Active</h6>
        <p id="activeAdverts" class="fw-bold fs-5 text-success">0</p>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card shadow-sm text-center p-3">
        <h6>Expired</h6>
        <p id="expiredAdverts" class="fw-bold fs-5 text-danger">0</p>
      </div>
    </div>
  </div>

  <!-- Adverts Table -->
  <div class="table-responsive">
    <table class="table table-bordered table-striped">
      <thead class="table-light">
        <tr>
          <th>Property</th>
          <th>Location</th>
          <th>Start Date</th>
          <th>End Date</th>
          <th>Status</th>
          <th>Created</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody id="advertsTableBody">
        <!-- Filled dynamically via JS -->
      </tbody>
    </table>
  </div>

  <!-- Create Advert Modal -->
  <div class="modal fade" id="createAdvertModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
      <div class="modal-content">
        <form id="createAdvertForm" method="POST" action="process_advert.php">
          <div class="modal-header">
            <h5 class="modal-title">Create Advert</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">

            <!-- Select Property -->
            <div class="mb-3">
              <label class="form-label">Select Property</label>
              <select name="property_id" id="property_id" class="form-select" required>
                <option value="">-- Choose Property --</option>
                <?php
                $stmt = $conn->prepare("SELECT id, title FROM properties WHERE user_id=?");
                $stmt->bind_param("i", $_SESSION['user_id']);
                $stmt->execute();
                $res = $stmt->get_result();
                while ($prop = $res->fetch_assoc()) {
                  echo "<option value='{$prop['id']}'>" . htmlspecialchars($prop['title']) . "</option>";
                }
                $stmt->close();
                ?>
              </select>
            </div>

            <!-- Dates -->
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Start Date</label>
                <input type="date" name="start_date" id="start_date" class="form-control" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">End Date</label>
                <input type="date" name="end_date" id="end_date" class="form-control" required>
              </div>
            </div>

            <!-- Duration & Cost -->
            <div class="row g-3 mt-2">
              <div class="col-md-6">
                <label class="form-label">Duration (days)</label>
                <input type="text" id="duration" class="form-control" readonly>
              </div>
              <div class="col-md-6">
                <label class="form-label">Total Cost (₦)</label>
                <input type="text" id="total_cost" name="total_cost" class="form-control" readonly>
              </div>
            </div>

            <!-- Location -->
            <div class="mb-3 mt-3">
              <label class="form-label">Advert Location</label>
              <select name="location" id="location" class="form-select" required>
                <?php
                $planQ = $conn->prepare("SELECT subscription_plan FROM users WHERE id=?");
                $planQ->bind_param("i", $_SESSION['user_id']);
                $planQ->execute();
                $planRes = $planQ->get_result();
                $plan = "basic";
                if ($planRes->num_rows > 0) {
                  $plan = strtolower($planRes->fetch_assoc()['subscription_plan']);
                }
                $planQ->close();

                if ($plan === "premium") {
                  echo '<option value="homepage">Homepage (₦500/day)</option>';
                  echo '<option value="property_details">Property Details (₦300/day)</option>';
                } else {
                  echo '<option value="property_details">Property Details (₦300/day)</option>';
                }
                ?>
              </select>
            </div>

            <!-- Terms -->
            <div class="form-check mb-3">
              <input type="checkbox" class="form-check-input" id="terms" name="terms">
              <label class="form-check-label" for="terms">I agree to the terms and conditions</label>
            </div>
          </div>

          <div class="modal-footer">
            <button type="submit" class="btn btn-primary" id="submitAdvertBtn" disabled>Submit Advert</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          </div>
        </form>
      </div>
    </div>
  </div>
 </section>
 <script>
 document.addEventListener("DOMContentLoaded", () => {

  const totalEl = document.getElementById("totalAdverts");
  const activeEl = document.getElementById("activeAdverts");
  const expiredEl = document.getElementById("expiredAdverts");
  const tableBody = document.getElementById("advertsTableBody");

  function fetchAdverts() {
    fetch("fetch_agent_adverts.php")
      .then(res => res.json())
      .then(data => {
        if (data.error) {
          alert(data.error);
          return;
        }

        // Update summary cards
        totalEl.textContent = data.counts.total;
        activeEl.textContent = data.counts.active;
        expiredEl.textContent = data.counts.expired;

        // Populate table
        tableBody.innerHTML = "";
        data.adverts.forEach(ad => {
          tableBody.innerHTML += `
            <tr>
              <td>${ad.property_title}</td>
              <td>${ad.location}</td>
              <td>${ad.start_date}</td>
              <td>${ad.end_date}</td>
              <td>${ad.status}</td>
              <td>${ad.created_at}</td>
              <td>
                <button class="btn btn-sm btn-danger deleteAdvertBtn" data-id="${ad.id}">Delete</button>
              </td>
            </tr>
          `;
        });
      })
      .catch(err => console.error(err));
  }

  // Initial fetch
  fetchAdverts();

  // Delete advert
  document.addEventListener("click", e => {
    if (e.target.classList.contains("deleteAdvertBtn")) {
      const id = e.target.dataset.id;
      if (confirm("Are you sure you want to delete this advert?")) {
        fetch("delete_advert.php", {
          method: "POST",
          headers: {"Content-Type": "application/x-www-form-urlencoded"},
          body: "id=" + id
        })
        .then(res => res.json())
        .then(data => {
          alert(data.message);
          if (data.success) fetchAdverts(); // reload table & counts
        });
      }
    }
  });

  // Enable submit button only if terms checked
  const termsCheckbox = document.getElementById("terms");
  const submitBtn = document.getElementById("submitAdvertBtn");
  termsCheckbox.addEventListener("change", () => {
    submitBtn.disabled = !termsCheckbox.checked;
  });

  // Optional: Refresh table after modal closes (in case advert was created via redirect)
  const createModal = document.getElementById("createAdvertModal");
  createModal.addEventListener('hidden.bs.modal', fetchAdverts);

 });
 </script>
 <script>
 document.addEventListener("DOMContentLoaded", () => {
  const startDate = document.getElementById("start_date");
  const endDate = document.getElementById("end_date");
  const location = document.getElementById("location");
  const durationField = document.getElementById("duration");
  const costField = document.getElementById("total_cost");
  const terms = document.getElementById("terms");
  const submitBtn = document.getElementById("submitAdvertBtn");

  // Enable submit only if terms checked
  terms.addEventListener("change", () => {
    submitBtn.disabled = !terms.checked;
  });

  // Calculate duration & cost
  function calculateCost() {
    const start = new Date(startDate.value);
    const end = new Date(endDate.value);
    if (!isNaN(start) && !isNaN(end) && end >= start) {
      const days = Math.ceil((end - start) / (1000*60*60*24)) + 1;
      durationField.value = days;

      let rate = (location.value === "homepage") ? 500 : 300;
      costField.value = (days * rate).toFixed(2);
    } else {
      durationField.value = "";
      costField.value = "";
    }
  }

  [startDate, endDate, location].forEach(el => el.addEventListener("change", calculateCost));
  });
</script>

<section id="transactions" class="container py-4">
  <h4 class="mb-3">Transactions</h4>

  <?php
  require_once "config.php";
  if (!isset($_SESSION)) { session_start(); }

  if (!isset($_SESSION['user_id'])) {
      echo "<p class='text-danger'>You must be logged in to view your transactions.</p>";
  } else {
      $user_id = $_SESSION['user_id'];

      // ✅ Fetch wallet balance
      $bal_stmt = $conn->prepare("SELECT balance, currency FROM users WHERE id = ?");
      $bal_stmt->bind_param("i", $user_id);
      $bal_stmt->execute();
      $bal_result = $bal_stmt->get_result()->fetch_assoc();
      $bal_stmt->close();

      $balance = $bal_result['balance'] ?? 0;
      $currency = $bal_result['currency'] ?? "NGN";

      echo "<div class='mb-3'>
              <strong>Wallet Balance:</strong> 
              <span class='fs-5 text-success'>{$currency} " . number_format($balance, 2) . "</span>
            </div>";

      // ✅ Fetch all transactions
      $sql = "SELECT id, type, amount, currency, description, reference, status, created_at 
              FROM transactions 
              WHERE user_id = ?
              ORDER BY created_at DESC";
      $stmt = $conn->prepare($sql);
      $stmt->bind_param("i", $user_id);
      $stmt->execute();
      $result = $stmt->get_result();

      if ($result->num_rows > 0) {
          // ✅ Dropdown filter
          echo '<div class="mb-3">
                  <label for="filter" class="form-label me-2">Filter:</label>
                  <select id="filter" class="form-select d-inline-block w-auto">
                      <option value="all">All</option>
                      <option value="credit">Credit</option>
                      <option value="debit">Debit</option>
                      <option value="deposit">Deposit</option>
                      <option value="adverts">Adverts</option>
                      <option value="uploads">Uploads</option>
                  </select>
                </div>';

          echo '<div class="table-responsive">';
          echo '<table class="table table-bordered table-striped" id="transactionsTable">';
          echo '<thead class="table-light">
                  <tr>
                      <th>#</th>
                      <th>Type</th>
                      <th>Amount</th>
                      <th>Description</th>
                      <th>Reference</th>
                      <th>Status</th>
                      <th>Date</th>
                  </tr>
                </thead><tbody>';

          $counter = 1; // sequential numbering
          while ($row = $result->fetch_assoc()) {
              $desc = strtolower($row['description']);
              $classes = "all " . strtolower($row['type']);
              if (strpos($desc, 'deposit') !== false) $classes .= " deposit";
              if (strpos($desc, 'advert') !== false) $classes .= " adverts";
              if (strpos($desc, 'upload') !== false) $classes .= " uploads";

              echo "<tr class='{$classes}'>
                      <td>{$counter}</td> <!-- sequential numbering -->
                      <td>" . ucfirst($row['type']) . "</td>
                      <td>{$row['currency']} " . number_format($row['amount'], 2) . "</td>
                      <td>{$row['description']}</td>
                      <td>{$row['reference']}</td>
                      <td><span class='badge bg-" . 
                          ($row['status'] === 'completed' ? "success" : ($row['status'] === 'pending' ? "warning" : "danger")) . 
                          "'>{$row['status']}</span></td>
                      <td>" . date("M d, Y H:i", strtotime($row['created_at'])) . "</td>
                    </tr>";
              $counter++;
          }
          echo '</tbody></table></div>';
      } else {
          echo "<p class='text-muted'>No transactions found.</p>";
      }
      $stmt->close();
  }
  ?>
</section>

<script>
document.getElementById('filter').addEventListener('change', function() {
    let filter = this.value;
    let rows = document.querySelectorAll('#transactionsTable tbody tr');
    rows.forEach(row => {
        if (filter === 'all') {
            row.style.display = '';
        } else if (row.classList.contains(filter)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
});
</script>



<section id="profile" class="container py-5">
  <div class="row justify-content-center">
    <div class="col-md-6">
      <div class="card profile-card shadow-lg border-0 rounded-3">
        <div class="card-body text-center">
          <!-- Profile Image -->
          <div class="profile-img-container mb-3">
    <img src="<?= !empty($agent_info['image']) ? 'uploads/' . htmlspecialchars($agent_info['image']) : 'images/default-avatar.png' ?>" 
         alt="Profile Image" 
         id="profileImage" 
         class="rounded-circle border profile-img">
 </div>


          <!-- Agent Details -->
          <h5 class="card-title mb-1">
            <?= htmlspecialchars($agent_info['first_name'].' '.$agent_info['last_name']) ?>
          </h5>
          <p class="text-muted mb-2"><?= htmlspecialchars($agent_info['email']) ?></p>
          <p class="mb-1"><i class="bi bi-phone"></i> <?= htmlspecialchars($agent_info['phone']) ?></p>
          <span class="badge bg-success">
            Plan: <?= htmlspecialchars($agent_info['subscription_plan'] ?? 'Free') ?>
          </span>

          <!-- Edit Button -->
          <div class="mt-4">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editProfileModal">
              <i class="bi bi-pencil-square"></i> Edit Profile
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Edit Profile Modal -->
<div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content rounded-3">
      <div class="modal-header">
        <h5 class="modal-title" id="editProfileModalLabel">Edit Profile</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="editProfileForm" action="agent_profile.php" method="POST" enctype="multipart/form-data">
          
          <!-- Image Upload with Preview -->
          <div class="mb-3 text-center">
            <img src="<?= !empty($agent_info['image']) ? 'uploads/' . htmlspecialchars($agent_info['image']) : 'images/default-avatar.png' ?>" 
         alt="Profile Image" 
         id="profileImage" 
         class="rounded-circle border profile-img">
            <input type="file" name="profile_image" id="profileImageInput" class="form-control" accept="image/*">
          </div>

          <!-- Change Password -->
          <div class="mb-3">
            <label for="password" class="form-label">New Password</label>
            <input type="password" name="password" id="password" class="form-control">
          </div>
          <div class="mb-3">
            <label for="confirmPassword" class="form-label">Confirm Password</label>
            <input type="password" name="confirm_password" id="confirmPassword" class="form-control">
          </div>

          <button type="submit" class="btn btn-success w-100">Save Changes</button>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- Custom CSS -->
<style>
.profile-card {
  background: #fff;
  padding: 20px;
}
.profile-img-container {
  position: relative;
  display: inline-block;
}
.profile-img {
  width: 120px;
  height: 120px;
  object-fit: cover;
}
</style>

<!-- Preview JS -->
<script>
document.getElementById('profileImageInput').addEventListener('change', function(e){
  const [file] = e.target.files;
  if (file) {
    document.getElementById('previewImage').src = URL.createObjectURL(file);
  }
});
</script>





  </div>

  <script>
    const sidebar = document.getElementById('sidebar');
    const topNav = document.getElementById('top-nav');
    const mainContent = document.getElementById('main-content');
    const toggleBtn = document.getElementById('sidebarToggle');

    toggleBtn.addEventListener('click', () => {
      sidebar.classList.toggle('collapsed');
      topNav.classList.toggle('collapsed');
      mainContent.classList.toggle('collapsed');
    });

    // Smooth scroll for sidebar menu
    document.querySelectorAll('#sidebar .menu a[href^="#"]').forEach(link => {
      link.addEventListener('click', function(e){
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if(target){
          target.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
        // Auto close sidebar on small screens
        if(window.innerWidth <= 992){
          sidebar.classList.remove('collapsed');
          topNav.classList.remove('collapsed');
          mainContent.classList.remove('collapsed');
        }
      });
    });
  </script>
</body>
</html>
