<?php 
//index2.php

include 'db_connect.php'; ?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Partners and Agreements Viewer</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
  <style>
    body {
      background-color: #f8f9fa;
    }
    .navbar {
      background-color: #343a40 !important;
      box-shadow: 0 2px 4px rgba(0,0,0,.1);
    }
    .navbar-brand, .nav-link {
      color: #fff !important;
    }
    .nav-link.active {
      font-weight: bold;
      border-bottom: 2px solid #0d6efd;
    }
    .card-header {
      background-color: #0d6efd;
      color: #fff;
      font-weight: bold;
    }
    .profile-img {
      width: 50px;
      height: 50px;
      object-fit: cover;
      border-radius: 50%;
    }
    .table-responsive {
      margin-top: 20px;
    }
    .card {
      border: none;
      box-shadow: 0 4px 8px rgba(0,0,0,.05);
    }
  </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#"><i class="fas fa-handshake"></i> Partner Portal</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" href="partners_view_general_Contribution_details.php"><i class="fas fa-list-ul"></i> View Partners</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="add_Partnership.php"><i class="fas fa-user-plus"></i> Add Partner</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

<div class="container mt-5">
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span><i class="fas fa-users"></i> Partner Agreements</span>
      <a href="add_Partnership.php" class="btn btn-light btn-sm">
        <i class="fas fa-plus"></i> Add New Partner
      </a>
    </div>
    <div class="card-body">
      <form method="GET" class="row g-2 mb-4 align-items-center">
        <div class="col-md-6">
          <div class="input-group">
            <input type="text" name="search" class="form-control" placeholder="Search by Partner Code or Name"
                   value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
            <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i> Search</button>
          </div>
        </div>
      </form>

      <div class="table-responsive">
        <table class="table table-bordered table-hover bg-white">
          <thead class="table-dark">
            <tr>
              <th>#</th>
              <th>Profile</th>
              <th>Partner Code</th>
              <th>Partner Name</th>
              <th>Partnership Type</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php
            $search = isset($_GET['search']) ? trim($_GET['search']) : '';

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

            // Count total records
            $count_sql = "SELECT COUNT(*) as total 
                          FROM Partners p
                          LEFT JOIN Partnership_Agreements pa ON pa.partner_id = p.partner_id
                          LEFT JOIN Partnership_Types pt ON pt.partnership_type_id = pa.partnership_type_id";
            if ($search !== '') {
                $count_sql .= " WHERE p.partner_code LIKE ? OR p.partner_name LIKE ?";
                $stmt = $conn->prepare($count_sql);
                $likeSearch = "%$search%";
                $stmt->bind_param("ss", $likeSearch, $likeSearch);
                $stmt->execute();
                $count_result = $stmt->get_result();
                $total_rows = $count_result->fetch_assoc()['total'];
                $stmt->close();
            } else {
                $count_result = $conn->query($count_sql);
                $total_rows = $count_result->fetch_assoc()['total'];
            }

            $total_pages = ceil($total_rows / $limit);

            // Main query
            $sql = "SELECT p.partner_id, p.partner_code, p.partner_name, p.profile_image_url,
                           pt.type_name, pt.type_range
                    FROM Partners p
                    LEFT JOIN Partnership_Agreements pa ON pa.partner_id = p.partner_id
                    LEFT JOIN Partnership_Types pt ON pt.partnership_type_id = pa.partnership_type_id";

            if ($search !== '') {
                $sql .= " WHERE p.partner_code LIKE ? OR p.partner_name LIKE ?";
            }

            $sql .= " ORDER BY p.partner_id DESC LIMIT ? OFFSET ?";

            if ($search !== '') {
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ssii", $likeSearch, $likeSearch, $limit, $offset);
                $stmt->execute();
                $result = $stmt->get_result();
            } else {
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ii", $limit, $offset);
                $stmt->execute();
                $result = $stmt->get_result();
            }

            $index = $offset + 1;
            if ($result && $result->num_rows > 0) {
              while ($row = $result->fetch_assoc()) {
                $image = !empty($row['profile_image_url']) ? $row['profile_image_url'] : 'https://via.placeholder.com/50';
                echo "<tr>
                        <td>{$index}</td>
                        <td><img src='" . htmlspecialchars($image) . "' class='profile-img' alt='Profile image of " . htmlspecialchars($row['partner_name']) . "'></td>
                        <td>" . htmlspecialchars($row['partner_code']) . "</td>
                        <td>" . htmlspecialchars($row['partner_name']) . "</td>
                        <td><strong>" . htmlspecialchars($row['type_name'] ?? 'N/A') . "</strong><br><small>" . htmlspecialchars($row['type_range'] ?? '') . "</small></td>
                        <td>
                          <a href='edit_partnership.php?id={$row['partner_id']}' class='btn btn-info btn-sm me-1'><i class='fas fa-eye'></i> View</a>
                          <a href='send_confirm_registration_sms_for_index2_php_page.php?id={$row['partner_id']}' class='btn btn-warning btn-sm me-1'><i class='fas fa-edit'></i> Send SmS</a>
                          <button type='button' class='btn btn-danger btn-sm' data-bs-toggle='modal' data-bs-target='#deleteModal' data-partner-id='{$row['partner_id']}' data-partner-name='" . htmlspecialchars($row['partner_name']) . "'>
                            <i class='fas fa-trash'></i> Delete
                          </button>
                        </td>
                      </tr>";
                $index++;
              }
            } else {
              echo "<tr><td colspan='6' class='text-center'>No partners found.</td></tr>";
            }
            $stmt->close();
            $conn->close();
          ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <nav>
        <ul class="pagination justify-content-center">
          <?php if ($page > 1): ?>
            <li class="page-item"><a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>">Previous</a></li>
          <?php endif; ?>
          
          <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
              <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
            </li>
          <?php endfor; ?>
          
          <?php if ($page < $total_pages): ?>
            <li class="page-item"><a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>">Next</a></li>
          <?php endif; ?>
        </ul>
      </nav>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Are you sure you want to delete <strong id="partnerName"></strong>? This action cannot be undone.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <a href="#" id="confirmDeleteButton" class="btn btn-danger">Delete</a>
      </div>
    </div>
  </div>
