<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';

session_start();
if (empty($_SESSION['authenticated'])) {
    header("Location: signin.php");
    exit();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/module_helpers.php';
require_once __DIR__ . '/includes/settings_helpers.php';

$context = payroll_org_context($conn);
settings_ensure_audit_tables($conn);
$employees = payroll_load_employees($conn);
$paidThroughAccounts = [
    'Undeposited Funds',
    'Petty Cash',
    'B2L Mobitech - Bank Account',
];
$employeeMap = [];
foreach ($employees as $employee) {
    $employeeMap[(int) $employee['id']] = payroll_employee_name($employee) . ' (' . payroll_employee_code($employee) . ')';
}

$flashMessage = $_SESSION['flash_ok'] ?? '';
$flashError = $_SESSION['flash_err'] ?? '';
unset($_SESSION['flash_ok'], $_SESSION['flash_err']);

$requiredTables = ['loan_types', 'employee_loans', 'loan_repayments'];
$missingTables = payroll_missing_tables($conn, $requiredTables);
$schemaReady = empty($missingTables);
if ($schemaReady) {
    settings_ensure_loan_approval_columns($conn);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$schemaReady) {
    payroll_redirect_with_flash('loans.php', 'Import database/workhub_modules.sql in phpMyAdmin before using Loans.', true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_loan_type'])) {
    $loanName = trim((string) ($_POST['loan_name'] ?? ''));
    $perquisiteRate = trim((string) ($_POST['perquisite_rate'] ?? '0'));
    $returnView = trim((string) ($_POST['return_view'] ?? 'list'));
    $manageRedirect = $returnView === 'new' ? 'loans.php?view=new&manage_loans=true&create=true' : 'loans.php?manage_loans=true';

    if ($loanName === '') {
        payroll_redirect_with_flash($manageRedirect, 'Loan type name is required.', true);
    }
    if (!is_numeric($perquisiteRate)) {
        payroll_redirect_with_flash($manageRedirect, 'Perquisite rate must be numeric.', true);
    }

    $stmt = $conn->prepare("INSERT INTO loan_types (org_id, loan_name, perquisite_rate, description) VALUES (?, ?, ?, '')");
    if (!$stmt) {
        payroll_redirect_with_flash($manageRedirect, 'Unable to prepare loan type save.', true);
    }

    $rate = (float) $perquisiteRate;
    $stmt->bind_param('ssd', $context['org_id'], $loanName, $rate);
    if (!$stmt->execute()) {
        $message = 'Unable to save loan type. ' . $stmt->error;
        $stmt->close();
        payroll_redirect_with_flash($manageRedirect, $message, true);
    }
    $newLoanTypeId = (int) $stmt->insert_id;
    $stmt->close();

    if ($returnView === 'new' && $newLoanTypeId > 0) {
        payroll_redirect_with_flash('loans.php?view=new&loan_type_id=' . $newLoanTypeId, 'Loan type created successfully.');
    }

    payroll_redirect_with_flash('loans.php?manage_loans=true', 'Loan type created successfully.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_loan_approval'])) {
    $loanId = (int) ($_POST['loan_id'] ?? 0);
    $approvalStatus = trim((string) ($_POST['approval_status'] ?? 'pending'));
    $approvalNotes = trim((string) ($_POST['approval_notes'] ?? ''));
    $validApprovalStatuses = ['pending', 'approved', 'rejected'];
    if ($loanId <= 0 || !in_array($approvalStatus, $validApprovalStatuses, true)) {
        payroll_redirect_with_flash('loans.php', 'Invalid loan approval request.', true);
    }

    $oldLoan = null;
    $oldStmt = $conn->prepare("SELECT * FROM employee_loans WHERE id = ? AND org_id = ? LIMIT 1");
    if ($oldStmt) {
        $oldStmt->bind_param('is', $loanId, $context['org_id']);
        $oldStmt->execute();
        $oldResult = $oldStmt->get_result();
        $oldLoan = $oldResult ? $oldResult->fetch_assoc() : null;
        $oldStmt->close();
    }
    if (!$oldLoan) {
        payroll_redirect_with_flash('loans.php', 'Loan not found for this organization.', true);
    }

    $approvedBy = (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system');
    $approvedAt = in_array($approvalStatus, ['approved', 'rejected'], true) ? date('Y-m-d H:i:s') : null;
    $stmt = $conn->prepare(
        "UPDATE employee_loans
         SET approval_status = ?, approved_by = ?, approved_at = ?, approval_notes = ?
         WHERE id = ? AND org_id = ?"
    );
    if (!$stmt) {
        payroll_redirect_with_flash('loans.php', 'Unable to prepare loan approval update.', true);
    }
    $stmt->bind_param('ssssis', $approvalStatus, $approvedBy, $approvedAt, $approvalNotes, $loanId, $context['org_id']);
    if (!$stmt->execute()) {
        $message = 'Unable to update loan approval. ' . $stmt->error;
        $stmt->close();
        payroll_redirect_with_flash('loans.php', $message, true);
    }
    $stmt->close();

    $newLoan = null;
    $newStmt = $conn->prepare("SELECT * FROM employee_loans WHERE id = ? AND org_id = ? LIMIT 1");
    if ($newStmt) {
        $newStmt->bind_param('is', $loanId, $context['org_id']);
        $newStmt->execute();
        $newResult = $newStmt->get_result();
        $newLoan = $newResult ? $newResult->fetch_assoc() : null;
        $newStmt->close();
    }

    settings_log_loan_history(
        $conn,
        $context['org_id'],
        $loanId,
        isset($oldLoan['employee_id']) ? (int) $oldLoan['employee_id'] : null,
        'approval_updated',
        $approvedBy,
        $oldLoan,
        $newLoan
    );
    $requestStmt = $conn->prepare(
        "UPDATE approval_requests
         SET approval_status = ?, approved_by = ?, approval_notes = ?
         WHERE org_id = ? AND module_name = 'loan' AND reference_type = 'employee_loan' AND reference_id = ?"
    );
    if ($requestStmt) {
        $requestStmt->bind_param('ssssi', $approvalStatus, $approvedBy, $approvalNotes, $context['org_id'], $loanId);
        $requestStmt->execute();
        $requestStmt->close();
    }

    payroll_redirect_with_flash('loans.php', 'Loan approval updated successfully.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_loan'])) {
    $employeeId = (int) ($_POST['employee_id'] ?? 0);
    $loanTypeId = (int) ($_POST['loan_type_id'] ?? 0);
    $loanAmount = (float) ($_POST['loan_amount'] ?? 0);
    $disbursementDate = trim((string) ($_POST['disbursement_date'] ?? ''));
    $paidThroughAccount = trim((string) ($_POST['paid_through_account'] ?? ''));
    $referenceNumber = trim((string) ($_POST['reference_number'] ?? ''));
    $reason = trim((string) ($_POST['reason'] ?? ''));
    $totalInstallments = (int) ($_POST['total_installments'] ?? 1);
    $repaymentStartMonth = trim((string) ($_POST['repayment_start_month'] ?? ''));
    $installmentAmountInput = trim((string) ($_POST['installment_amount'] ?? ''));
    $status = trim((string) ($_POST['status'] ?? 'open'));
    $exemptPerquisite = isset($_POST['exempt_perquisite']) ? 1 : 0;

    if ($employeeId <= 0 || $loanTypeId <= 0) {
        payroll_redirect_with_flash('loans.php?view=new', 'Select employee and loan type.', true);
    }
    if ($loanAmount <= 0) {
        payroll_redirect_with_flash('loans.php?view=new', 'Enter a valid loan amount.', true);
    }
    if ($disbursementDate === '' || $paidThroughAccount === '' || $reason === '') {
        payroll_redirect_with_flash('loans.php?view=new', 'Disbursement date, paid through account, and reason are required.', true);
    }

    $totalInstallments = max(1, $totalInstallments);
    $installmentAmount = $installmentAmountInput !== '' && is_numeric($installmentAmountInput)
        ? (float) $installmentAmountInput
        : round($loanAmount / $totalInstallments, 2);

    $stmt = $conn->prepare("INSERT INTO employee_loans
        (org_id, employee_id, loan_type_id, loan_amount, disbursement_date, paid_through_account, reference_number, reason, exempt_perquisite, installment_amount, total_installments, repayment_start_month, status, approval_status, outstanding_amount)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)");
    if (!$stmt) {
        payroll_redirect_with_flash('loans.php?view=new', 'Unable to prepare loan save.', true);
    }

    $outstandingAmount = $loanAmount;
    $repaymentMonthSql = $repaymentStartMonth !== '' ? ($repaymentStartMonth . '-01') : null;
    $stmt->bind_param(
        'siidssssidissd',
        $context['org_id'],
        $employeeId,
        $loanTypeId,
        $loanAmount,
        $disbursementDate,
        $paidThroughAccount,
        $referenceNumber,
        $reason,
        $exemptPerquisite,
        $installmentAmount,
        $totalInstallments,
        $repaymentMonthSql,
        $status,
        $outstandingAmount
    );

    if (!$stmt->execute()) {
        $message = 'Unable to save loan. ' . $stmt->error;
        $stmt->close();
        payroll_redirect_with_flash('loans.php?view=new', $message, true);
    }

    $loanId = (int) $stmt->insert_id;
    $stmt->close();

    if ($repaymentMonthSql && $loanId > 0) {
        $repaymentStmt = $conn->prepare("INSERT INTO loan_repayments (loan_id, employee_id, repayment_month, repayment_type, installment_amount, principal_amount, remarks)
                                         VALUES (?, ?, ?, 'Loan Repayment Method', ?, ?, ?)");
        if ($repaymentStmt) {
            $currentMonth = DateTime::createFromFormat('Y-m-d', $repaymentMonthSql) ?: new DateTime($repaymentMonthSql);
            for ($i = 0; $i < $totalInstallments; $i++) {
                $repaymentMonth = $currentMonth->format('Y-m-01');
                $principalAmount = $installmentAmount;
                $remarks = 'Auto schedule';
                $repaymentStmt->bind_param('iisdds', $loanId, $employeeId, $repaymentMonth, $installmentAmount, $principalAmount, $remarks);
                $repaymentStmt->execute();
                $currentMonth->modify('+1 month');
            }
            $repaymentStmt->close();
        }
    }

    $loanSnapshot = null;
    $snapshotStmt = $conn->prepare("SELECT * FROM employee_loans WHERE id = ? AND org_id = ? LIMIT 1");
    if ($snapshotStmt) {
        $snapshotStmt->bind_param('is', $loanId, $context['org_id']);
        $snapshotStmt->execute();
        $snapshotResult = $snapshotStmt->get_result();
        $loanSnapshot = $snapshotResult ? $snapshotResult->fetch_assoc() : null;
        $snapshotStmt->close();
    }

    settings_log_loan_history(
        $conn,
        $context['org_id'],
        $loanId,
        $employeeId,
        'created',
        (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system'),
        null,
        $loanSnapshot
    );
    settings_create_approval_request(
        $conn,
        $context['org_id'],
        'loan',
        'employee_loan',
        $loanId,
        $employeeId,
        (string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system'),
        'pending',
        'Loan created and waiting for organization approval.'
    );

    payroll_redirect_with_flash('loans.php', 'Loan created successfully.');
}

$loanTypes = [];
if ($schemaReady) {
    $typeStmt = $conn->prepare("SELECT * FROM loan_types WHERE org_id = ? AND COALESCE(is_active, 1) = 1 ORDER BY loan_name ASC");
    if ($typeStmt) {
        $typeStmt->bind_param('s', $context['org_id']);
        $typeStmt->execute();
        $typeResult = $typeStmt->get_result();
        while ($typeResult && ($row = $typeResult->fetch_assoc())) {
            $loanTypes[] = $row;
        }
        $typeStmt->close();
    }
}

$view = trim((string) ($_GET['view'] ?? 'list'));
$validViews = ['list', 'new', 'repayments'];
if (!in_array($view, $validViews, true)) {
    $view = 'list';
}

$statusFilter = trim((string) ($_GET['status'] ?? 'all'));
$validStatuses = ['all', 'open', 'paused', 'closed'];
if (!in_array($statusFilter, $validStatuses, true)) {
    $statusFilter = 'all';
}

$filterEmployeeId = (int) ($_GET['employee_id'] ?? 0);
$filterLoanTypeId = (int) ($_GET['loan_type_id'] ?? 0);
$filterRepaymentMonth = trim((string) ($_GET['month'] ?? ''));
$filterRepaymentType = trim((string) ($_GET['repayment_type'] ?? ''));
$showManageLoans = isset($_GET['manage_loans']) && $_GET['manage_loans'] === 'true';
$showFilters = isset($_GET['show_filter']) && $_GET['show_filter'] === 'true';

$loans = [];
$repayments = [];
if ($schemaReady) {
    $loanSql = "SELECT l.*, t.loan_name, t.perquisite_rate
                FROM employee_loans l
                LEFT JOIN loan_types t ON t.id = l.loan_type_id
                WHERE l.org_id = ?";
    $loanTypesBind = 's';
    $loanParams = [$context['org_id']];

    if ($statusFilter !== 'all') {
        $loanSql .= " AND l.status = ?";
        $loanTypesBind .= 's';
        $loanParams[] = $statusFilter;
    }
    if ($filterEmployeeId > 0) {
        $loanSql .= " AND l.employee_id = ?";
        $loanTypesBind .= 'i';
        $loanParams[] = $filterEmployeeId;
    }
    if ($filterLoanTypeId > 0) {
        $loanSql .= " AND l.loan_type_id = ?";
        $loanTypesBind .= 'i';
        $loanParams[] = $filterLoanTypeId;
    }
    $loanSql .= " ORDER BY l.id DESC";

    $stmt = $conn->prepare($loanSql);
    if ($stmt) {
        if ($loanParams) {
            $bind = [$loanTypesBind];
            foreach ($loanParams as $index => $value) {
                $loanParams[$index] = $value;
                $bind[] = &$loanParams[$index];
            }
            call_user_func_array([$stmt, 'bind_param'], $bind);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $loans[] = $row;
        }
        $stmt->close();
    }

    $repaymentSql = "SELECT lr.*, el.reference_number, el.loan_type_id, lt.loan_name
                     FROM loan_repayments lr
                     LEFT JOIN employee_loans el ON el.id = lr.loan_id
                     LEFT JOIN loan_types lt ON lt.id = el.loan_type_id
                     WHERE el.org_id = ?";
    $repaymentTypesBind = 's';
    $repaymentParams = [$context['org_id']];

    if ($filterEmployeeId > 0) {
        $repaymentSql .= " AND lr.employee_id = ?";
        $repaymentTypesBind .= 'i';
        $repaymentParams[] = $filterEmployeeId;
    }
    if ($filterLoanTypeId > 0) {
        $repaymentSql .= " AND el.loan_type_id = ?";
        $repaymentTypesBind .= 'i';
        $repaymentParams[] = $filterLoanTypeId;
    }
    if ($filterRepaymentMonth !== '') {
        $repaymentSql .= " AND DATE_FORMAT(lr.repayment_month, '%Y-%m') = ?";
        $repaymentTypesBind .= 's';
        $repaymentParams[] = $filterRepaymentMonth;
    }
    if ($filterRepaymentType !== '') {
        $repaymentSql .= " AND lr.repayment_type = ?";
        $repaymentTypesBind .= 's';
        $repaymentParams[] = $filterRepaymentType;
    }
    $repaymentSql .= " ORDER BY lr.repayment_month DESC, lr.id DESC";

    $stmt = $conn->prepare($repaymentSql);
    if ($stmt) {
        if ($repaymentParams) {
            $bind = [$repaymentTypesBind];
            foreach ($repaymentParams as $index => $value) {
                $repaymentParams[$index] = $value;
                $bind[] = &$repaymentParams[$index];
            }
            call_user_func_array([$stmt, 'bind_param'], $bind);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $repayments[] = $row;
        }
        $stmt->close();
    }
}

$openCount = 0;
$totalOutstanding = 0.0;
foreach ($loans as $loan) {
    if (($loan['status'] ?? '') === 'open') {
        $openCount++;
    }
    $totalOutstanding += (float) ($loan['outstanding_amount'] ?? 0);
}

$emptyLoanMessage = "You haven't provided any loans to your employees. You can provide loans to your employees and deduct the instalment amount from their salary every month.";
$selectedStatusLabel = [
    'all' => 'All Loans',
    'open' => 'Open Loans',
    'paused' => 'Paused Loans',
    'closed' => 'Closed Loans',
][$statusFilter];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loans | Payroll</title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="modules.css">
    <style>
        .search-select{position:relative;}
        .search-select__trigger{width:100%;height:48px;border:1px solid #d7deea;border-radius:8px;background:#fff;display:flex;align-items:center;justify-content:space-between;padding:0 14px;font:inherit;color:#1f2937;cursor:pointer;}
        .search-select__trigger.is-empty{color:#94a3b8;}
        .search-select__menu{position:absolute;top:calc(100% + 8px);left:0;right:0;background:#fff;border:1px solid #d7deea;border-radius:12px;box-shadow:0 20px 42px rgba(15,23,42,.14);z-index:30;overflow:hidden;}
        .search-select__search{display:flex;align-items:center;gap:10px;padding:10px 12px;border-bottom:1px solid #eef2f7;}
        .search-select__search input{border:none;outline:none;width:100%;font:inherit;}
        .search-select__list{max-height:220px;overflow:auto;padding:8px 0;}
        .search-select__option,.search-select__link{display:flex;align-items:center;width:100%;padding:10px 14px;border:none;background:#fff;text-align:left;font:inherit;color:#334155;cursor:pointer;text-decoration:none;}
        .search-select__option:hover,.search-select__link:hover,.search-select__option.is-active{background:#3b82f6;color:#fff;}
        .search-select__empty{padding:14px;color:#94a3b8;font-size:13px;}
        .loan-helper-line{margin-top:10px;font-size:13px;color:#5f6b7a;}
        .loan-helper-line strong{color:#111827;}
        .loan-inline-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px 28px;}
        .loan-inline-grid .field-group.full-span{grid-column:1 / -1;}
        .currency-field span{min-width:30px;display:flex;align-items:center;justify-content:center;}
        .loan-type-inline-form{display:grid;grid-template-columns:minmax(0,1fr) 140px auto auto;gap:14px;align-items:center;}
        @media (max-width: 860px){
            .loan-inline-grid,.loan-type-inline-form{grid-template-columns:1fr;}
        }
    </style>
</head>
<body class="module-page">
<div class="module-shell loans-shell">
    <aside class="module-sidebar">
        <div class="module-brand">
            <img src="images/b2l_mobitech_pvt_ltd_logo.jpg" alt="B2L Mobitech Pvt Ltd">
            <span>Payroll</span>
        </div>
        <div class="module-sidebar-scroll">
            <div class="module-sidebar-section">
                <div class="module-getting-started">
                    <div class="module-gs-top">
                        <i class="fa-solid fa-wand-magic-sparkles"></i>
                        <span>Getting Started</span>
                    </div>
                    <div class="module-progress-bar">
                        <div class="module-progress-fill"></div>
                    </div>
                </div>
            </div>
            <nav class="module-nav">
                <a href="dashboard.php"><i class="fa-regular fa-circle-dot"></i><span>Dashboard</span></a>
                <a href="employees.php"><i class="fa-regular fa-user"></i><span>Employees</span></a>
                <a href="payruns.php"><i class="fa-regular fa-calendar-check"></i><span>Pay Runs</span></a>
                <a href="#"><i class="fa-regular fa-square-check"></i><span>Approvals</span></a>
                <a href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
                <a class="active" href="loans.php"><i class="fa-solid fa-indian-rupee-sign"></i><span>Loans</span></a>
                <a href="giving.php"><i class="fa-regular fa-heart"></i><span>Giving</span></a>
                <a href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
                <a href="reports.php"><i class="fa-regular fa-chart-bar"></i><span>Reports</span></a>
                <a href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a>
            </nav>
        </div>
        <div class="module-sidebar-footer">
            <a class="module-support-link" href="#">Contact Support <i class="fa-solid fa-angle-right"></i></a>
        </div>
        <div class="module-support-tile">
            <div class="module-support-title">Track TDS Liabilities and Generate Form 24Q</div>
            <a class="module-support-action" href="#">View Details</a>
        </div>
        <div class="module-support-tile alt">
            <div class="module-support-title">Access My Portal</div>
        </div>
    </aside>

    <main class="module-main loans-main">
        <div class="module-topbar loans-topbar">
            <div class="module-search">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" placeholder="Search in Employee">
            </div>
            <div class="module-user">
                <span><?php echo htmlspecialchars($context['display_name']); ?></span>
                <span class="module-avatar"><?php echo htmlspecialchars(strtoupper(substr($context['display_name'], 0, 1))); ?></span>
            </div>
        </div>

        <?php if ($flashMessage): ?>
            <div class="alert ok"><?php echo htmlspecialchars($flashMessage); ?></div>
        <?php endif; ?>
        <?php if ($flashError): ?>
            <div class="alert err"><?php echo htmlspecialchars($flashError); ?></div>
        <?php endif; ?>
        <?php if (!$schemaReady): ?>
            <div class="alert err">Missing tables: <?php echo htmlspecialchars(implode(', ', $missingTables)); ?>. Import <strong>database/workhub_modules.sql</strong> in phpMyAdmin first.</div>
        <?php endif; ?>

        <?php if ($view === 'new'): ?>
            <section class="loan-page loan-form-page">
                <?php
                    $selectedLoanTypeId = (int) ($_GET['loan_type_id'] ?? 0);
                    $selectedLoanTypeLabel = 'Select Loan';
                    $selectedLoanRate = '0.00';
                    foreach ($loanTypes as $type) {
                        if ((int) $type['id'] === $selectedLoanTypeId) {
                            $selectedLoanTypeLabel = (string) $type['loan_name'];
                            $selectedLoanRate = number_format((float) $type['perquisite_rate'], 2);
                            break;
                        }
                    }
                ?>
                <div class="loan-page-head">
                    <h1>Create Loan</h1>
                    <a class="icon-btn ghost" href="loans.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                </div>

                <form method="post" class="loan-create-form">
                    <input type="hidden" name="create_loan" value="1">

                    <div class="field-group full">
                        <label for="loan_type_id">Loan Name <span class="req">*</span></label>
                        <div class="search-select" data-search-select>
                            <input id="loan_type_id" type="hidden" name="loan_type_id" value="<?php echo $selectedLoanTypeId > 0 ? $selectedLoanTypeId : ''; ?>">
                            <button class="search-select__trigger <?php echo $selectedLoanTypeId > 0 ? '' : 'is-empty'; ?>" type="button" data-search-trigger>
                                <span data-search-label><?php echo htmlspecialchars($selectedLoanTypeLabel); ?></span>
                                <i class="fa-solid fa-angle-down"></i>
                            </button>
                            <div class="search-select__menu" data-search-menu hidden>
                                <div class="search-select__search">
                                    <i class="fa-solid fa-magnifying-glass"></i>
                                    <input type="text" placeholder="" data-search-input>
                                </div>
                                <div class="search-select__list">
                                    <?php if ($loanTypes): ?>
                                        <?php foreach ($loanTypes as $type): ?>
                                            <button
                                                class="search-select__option <?php echo (int) $type['id'] === $selectedLoanTypeId ? 'is-active' : ''; ?>"
                                                type="button"
                                                data-search-option
                                                data-value="<?php echo (int) $type['id']; ?>"
                                                data-label="<?php echo htmlspecialchars((string) $type['loan_name']); ?>"
                                                data-rate="<?php echo htmlspecialchars(number_format((float) $type['perquisite_rate'], 2)); ?>"
                                            ><?php echo htmlspecialchars((string) $type['loan_name']); ?></button>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="search-select__empty">SORRY! NO RESULTS FOUND</div>
                                    <?php endif; ?>
                                </div>
                                <a class="search-select__link" href="loans.php?view=new&manage_loans=true">Manage Loans</a>
                            </div>
                        </div>
                        <div class="loan-helper-line">Perquisite Rate: <strong><span data-loan-rate><?php echo htmlspecialchars($selectedLoanRate); ?></span>%</strong></div>
                    </div>

                    <div class="loan-inline-grid">
                        <div class="field-group">
                            <label for="employee_id">Employee Name <span class="req">*</span></label>
                            <div class="search-select" data-search-select>
                                <input id="employee_id" type="hidden" name="employee_id" value="">
                                <button class="search-select__trigger is-empty" type="button" data-search-trigger>
                                    <span data-search-label>Search Employee</span>
                                    <i class="fa-solid fa-angle-down"></i>
                                </button>
                                <div class="search-select__menu" data-search-menu hidden>
                                    <div class="search-select__search">
                                        <i class="fa-solid fa-magnifying-glass"></i>
                                        <input type="text" placeholder="" data-search-input>
                                    </div>
                                    <div class="search-select__list">
                                        <?php foreach ($employeeMap as $employeeId => $label): ?>
                                            <button class="search-select__option" type="button" data-search-option data-value="<?php echo $employeeId; ?>" data-label="<?php echo htmlspecialchars($label); ?>"><?php echo htmlspecialchars($label); ?></button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="field-group">
                            <label for="loan_amount">Loan Amount <span class="req">*</span></label>
                            <div class="currency-field">
                                <span>₹</span>
                                <input id="loan_amount" type="number" step="0.01" name="loan_amount" placeholder="0" required>
                            </div>
                        </div>
                        <div class="field-group">
                            <label for="disbursement_date">Disbursement Date <span class="req">*</span></label>
                            <input id="disbursement_date" type="date" name="disbursement_date" required>
                        </div>
                        <div class="field-group">
                            <label for="paid_through_account">Paid Through Account <span class="req">*</span></label>
                            <div class="search-select" data-search-select>
                                <input id="paid_through_account" type="hidden" name="paid_through_account" value="">
                                <button class="search-select__trigger is-empty" type="button" data-search-trigger>
                                    <span data-search-label>Select</span>
                                    <i class="fa-solid fa-angle-down"></i>
                                </button>
                                <div class="search-select__menu" data-search-menu hidden>
                                    <div class="search-select__search">
                                        <i class="fa-solid fa-magnifying-glass"></i>
                                        <input type="text" placeholder="" data-search-input>
                                    </div>
                                    <div class="search-select__list">
                                        <?php foreach ($paidThroughAccounts as $accountLabel): ?>
                                            <button class="search-select__option" type="button" data-search-option data-value="<?php echo htmlspecialchars($accountLabel); ?>" data-label="<?php echo htmlspecialchars($accountLabel); ?>"><?php echo htmlspecialchars($accountLabel); ?></button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="field-group">
                            <label for="reference_number">Reference Number</label>
                            <input id="reference_number" type="text" name="reference_number">
                        </div>
                        <div class="field-group full-span">
                            <label for="repayment_start_month">Repayment Start Month</label>
                            <input id="repayment_start_month" type="month" name="repayment_start_month">
                        </div>
                    </div>

                    <div class="field-group full">
                        <label for="reason">Reason <span class="req">*</span></label>
                        <textarea id="reason" name="reason" required></textarea>
                    </div>

                    <div class="field-group full">
                        <label class="field-inline note-checkbox">
                            <input type="checkbox" name="exempt_perquisite" value="1">
                            <span>Exempt this loan from perquisite calculation</span>
                        </label>
                        <div class="helper-copy">According to Rule 3(A), employees availing medical loan or any loan below Rs 20,000 can be exempted from perquisite calculation.</div>
                    </div>

                    <div class="field-group full loan-inline-hidden">
                        <label for="loan_status">Status</label>
                        <select id="loan_status" name="status">
                            <option value="open">Open Loans</option>
                            <option value="paused">Paused Loans</option>
                            <option value="closed">Closed Loans</option>
                        </select>
                    </div>

                    <div class="form-actions footer-actions">
                        <button class="btn-primary" type="submit">Save</button>
                        <a class="btn-secondary" href="loans.php">Cancel</a>
                        <div class="mand-note"><span>*</span> indicates mandatory fields</div>
                    </div>
                </form>
            </section>
        <?php elseif ($view === 'repayments'): ?>
            <section class="loan-page">
                <div class="loan-page-head">
                    <div class="loan-back-title">
                        <a class="icon-btn subtle" href="loans.php" aria-label="Back"><i class="fa-solid fa-angle-left"></i></a>
                        <h1>Loan Repayments</h1>
                    </div>
                    <div class="loan-head-tools">
                        <a class="icon-btn" href="loans.php?view=repayments&show_filter=true" aria-label="Filter"><i class="fa-solid fa-filter"></i></a>
                    </div>
                </div>

                <div class="repayment-filter-pills">
                    <div class="filter-pill">Month: <?php echo htmlspecialchars($filterRepaymentMonth !== '' ? date('M Y', strtotime($filterRepaymentMonth . '-01')) : date('M Y')); ?></div>
                    <div class="filter-pill">Repayment Method: <?php echo htmlspecialchars($filterRepaymentType !== '' ? $filterRepaymentType : 'Loan Repayment Method'); ?></div>
                    <div class="filter-pill">Employees: <?php echo htmlspecialchars($filterEmployeeId > 0 && isset($employeeMap[$filterEmployeeId]) ? $employeeMap[$filterEmployeeId] : 'Select an Employee'); ?></div>
                </div>

                <?php if (!$repayments): ?>
                    <div class="empty-state repayments-empty">
                        <div class="empty-illustration loans-ghost"></div>
                        <p>No loan repayments match the selected filter.</p>
                    </div>
                <?php else: ?>
                    <div class="table-wrap loan-table-wrap">
                        <table class="module-table">
                            <thead>
                            <tr>
                                <th>Employee</th>
                                <th>Repayment Month</th>
                                <th>Repayment Type</th>
                                <th>Installment Amount</th>
                                <th>Reference</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($repayments as $repayment): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($employeeMap[(int) $repayment['employee_id']] ?? ('Employee #' . (int) $repayment['employee_id'])); ?></td>
                                    <td><?php echo htmlspecialchars(payroll_month_label($repayment['repayment_month'] ?? null)); ?></td>
                                    <td><?php echo htmlspecialchars((string) ($repayment['repayment_type'] ?? 'Loan Repayment Method')); ?></td>
                                    <td><?php echo htmlspecialchars(payroll_format_currency($repayment['installment_amount'] ?? 0)); ?></td>
                                    <td><?php echo htmlspecialchars((string) ($repayment['reference_number'] ?? '-')); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>
        <?php else: ?>
            <section class="loan-page">
                <div class="loan-toolbar">
                    <div class="loan-status-dropdown">
                        <button class="status-chip" type="button" data-status-toggle>
                            <span><?php echo htmlspecialchars($selectedStatusLabel); ?></span>
                            <i class="fa-solid fa-angle-down"></i>
                        </button>
                        <div class="status-menu" data-status-menu>
                            <a class="<?php echo $statusFilter === 'all' ? 'active' : ''; ?>" href="loans.php?status=all">All Loans</a>
                            <a class="<?php echo $statusFilter === 'open' ? 'active' : ''; ?>" href="loans.php?status=open">Open Loans</a>
                            <a class="<?php echo $statusFilter === 'paused' ? 'active' : ''; ?>" href="loans.php?status=paused">Paused Loans</a>
                            <a class="<?php echo $statusFilter === 'closed' ? 'active' : ''; ?>" href="loans.php?status=closed">Closed Loans</a>
                        </div>
                    </div>

                    <div class="loan-actions">
                        <a class="btn-link-primary" href="loans.php?view=repayments">
                            <i class="fa-regular fa-calendar"></i>
                            <span>View Loan Repayments</span>
                        </a>
                        <a class="btn-primary compact" href="loans.php?view=new"><i class="fa-solid fa-plus"></i> Add</a>
                        <div class="toolbar-menu-wrap">
                            <button class="icon-btn" type="button" data-more-toggle><i class="fa-solid fa-ellipsis"></i></button>
                            <div class="toolbar-pop" data-more-menu>
                                <a href="loans.php?manage_loans=true"><i class="fa-solid fa-gear"></i> Manage Loans</a>
                            </div>
                        </div>
                        <a class="icon-btn" href="loans.php?show_filter=true" aria-label="Filter"><i class="fa-solid fa-filter"></i></a>
                    </div>
                </div>

                <?php if (!$loans): ?>
                    <div class="empty-state loans-empty">
                        <div class="empty-illustration loans-box"></div>
                        <p><?php echo htmlspecialchars($emptyLoanMessage); ?></p>
                    </div>
                <?php else: ?>
                    <div class="loan-summary-row">
                        <div class="summary-card">
                            <span>Loan Types</span>
                            <strong><?php echo count($loanTypes); ?></strong>
                        </div>
                        <div class="summary-card">
                            <span>Open Loans</span>
                            <strong><?php echo $openCount; ?></strong>
                        </div>
                        <div class="summary-card">
                            <span>Outstanding</span>
                            <strong><?php echo htmlspecialchars(payroll_format_currency($totalOutstanding)); ?></strong>
                        </div>
                    </div>

                    <div class="table-wrap loan-table-wrap">
                        <table class="module-table">
                            <thead>
                            <tr>
                                <th>Employee</th>
                                <th>Loan Type</th>
                                <th>Loan Amount</th>
                                <th>Outstanding Amount</th>
                                <th>Disbursement Date</th>
                                <th>Repayment Date</th>
                                <th>Status</th>
                                <th>Approval</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($loans as $loan): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($employeeMap[(int) $loan['employee_id']] ?? ('Employee #' . (int) $loan['employee_id'])); ?></td>
                                    <td><?php echo htmlspecialchars((string) ($loan['loan_name'] ?? 'Loan')); ?></td>
                                    <td><?php echo htmlspecialchars(payroll_format_currency($loan['loan_amount'] ?? 0)); ?></td>
                                    <td><?php echo htmlspecialchars(payroll_format_currency($loan['outstanding_amount'] ?? 0)); ?></td>
                                    <td><?php echo htmlspecialchars(payroll_date_label($loan['disbursement_date'] ?? null)); ?></td>
                                    <td><?php echo htmlspecialchars(payroll_month_label($loan['repayment_start_month'] ?? null)); ?></td>
                                    <td><span class="badge <?php echo htmlspecialchars((string) ($loan['status'] ?? 'open')); ?>"><?php echo htmlspecialchars(ucfirst((string) ($loan['status'] ?? 'open'))); ?></span></td>
                                    <td>
                                        <form method="post" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                                            <input type="hidden" name="update_loan_approval" value="1">
                                            <input type="hidden" name="loan_id" value="<?php echo (int) $loan['id']; ?>">
                                            <select name="approval_status">
                                                <?php $currentApproval = (string) ($loan['approval_status'] ?? 'pending'); ?>
                                                <option value="pending" <?php echo $currentApproval === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="approved" <?php echo $currentApproval === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                                <option value="rejected" <?php echo $currentApproval === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                            </select>
                                            <input type="text" name="approval_notes" value="<?php echo htmlspecialchars((string) ($loan['approval_notes'] ?? '')); ?>" placeholder="Approval notes">
                                            <button class="btn-secondary" type="submit">Save</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>
        <?php endif; ?>
    </main>
</div>
<?php if ($showManageLoans): ?>
    <div class="sheet-backdrop">
        <div class="sheet-dialog manage-dialog">
            <div class="sheet-head">
                <h2>Manage Loans</h2>
                <a class="icon-btn ghost" href="loans.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
            </div>
            <div class="loan-type-table-head">
                <span>LOAN NAME</span>
                <span>PERQUISITE RATE</span>
            </div>

            <?php if (!$loanTypes): ?>
                <div class="manage-empty">
                    <a class="create-loan-type-link" href="loans.php?<?php echo $view === 'new' ? 'view=new&' : ''; ?>manage_loans=true&create=true">+ Create New Loan Type</a>
                </div>
            <?php else: ?>
                <div class="loan-type-list">
                    <?php foreach ($loanTypes as $type): ?>
                        <div class="loan-type-row">
                            <span><?php echo htmlspecialchars((string) $type['loan_name']); ?></span>
                            <span><?php echo htmlspecialchars(number_format((float) $type['perquisite_rate'], 2)); ?></span>
                        </div>
                    <?php endforeach; ?>
                    <a class="create-loan-type-link inline" href="loans.php?<?php echo $view === 'new' ? 'view=new&' : ''; ?>manage_loans=true&create=true">+ Create New Loan Type</a>
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['create']) && $_GET['create'] === 'true'): ?>
                <form method="post" class="loan-type-inline-form">
                    <input type="hidden" name="create_loan_type" value="1">
                    <input type="hidden" name="return_view" value="<?php echo htmlspecialchars($view); ?>">
                    <input type="text" name="loan_name" placeholder="">
                    <input type="number" step="0.01" name="perquisite_rate" value="0.00">
                    <button class="btn-primary" type="submit">Save and Select</button>
                    <a class="btn-secondary" href="loans.php?<?php echo $view === 'new' ? 'view=new&' : ''; ?>manage_loans=true">Cancel</a>
                </form>
            <?php endif; ?>

            <div class="manage-note">
                <i class="fa-regular fa-circle-info"></i>
                <span>Perquisite Rate is required for all type of loans with loan amount greater than Rs 20,000 except Medical Loan. Any change in Perquisite Rate, will be applied to all the employees who has availed that Loan.</span>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php if ($showFilters): ?>
    <div class="filter-drawer open" aria-hidden="false">
        <div class="filter-panel">
            <div class="filter-head">
                <h3>Filter By</h3>
                <a class="icon-btn ghost" href="<?php echo $view === 'repayments' ? 'loans.php?view=repayments' : 'loans.php'; ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
            </div>
            <form method="get" class="filter-body">
                <?php if ($view === 'repayments'): ?>
                    <input type="hidden" name="view" value="repayments">
                <?php endif; ?>
                <div class="filter-search">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <input type="text" placeholder="Search">
                </div>
                <div class="loan-filter-grid">
                    <div class="field-group">
                        <label for="drawer_employee">Employee</label>
                        <select id="drawer_employee" name="employee_id">
                            <option value="0">Select an Employee</option>
                            <?php foreach ($employeeMap as $employeeId => $label): ?>
                                <option value="<?php echo $employeeId; ?>" <?php echo $filterEmployeeId === $employeeId ? 'selected' : ''; ?>><?php echo htmlspecialchars($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="field-group">
                        <label for="drawer_loan_type">Loan Type</label>
                        <select id="drawer_loan_type" name="loan_type_id">
                            <option value="0">Select Loan Type</option>
                            <?php foreach ($loanTypes as $type): ?>
                                <option value="<?php echo (int) $type['id']; ?>" <?php echo $filterLoanTypeId === (int) $type['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars((string) $type['loan_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php if ($view === 'repayments'): ?>
                        <div class="field-group">
                            <label for="drawer_month">Repayment Date</label>
                            <input id="drawer_month" type="month" name="month" value="<?php echo htmlspecialchars($filterRepaymentMonth); ?>">
                        </div>
                        <div class="field-group">
                            <label for="drawer_method">Repayment Method</label>
                            <select id="drawer_method" name="repayment_type">
                                <option value="">Loan Repayment Method</option>
                                <option value="Loan Repayment Method" <?php echo $filterRepaymentType === 'Loan Repayment Method' ? 'selected' : ''; ?>>Loan Repayment Method</option>
                            </select>
                        </div>
                    <?php else: ?>
                        <div class="field-group">
                            <label for="drawer_status">Loan Status</label>
                            <select id="drawer_status" name="status">
                                <option value="all">All Loans</option>
                                <option value="open" <?php echo $statusFilter === 'open' ? 'selected' : ''; ?>>Open Loans</option>
                                <option value="paused" <?php echo $statusFilter === 'paused' ? 'selected' : ''; ?>>Paused Loans</option>
                                <option value="closed" <?php echo $statusFilter === 'closed' ? 'selected' : ''; ?>>Closed Loans</option>
                            </select>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="filter-foot">
                    <button class="btn-primary" type="submit">Apply</button>
                    <a class="btn-link danger-link" href="<?php echo $view === 'repayments' ? 'loans.php?view=repayments' : 'loans.php'; ?>">Clear Filter</a>
                </div>
            </form>
        </div>
    </div>
<?php endif; ?>

<script>
    (function () {
        const statusBtn = document.querySelector('[data-status-toggle]');
        const statusMenu = document.querySelector('[data-status-menu]');
        if (!statusBtn || !statusMenu) return;
        statusBtn.addEventListener('click', function (event) {
            event.stopPropagation();
            statusMenu.classList.toggle('open');
        });
        document.addEventListener('click', function (event) {
            if (!statusMenu.contains(event.target) && !statusBtn.contains(event.target)) {
                statusMenu.classList.remove('open');
            }
        });
    })();

    (function () {
        const moreBtn = document.querySelector('[data-more-toggle]');
        const moreMenu = document.querySelector('[data-more-menu]');
        if (!moreBtn || !moreMenu) return;
        moreBtn.addEventListener('click', function (event) {
            event.stopPropagation();
            moreMenu.classList.toggle('open');
        });
        document.addEventListener('click', function (event) {
            if (!moreMenu.contains(event.target) && !moreBtn.contains(event.target)) {
                moreMenu.classList.remove('open');
            }
        });
    })();
    (function () {
        const selects = document.querySelectorAll('[data-search-select]');
        if (!selects.length) return;

        const closeAll = (except) => {
            selects.forEach((root) => {
                if (root === except) return;
                const menu = root.querySelector('[data-search-menu]');
                if (menu) menu.hidden = true;
            });
        };

        selects.forEach((root) => {
            const hiddenInput = root.querySelector('input[type="hidden"]');
            const trigger = root.querySelector('[data-search-trigger]');
            const label = root.querySelector('[data-search-label]');
            const menu = root.querySelector('[data-search-menu]');
            const searchInput = root.querySelector('[data-search-input]');
            const options = root.querySelectorAll('[data-search-option]');

            const syncTrigger = (text, empty) => {
                if (label) label.textContent = text;
                if (trigger) trigger.classList.toggle('is-empty', empty);
            };

            if (trigger && menu) {
                trigger.addEventListener('click', function (event) {
                    event.preventDefault();
                    const willOpen = menu.hidden;
                    closeAll(root);
                    menu.hidden = !willOpen;
                    if (willOpen && searchInput) {
                        searchInput.value = '';
                        options.forEach(option => option.hidden = false);
                        searchInput.focus();
                    }
                });
            }

            if (searchInput) {
                searchInput.addEventListener('input', function () {
                    const query = searchInput.value.trim().toLowerCase();
                    options.forEach((option) => {
                        const text = (option.getAttribute('data-label') || option.textContent || '').toLowerCase();
                        option.hidden = query !== '' && !text.includes(query);
                    });
                });
            }

            options.forEach((option) => {
                option.addEventListener('click', function () {
                    const value = option.getAttribute('data-value') || '';
                    const text = option.getAttribute('data-label') || option.textContent || '';
                    if (hiddenInput) hiddenInput.value = value;
                    syncTrigger(text, value === '');
                    options.forEach(item => item.classList.remove('is-active'));
                    option.classList.add('is-active');
                    if (menu) menu.hidden = true;

                    if (hiddenInput && hiddenInput.name === 'loan_type_id') {
                        const rateNode = document.querySelector('[data-loan-rate]');
                        if (rateNode) {
                            rateNode.textContent = option.getAttribute('data-rate') || '0.00';
                        }
                    }
                });
            });
        });

        document.addEventListener('click', function (event) {
            if (event.target.closest('[data-search-select]')) return;
            closeAll(null);
        });
    })();
    (function () {
        const loanForm = document.querySelector('.loan-create-form');
        if (!loanForm) return;
        loanForm.addEventListener('submit', function (event) {
            const requiredFields = [
                { name: 'loan_type_id', label: 'Loan Name' },
                { name: 'employee_id', label: 'Employee Name' },
                { name: 'paid_through_account', label: 'Paid Through Account' }
            ];
            for (const field of requiredFields) {
                const input = loanForm.querySelector(`input[name="${field.name}"]`);
                if (input && String(input.value).trim() === '') {
                    event.preventDefault();
                    alert(`Please select ${field.label}.`);
                    return;
                }
            }
        });
    })();
</script>
</body>
</html>
