<?php
require 'header.php';
require 'db.php';

// compute total bondhoki amount
$total_bondhoki = 0.0;
$tres = $conn->query("SELECT COALESCE(SUM(amount),0) AS total FROM bondhoki_customers");
if ($tres) {
    $trow = $tres->fetch_assoc();
    $total_bondhoki = floatval($trow['total'] ?? 0);
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
<style>
.container{max-width:1100px;margin:20px auto}
.table{width:100%;border-collapse:collapse;background:#fff;box-shadow:0 6px 18px rgba(0,0,0,0.05);border-radius:10px;overflow:hidden}
th,td{padding:10px 12px;border-bottom:1px solid #eee;text-align:left}
th{background:#0ea5a4;color:#fff;font-weight:600}
tr:hover{background:#f9fafb}
.btn{padding:6px 10px;border-radius:8px;text-decoration:none;color:#fff;background:#0ea5a4;cursor:pointer;border:none}
.btn-danger{background:#dc2626}
.btn-warning{background:#f59e0b}
.details{display:none;background:#f9fafb;padding:12px;border-radius:8px;margin-top:10px}
.month-table{width:100%;border-collapse:collapse;margin-top:8px}
.month-table th,.month-table td{padding:8px;border:1px solid #ddd;font-size:14px;text-align:center}
.paid{background:#e0f2fe;color:#0369a1}
.unpaid{background:#fee2e2;color:#991b1b}
.search-box{margin-bottom:15px;display:flex;justify-content:space-between;align-items:center}
.search-box input{padding:8px 10px;border:1px solid #ccc;border-radius:8px;width:240px}
.header-btns a{background:#0ea5a4;color:#fff;padding:8px 12px;border-radius:8px;text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-weight:600}
.modal{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);display:none;align-items:center;justify-content:center;z-index:9999}
.modal-content{background:#fff;padding:20px;border-radius:10px;width:400px;max-width:90%;box-shadow:0 4px 16px rgba(0,0,0,0.3)}
.modal-content h3{margin-top:0}
.modal img{width:120px;border-radius:8px;background:#f3f4f6;padding:6px;margin-bottom:10px}
.close-btn{background:#ef4444;color:#fff;border:none;border-radius:6px;padding:6px 10px;cursor:pointer;float:right}

/* total pill */
.total-pill{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:999px;background:linear-gradient(90deg,#fff,#f3f9ff);border:1px solid #e6f0ff;color:#0b63d6;font-weight:700;margin-left:8px}
.total-pill .label{font-size:12px;color:#6b7280;font-weight:600;margin-right:6px}

@media (max-width:880px){
  .search-box input{width:160px}
}
</style>

<div class="container">
  <div class="search-box">
    <h2 style="margin:0;color:#0ea5a4;font-weight:700;">Bondhoki Customer List</h2>

    <div style="display:flex;gap:12px;align-items:center">
      <!-- total bondhoki amount pill -->
      <div class="total-pill" title="Total Bondhoki Amount">
        <span class="label">Total</span>
        <span>৳ <?php echo number_format($total_bondhoki,2) ?></span>
      </div>

      <div class="header-btns">
        <a href="bondhoki.php"><i class="bi bi-person-plus"></i> Add Customer</a>
        <a href="dashboard.php" style="background:#3b82f6"><i class="bi bi-house-door"></i> Dashboard</a>
      </div>
    </div>
  </div>

  <p style="color:#64748b;margin-bottom:12px">গ্রাহকদের সম্পূর্ণ বন্ধকি তালিকা ও মাসভিত্তিক কিস্তি হিসাব।</p>

  <div class="search-box">
    <input type="text" id="searchInput" placeholder="🔍 Search customer...">
  </div>

  <table class="table" id="customerTable">
    <tr>
      <th>ID</th>
      <th>Customer Name</th>
      <th>Phone</th>
      <th>Item</th>
      <th>Amount (৳)</th>
      <th>Profit %</th>
      <th>Months</th>
      <th>Status</th>
      <th>Action</th>
    </tr>

<?php
$res = $conn->query("SELECT * FROM bondhoki_customers ORDER BY id DESC");
while($row = $res->fetch_assoc()):
  $imgFile = trim($row['image'] ?? $row['item_image'] ?? '');
  if (empty($imgFile)) {
      $imgPath = 'uploads/bondhoki_images/no_image.png';
  } elseif (str_starts_with($imgFile, 'uploads/')) {
      $imgPath = $imgFile;
  } else {
      $imgPath = 'uploads/bondhoki_images/' . $imgFile;
  }
  if (!file_exists($imgPath)) {
      $imgPath = 'uploads/bondhoki_images/no_image.png';
  }
?>
    <tr>
      <td><?php echo $row['id']; ?></td>
      <td><?php echo htmlspecialchars($row['name']); ?></td>
      <td><?php echo htmlspecialchars($row['phone']); ?></td>
      <td><?php echo htmlspecialchars($row['item_name']); ?></td>
      <td><?php echo number_format($row['amount'],2); ?></td>
      <td><?php echo $row['percent']; ?>%</td>
      <td><?php echo $row['months']; ?></td>
      <td><?php echo ucfirst($row['status']); ?></td>
      <td style="white-space:nowrap">
        <button class="btn viewBtn" data-id="<?php echo $row['id']; ?>">📋 Payments</button>
        <button class="btn" style="background:#3b82f6" data-name="<?php echo htmlspecialchars($row['name']); ?>" data-phone="<?php echo htmlspecialchars($row['phone']); ?>" data-item="<?php echo htmlspecialchars($row['item_name']); ?>" data-amount="<?php echo htmlspecialchars(number_format($row['amount'],2)); ?>" data-percent="<?php echo htmlspecialchars($row['percent']); ?>" data-img="<?php echo htmlspecialchars($imgPath); ?>" data-months="<?php echo (int)$row['months']; ?>" onclick="openViewModal(this)">👁 View</button>
        <button class="btn btn-warning editBtn"
          data-id="<?php echo $row['id']; ?>"
          data-name="<?php echo htmlspecialchars($row['name']); ?>"
          data-phone="<?php echo htmlspecialchars($row['phone']); ?>"
          data-item="<?php echo htmlspecialchars($row['item_name']); ?>"
          data-amount="<?php echo htmlspecialchars($row['amount']); ?>"
          data-percent="<?php echo htmlspecialchars($row['percent']); ?>"
          data-months="<?php echo htmlspecialchars($row['months']); ?>"
        ><i class="bi bi-pencil-square"></i> Edit</button>
        <button class="btn btn-danger deleteBtn" data-id="<?php echo $row['id']; ?>" data-name="<?php echo htmlspecialchars($row['name']); ?>"><i class="bi bi-trash"></i> Delete</button>
      </td>
    </tr>

    <tr class="details" id="details-<?php echo $row['id']; ?>">
      <td colspan="9">
        <h4>📅 Payment Schedule for <?php echo htmlspecialchars($row['name']); ?></h4>
        <table class="month-table">
          <tr>
            <th>Month</th>
            <th>Year</th>
            <th>Due (৳)</th>
            <th>Paid (৳)</th>
            <th>Status</th>
            <th>Action</th>
          </tr>

          <?php
          $pRes = $conn->query("SELECT * FROM bondhoki_payments WHERE bondhoki_id=".$row['id']." ORDER BY month_no ASC");
          $start = new DateTime($row['start_date']);
          while($p = $pRes->fetch_assoc()):
            $monthName = clone $start;
            $monthName->modify("+".($p['month_no']-1)." month");
            $statusClass = ($p['status']=='paid') ? 'paid' : 'unpaid';
          ?>
          <tr class="<?php echo $statusClass; ?>">
            <td><?php echo $monthName->format('F'); ?></td>
            <td><?php echo $monthName->format('Y'); ?></td>
            <td><?php echo number_format($p['due_amount'],2); ?></td>
            <td><?php echo number_format($p['paid_amount'],2); ?></td>
            <td><?php echo ucfirst($p['status']); ?></td>
            <td>
              <?php if($p['status']!='paid'): ?>
              <form method="post" action="payment_update.php" style="display:inline">
                <input type="hidden" name="payment_id" value="<?php echo $p['id']; ?>">
                <input type="hidden" name="pay_amount" value="<?php echo $p['due_amount']; ?>">
                <button type="submit" class="btn" style="padding:4px 8px;font-size:13px">Mark Paid</button>
              </form>
              <?php else: ?> ✅ Paid <?php endif; ?>
            </td>
          </tr>
          <?php endwhile; ?>
        </table>
      </td>
    </tr>
<?php endwhile; ?>
  </table>
</div>

<!-- View Modal -->
<div class="modal" id="viewModal">
  <div class="modal-content">
    <button class="close-btn" onclick="closeViewModal()">✖</button>
    <h3>👤 Customer Details</h3>
    <img id="custImage" src="uploads/bondhoki_images/no_image.png" alt="Customer Item">
    <p><strong>Name:</strong> <span id="custName"></span></p>
    <p><strong>Phone:</strong> <span id="custPhone"></span></p>
    <p><strong>Item:</strong> <span id="custItem"></span></p>
    <p><strong>Amount:</strong> ৳<span id="custAmount"></span></p>
    <p><strong>Profit %:</strong> <span id="custPercent"></span>%</p>
    <p><strong>Months:</strong> <span id="custMonths"></span></p>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal" id="editModal">
  <div class="modal-content" style="width:420px;max-width:90%;">
    <button class="close-btn" id="closeEdit">✖</button>
    <h3>✏️ Edit Bondhoki Customer</h3>
    <form id="editForm" method="post" action="update_bondhoki.php" enctype="multipart/form-data">
      <input type="hidden" name="id" id="editId">
      <label>Name:<br><input type="text" name="name" id="editName" required></label><br><br>
      <label>Phone:<br><input type="text" name="phone" id="editPhone" required></label><br><br>
      <label>Item Name:<br><input type="text" name="item_name" id="editItem" required></label><br><br>
      <label>Amount (৳):<br><input type="number" step="0.01" name="amount" id="editAmount" required></label><br><br>
      <label>Profit %:<br><input type="number" step="0.01" name="percent" id="editPercent" required></label><br><br>
      <label>Months:<br><input type="number" name="months" id="editMonths" min="1" required></label><br><br>
      <label>Change Image:<br><input type="file" name="image"></label><br><br>
      <button type="submit" class="btn" style="background:#0ea5a4;">💾 Update</button>
    </form>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal" id="deleteModal">
  <div class="modal-content" style="width:380px;text-align:center;">
    <button class="close-btn" id="closeDelete">✖</button>
    <h3 style="color:#dc2626">⚠️ Confirm Delete</h3>
    <p>Are you sure you want to delete <strong id="deleteName"></strong>?</p>
    <form id="deleteForm" method="post" action="bondhoki_delete.php">
      <input type="hidden" name="id" id="deleteId">
      <button type="submit" class="btn btn-danger">🗑 Confirm Delete</button>
    </form>
  </div>
</div>

<script>
document.querySelectorAll('.viewBtn').forEach(btn=>{
  btn.addEventListener('click',()=>{
    const id=btn.dataset.id;
    const detail=document.getElementById('details-'+id);
    if(detail.style.display==='table-row'){detail.style.display='none';}
    else{document.querySelectorAll('.details').forEach(d=>d.style.display='none');detail.style.display='table-row';}
  });
});

// View Modal
function openViewModal(btn){
  document.getElementById('custName').innerText=btn.dataset.name;
  document.getElementById('custPhone').innerText=btn.dataset.phone;
  document.getElementById('custItem').innerText=btn.dataset.item;
  document.getElementById('custAmount').innerText=btn.dataset.amount;
  document.getElementById('custPercent').innerText=btn.dataset.percent;
  document.getElementById('custMonths').innerText=btn.dataset.months;
  document.getElementById('custImage').src=btn.dataset.img;
  document.getElementById('viewModal').style.display='flex';
}
function closeViewModal(){document.getElementById('viewModal').style.display='none';}
window.addEventListener('click',e=>{if(e.target==document.getElementById('viewModal'))closeViewModal();});

// Edit Modal
const editModal=document.getElementById('editModal');
document.querySelectorAll('.editBtn').forEach(btn=>{
  btn.addEventListener('click',()=>{
    document.getElementById('editId').value=btn.dataset.id;
    document.getElementById('editName').value=btn.dataset.name;
    document.getElementById('editPhone').value=btn.dataset.phone;
    document.getElementById('editItem').value=btn.dataset.item;
    document.getElementById('editAmount').value=btn.dataset.amount;
    document.getElementById('editPercent').value=btn.dataset.percent;
    document.getElementById('editMonths').value=btn.dataset.months;
    editModal.style.display='flex';
  });
});
document.getElementById('closeEdit').addEventListener('click',()=>editModal.style.display='none');
window.addEventListener('click',e=>{if(e.target==editModal)editModal.style.display='none';});

// Delete Modal
const deleteModal=document.getElementById('deleteModal');
document.querySelectorAll('.deleteBtn').forEach(btn=>{
  btn.addEventListener('click',()=>{
    document.getElementById('deleteId').value=btn.dataset.id;
    document.getElementById('deleteName').innerText=btn.dataset.name;
    deleteModal.style.display='flex';
  });
});
document.getElementById('closeDelete').addEventListener('click',()=>deleteModal.style.display='none');
window.addEventListener('click',e=>{if(e.target==deleteModal)deleteModal.style.display='none';});

// Search
document.getElementById('searchInput').addEventListener('keyup',event=>{
  const val=event.target.value.toLowerCase();
  document.querySelectorAll('#customerTable tr').forEach((tr,i)=>{
    if(i===0)return;
    tr.style.display=tr.innerText.toLowerCase().includes(val)?'':'none';
  });
});
</script>

<?php require 'footer.php'; ?>
