<?php
require_once '../src/Database.php';
require_once '../src/Auth.php';
$auth = new Auth();
$auth->requireLogin();

$db = new Database();
$conn = $db->getConnection();

// Pagination settings
$items_per_page = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
if ($page < 1) $page = 1;

// Get filter parameters
$status_filter = isset($_GET['status']) ? trim($_GET['status']) : '';
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query based on filters
$where_clauses = [];
$params = [];

if ($status_filter) {
    $where_clauses[] = 'status = ?';
    $params[] = $status_filter;
}

if ($search_query) {
    $where_clauses[] = '(msisdn LIKE ? OR id_number LIKE ?)';
    $params[] = '%' . $search_query . '%';
    $params[] = '%' . $search_query . '%';
}

$where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

// Get total count
$total_count = 0;
try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM loan_requests $where_sql");
    $stmt->execute($params);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_count = $result['count'] ?? 0;
} catch (Exception $e) {
    $total_count = 0;
}

// Calculate pagination
$total_pages = ceil($total_count / $items_per_page);
if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
}

$offset = ($page - 1) * $items_per_page;

// Get paginated loan requests
$loan_requests = [];
try {
    $sql = "SELECT id, msisdn, id_number, loan_amount, status, created_at FROM loan_requests $where_sql ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
    $stmt = $conn->prepare($sql);
    
    // Bind filter parameters
    $paramIndex = 1;
    foreach ($params as $param) {
        $stmt->bindValue($paramIndex++, $param, PDO::PARAM_STR);
    }
    
    // Bind pagination parameters
    $stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    
    $stmt->execute();
    $loan_requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $loan_requests = [];
    error_log('Error fetching loan requests: ' . $e->getMessage());
}