</div>

<!-- JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    var deleteModal = document.getElementById('deleteModal');
    deleteModal.addEventListener('show.bs.modal', function (event) {
      var button = event.relatedTarget;
      var partnerId = button.getAttribute('data-partner-id');
      var partnerName = button.getAttribute('data-partner-name');

      document.getElementById('partnerName').textContent = partnerName;
      document.getElementById('confirmDeleteButton').href = 'delete_partner.php?id=' + partnerId;
    });
  });
</script>
<!-- SMS Preview Modal -->
<div class="modal fade" id="smsPreviewModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content shadow-lg border-0">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fas fa-sms"></i> SMS Preview</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p><strong>📱 Recipient:</strong> <span id="previewPhone"></span></p>
        <p><strong>👤 Partner Name:</strong> <span id="previewName"></span></p>
        <p><strong>🔑 Partner Code:</strong> <span id="previewCode"></span></p>
        <hr>
        <p><strong>✉️ Message Content:</strong></p>
        <div class="alert alert-light border p-3" id="previewMessage"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" id="confirmSendBtn" class="btn btn-success">
          <i class="fas fa-paper-plane"></i> Send SMS
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Spinner Overlay -->
<div id="loadingOverlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%;
 background:rgba(255,255,255,0.85); z-index:2000; text-align:center; padding-top:15%;">
  <div class="spinner-border text-primary" role="status" style="width:5rem; height:5rem;"></div>
  <p class="mt-3 fw-bold">Sending SMS... Please wait</p>
</div>

<!-- Success/Error Toast -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index:3000">
  <div id="smsToast" class="toast align-items-center border-0" role="alert">
    <div class="d-flex">
      <div id="smsToastBody" class="toast-body text-white"></div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
    </div>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
  // Intercept Send SMS buttons
  document.querySelectorAll("a[href^='send_confirm_registration_sms_for_index2_php_page.php?id=']").forEach(btn => {
    btn.addEventListener("click", function(e) {
      e.preventDefault();
      let url = new URL(btn.href, window.location.origin);
      let partnerId = url.searchParams.get("id");

      // Fetch preview details (use same endpoint with GET for preview only)
      fetch("send_confirm_registration_sms_for_index2_php_page.php?id=" + partnerId)
        .then(res => res.json())
        .then(data => {
          if (!data || data.status === "error") {
            alert("❌ Failed to fetch SMS preview. Try again.");
            return;
          }

          // Fill modal with details
          document.getElementById("previewName").textContent   = data.partner_name ?? "Unknown";
          document.getElementById("previewCode").textContent   = data.partner_code ?? "N/A";
          document.getElementById("previewPhone").textContent  = data.recipient_phone ?? "N/A";
          document.getElementById("previewMessage").textContent = data.full_message ?? (
            "Nguvu ya Omega, ndugu " + (data.partner_name ?? "") +
            ", umesajiliwa kwenye Haleluya TV partner na namba yako ni: " + (data.partner_code ?? "")
          );

          // Show modal
          let previewModal = new bootstrap.Modal(document.getElementById("smsPreviewModal"));
          previewModal.show();

          // Confirm send
          document.getElementById("confirmSendBtn").onclick = function() {
            previewModal.hide();
            document.getElementById("loadingOverlay").style.display = "block";

            fetch("send_confirm_registration_sms_for_index2_php_page.php", {
              method: "POST",
              headers: { "Content-Type": "application/x-www-form-urlencoded" },
              body: "partner_id=" + partnerId
            })
            .then(res => res.json())
            .then(result => {
              document.getElementById("loadingOverlay").style.display = "none";

              let toastEl = document.getElementById("smsToast");
              let toastBody = document.getElementById("smsToastBody");
              toastEl.classList.remove("bg-success", "bg-danger");

              if (result.status === "success") {
                toastEl.classList.add("bg-success");
                toastBody.textContent = "✅ " + result.message;
              } else {
                toastEl.classList.add("bg-danger");
                toastBody.textContent = "❌ " + result.message;
              }

              new bootstrap.Toast(toastEl).show();

              if (result.status === "success") {
                setTimeout(() => { window.location.href = "index2.php"; }, 2500);
              }
            })
            .catch(err => {
              document.getElementById("loadingOverlay").style.display = "none";
              alert("⚠️ Error: " + err);
            });
          };
        })
        .catch(err => {
          alert("⚠️ Fetch failed: " + err);
        });
    });
  });
});
</script>


</body>
</html>
