<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
requireLogin();
updateOverdueLoans($conn);

$search   = trim($_GET['search'] ?? '');
$page     = max(1, intval($_GET['page'] ?? 1));
$per_page = 20;
$result   = getPaginatedBorrowers($conn, $search, $page, $per_page);
$borrowers = $result['data'];
$total_pages = $result['pages'];
$total = $result['total'];

include 'includes/header.php';
include 'includes/sidebar.php';
?>
<div class="row mb-4">
    <div class="col-lg-8"><h3><i class="fas fa-users"></i> Borrowers</h3></div>
    <div class="col-lg-4 text-end">
        <a href="/cash_lending/add-borrower.php" class="btn btn-primary">
            <i class="fas fa-user-plus"></i> Add Borrower
        </a>
    </div>
</div>

<div class="card mb-3">
    <div class="card-body py-2">
        <form method="GET" class="d-flex gap-2">
            <input type="text" class="form-control" name="search" placeholder="Search name, contact, ID number…"
                   value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit" class="btn btn-outline-primary px-3"><i class="fas fa-search"></i></button>
            <?php if ($search): ?>
                <a href="/cash_lending/borrowers.php" class="btn btn-outline-secondary px-3"><i class="fas fa-times"></i></a>
            <?php endif; ?>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Borrowers List</h5>
        <small class="text-muted"><?php echo number_format($total); ?> total</small>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($borrowers)): ?>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th style="width:50px;">Photo</th>
                        <th>Name</th>
                        <th>Contact</th>
                        <th>ID Type</th>
                        <th>ID Number</th>
                        <th>Occupation</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($borrowers as $b):
                        $initials  = urlencode($b['first_name'].'+'. $b['last_name']);
                        $photo_src = !empty($b['photo']) && file_exists($b['photo'])
                            ? '/cash_lending/'.$b['photo']
                            : "https://ui-avatars.com/api/?name={$initials}&size=40&background=0d6efd&color=fff&rounded=true";
                    ?>
                    <tr>
                        <td><img src="<?php echo htmlspecialchars($photo_src); ?>"
                                 style="width:38px;height:38px;border-radius:50%;object-fit:cover;" alt=""></td>
                        <td><strong><?php echo htmlspecialchars($b['first_name'].' '.$b['last_name']); ?></strong></td>
                        <td><?php echo htmlspecialchars($b['contact']); ?></td>
                        <td><?php echo htmlspecialchars($b['id_type']); ?></td>
                        <td><?php echo htmlspecialchars($b['id_number']); ?></td>
                        <td><?php echo htmlspecialchars($b['occupation'] ?? '—'); ?></td>
                        <td>
                            <a href="/cash_lending/edit-borrower.php?id=<?php echo $b['id']; ?>"
                               class="btn btn-sm btn-outline-primary" title="Edit">
                                <i class="fas fa-edit"></i>
                            </a>
                            <button class="btn btn-sm btn-outline-danger" title="Delete"
                                    onclick="deleteBorrower(<?php echo $b['id']; ?>,'<?php echo htmlspecialchars($b['first_name'].' '.$b['last_name']); ?>',<?php echo intval($b['loan_count']??0); ?>,<?php echo intval($b['payment_count']??0); ?>)">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if ($total_pages > 1): ?>
        <div class="d-flex justify-content-between align-items-center p-3 border-top">
            <small class="text-muted">
                Showing <?php echo (($page-1)*$per_page)+1; ?>–<?php echo min($page*$per_page,$total); ?>
                of <?php echo number_format($total); ?>
            </small>
            <nav><ul class="pagination pagination-sm mb-0">
                <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                    <li class="page-item <?php echo $p===$page?'active':''; ?>">
                        <a class="page-link" href="?page=<?php echo $p; ?>&search=<?php echo urlencode($search); ?>">
                            <?php echo $p; ?>
                        </a>
                    </li>
                <?php endfor; ?>
            </ul></nav>
        </div>
        <?php endif; ?>

        <?php else: ?>
            <div class="empty-state p-5 text-center">
                <i class="fas fa-users fa-3x mb-3 text-muted opacity-25"></i>
                <h5><?php echo $search ? 'No results for "'.$search.'"' : 'No Borrowers Yet'; ?></h5>
                <a href="/cash_lending/add-borrower.php" class="btn btn-primary mt-3">
                    <i class="fas fa-user-plus"></i> Add Borrower
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function deleteBorrower(id, name, loans, payments) {
    const details = loans > 0
        ? '\n\nThis will also permanently delete:\n  \u2022 ' + loans + ' loan record(s)\n  \u2022 ' + payments + ' payment(s)'
        : '';
    if (!confirm('Delete borrower "' + name + '"?' + details + '\n\nThis cannot be undone.')) return;
    fetch('/cash_lending/api/delete-borrower.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'id=' + id
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) location.reload();
        else alert(data.message || 'Error deleting borrower');
    });
}
</script>
<?php include 'includes/footer.php'; ?>