// Get status counts for cards
$status_counts = [];
$statuses = ['pending', 'approved', 'rejected', 'disbursed'];
try {
    foreach ($statuses as $st) {
        $stmt = $conn->prepare('SELECT COUNT(*) as count FROM loan_requests WHERE status = ?');
        $stmt->execute([$st]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $status_counts[$st] = $result['count'] ?? 0;
    }
} catch (Exception $e) {
    // Ignore
}

// Get status color
function getStatusColor($status) {
    switch ($status) {
        case 'pending':
            return 'bg-yellow-100 text-yellow-800';
        case 'approved':
            return 'bg-blue-100 text-blue-800';
        case 'disbursed':
            return 'bg-green-100 text-green-800';
        case 'rejected':
            return 'bg-red-100 text-red-800';
        default:
            return 'bg-gray-100 text-gray-800';
    }
}

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $request_id = intval($_POST['request_id'] ?? 0);
    $new_status = $_POST['new_status'] ?? '';
    
    if ($request_id > 0 && in_array($new_status, $statuses)) {
        try {
            $stmt = $conn->prepare('UPDATE loan_requests SET status = ? WHERE id = ?');
            if ($stmt->execute([$new_status, $request_id])) {
                header('Location: loan_requests.php?page=' . $page . ($status_filter ? '&status=' . urlencode($status_filter) : '') . ($search_query ? '&search=' . urlencode($search_query) : ''));
                exit;
            }
        } catch (Exception $e) {
            // Error updating
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loan Requests - USSD System</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <?php include 'sidebar.php'; ?>
    <div class="md:ml-64 min-h-screen">
        <!-- Header -->
        <div class="bg-white shadow-md p-4 md:p-6 border-b border-gray-200">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Loan Requests</h1>
                <p class="text-gray-600 text-sm mt-1">Manage and track customer loan requests</p>
            </div>
        </div>

        <!-- Content -->
        <div class="p-4 md:p-8">
            <!-- Status Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Total Requests</p>
                            <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo number_format($total_count); ?></p>
                        </div>
                        <svg class="w-12 h-12 text-blue-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Pending</p>
                            <p class="text-3xl font-bold text-yellow-600 mt-2"><?php echo $status_counts['pending'] ?? 0; ?></p>
                        </div>
                        <svg class="w-12 h-12 text-yellow-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.5H7a1 1 0 100 2h4a1 1 0 001-1V7z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Approved</p>
                            <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo $status_counts['approved'] ?? 0; ?></p>
                        </div>
                        <svg class="w-12 h-12 text-blue-100" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                        </svg>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600 text-sm font-medium">Disbursed</p>
                            <p class="text-3xl font-bold text-green-600 mt-2"><?php echo $status_counts['disbursed'] ?? 0; ?></p>
                        </div>
                        <svg class="w-12 h-12 text-green-100" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Filters Section -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <h2 class="text-lg font-bold text-gray-800 mb-4">Filters</h2>
                <form method="GET" class="space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <!-- Search -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Search (MSISDN or ID)</label>
                            <input type="text" name="search" placeholder="Search by phone or ID..." value="<?php echo htmlspecialchars($search_query); ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>

                        <!-- Status Filter -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                            <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="">All Statuses</option>
                                <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="approved" <?php echo $status_filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                <option value="disbursed" <?php echo $status_filter === 'disbursed' ? 'selected' : ''; ?>>Disbursed</option>
                                <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>

                        <!-- Action Buttons -->
                        <div class="flex items-end gap-2">
                            <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg font-semibold transition">Apply Filters</button>
                            <a href="loan_requests.php" class="flex-1 bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg font-semibold transition text-center">Clear</a>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Loan Requests Table -->
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">MSISDN</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">ID Number</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Amount</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Status</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Date</th>
                                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($loan_requests as $request): ?>
                            <tr class="border-b border-gray-200 hover:bg-gray-50 transition">
                                <td class="px-6 py-3 text-sm font-mono text-gray-900"><?php echo htmlspecialchars($request['msisdn']); ?></td>
                                <td class="px-6 py-3 text-sm text-gray-700"><?php echo htmlspecialchars($request['id_number']); ?></td>
                                <td class="px-6 py-3 text-sm text-gray-700">
                                    <?php if ($request['loan_amount']): ?>
                                        KES <?php echo number_format($request['loan_amount'], 2); ?>
                                    <?php else: ?>
                                        <span class="text-gray-500">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-3 text-sm">
                                    <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo getStatusColor($request['status']); ?>">
                                        <?php echo ucfirst($request['status']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-3 text-sm text-gray-600">
                                    <?php echo date('M d, Y', strtotime($request['created_at'])); ?>
                                </td>
                                <td class="px-6 py-3 text-sm">
                                    <div class="flex gap-2">
                                        <button onclick="openStatusModal(<?php echo $request['id']; ?>, '<?php echo htmlspecialchars($request['msisdn']); ?>', '<?php echo $request['status']; ?>')" class="text-blue-600 hover:text-blue-800 font-semibold">Update</button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php if (empty($loan_requests)): ?>
                    <div class="text-center text-gray-500 py-12">
                        <svg class="w-12 h-12 mx-auto mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        <p class="text-lg">No loan requests found</p>
                        <p class="text-sm">Requests will appear here</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="mt-6 flex justify-between items-center">
                <div class="text-sm text-gray-600">
                    Showing <strong><?php echo (($page - 1) * $items_per_page) + 1; ?></strong> to <strong><?php echo min($page * $items_per_page, $total_count); ?></strong> of <strong><?php echo number_format($total_count); ?></strong> requests
                </div>
                <nav class="flex gap-2 flex-wrap">
                    <?php if ($page > 1): ?>
                    <a href="?page=1<?php echo $status_filter ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">First</a>
                    <a href="?page=<?php echo $page - 1; ?><?php echo $status_filter ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">Previous</a>
                    <?php endif; ?>

                    <?php
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $page + 2);
                    
                    if ($start_page > 1): ?>
                    <span class="px-3 py-2">...</span>
                    <?php endif; ?>

                    <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <?php if ($i === $page): ?>
                    <button class="px-3 py-2 bg-blue-600 text-white rounded-lg font-semibold"><?php echo $i; ?></button>
                    <?php else: ?>
                    <a href="?page=<?php echo $i; ?><?php echo $status_filter ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition"><?php echo $i; ?></a>
                    <?php endif; ?>
                    <?php endfor; ?>

                    <?php if ($end_page < $total_pages): ?>
                    <span class="px-3 py-2">...</span>
                    <?php endif; ?>

                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?><?php echo $status_filter ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">Next</a>
                    <a href="?page=<?php echo $total_pages; ?><?php echo $status_filter ? '&status=' . urlencode($status_filter) : ''; ?><?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>" class="px-3 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">Last</a>
                    <?php endif; ?>
                </nav>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Update Status Modal -->
    <div id="statusModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-lg w-full max-w-md">
            <div class="p-6 border-b border-gray-200">
                <h2 class="text-2xl font-bold text-gray-800">Update Request Status</h2>
                <p class="text-gray-600 text-sm mt-1">MSISDN: <span id="modalMsisdn"></span></p>
            </div>
            <form method="POST" class="p-6 space-y-4">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" name="request_id" id="requestId">
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Status</label>
                    <select name="new_status" id="statusSelect" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">Select Status</option>
                        <option value="pending">Pending</option>
                        <option value="approved">Approved</option>
                        <option value="disbursed">Disbursed</option>
                        <option value="rejected">Rejected</option>
                    </select>
                </div>

                <div class="flex gap-3 pt-4">
                    <button type="button" onclick="closeStatusModal()" class="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition font-semibold">Cancel</button>
                    <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-semibold">Update Status</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openStatusModal(requestId, msisdn, currentStatus) {
            document.getElementById('requestId').value = requestId;
            document.getElementById('modalMsisdn').textContent = msisdn;
            document.getElementById('statusSelect').value = currentStatus;
            document.getElementById('statusModal').classList.remove('hidden');
        }

        function closeStatusModal() {
            document.getElementById('statusModal').classList.add('hidden');
        }

        // Close modal on ESC key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeStatusModal();
            }
        });
    </script>
</body>
</html>
