<?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/reimbursements_module.php';

ensure_reimbursements_schema($conn);
$orgContext = reimbursement_org_context($conn);
$orgName = $orgContext['org_name'];
$orgId = (string) $orgContext['org_id'];

$status = $_GET['status'] ?? 'all';
$month = trim((string) ($_GET['month'] ?? ''));
$employeeFilter = isset($_GET['employee_id']) ? (int) $_GET['employee_id'] : 0;
$showFilters = isset($_GET['filters']) && $_GET['filters'] === '1';

if (!in_array($status, ['all', 'pending', 'approved', 'rejected'], true)) {
    $status = 'all';
}

$employees = reimbursement_load_employees($conn);
$employeeMap = reimbursement_employee_map($employees);
$employeeFilterOptions = [];
foreach ($employees as $employee) {
    $id = (int) ($employee['id'] ?? 0);
    $code = trim((string) ($employee['employee_code'] ?? $employee['employee_id'] ?? $id));
    $employeeFilterOptions[$id] = reimbursement_employee_name($employee) . ' (' . $code . ')';
}
$statusLabelMap = [
    'all' => 'All Claims',
    'pending' => 'Pending Claims',
    'approved' => 'Approved Claims',
    'rejected' => 'Rejected Claims',
];
$currentStatusLabel = $statusLabelMap[$status];

$filters = ["c.org_id = ?"];
$params = [$orgId];
$types = 's';

if ($status !== 'all') {
    $filters[] = "c.status = ?";
    $params[] = $status;
    $types .= 's';
}
if ($month !== '') {
    $filters[] = "DATE_FORMAT(c.claim_month, '%Y-%m') = ?";
    $params[] = $month;
    $types .= 's';
}
if ($employeeFilter > 0) {
    $filters[] = "c.employee_id = ?";
    $params[] = $employeeFilter;
    $types .= 'i';
}

$whereSql = 'WHERE ' . implode(' AND ', $filters);
$claims = [];
$sql = "SELECT
            c.id,
            c.employee_id,
            c.claim_month,
            c.status,
            c.total_claim_amount,
            c.total_approved_amount,
            c.notes,
            c.created_at,
            COUNT(i.id) AS bill_count
        FROM reimbursement_claims c
        LEFT JOIN reimbursement_items i ON i.claim_id = c.id
        {$whereSql}
        GROUP BY c.id
        ORDER BY c.claim_month DESC, c.id DESC";

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

$countMap = ['all' => 0, 'pending' => 0, 'approved' => 0, 'rejected' => 0];
$countResult = $conn->prepare("SELECT status, COUNT(*) AS total FROM reimbursement_claims WHERE org_id = ? GROUP BY status");
if ($countResult) {
    $countResult->bind_param('s', $orgId);
    $countResult->execute();
    $res = $countResult->get_result();
    while ($row = $res->fetch_assoc()) {
        $countMap[$row['status']] = (int) $row['total'];
        $countMap['all'] += (int) $row['total'];
    }
    $countResult->close();
}

$hasActiveFilters = ($month !== '' || $employeeFilter > 0);
$selectedEmployeeName = $employeeFilter > 0 ? ($employeeFilterOptions[$employeeFilter] ?? ($employeeMap[$employeeFilter] ?? 'Employee')) : 'Select an Employee';
$exportMonthText = $month !== '' ? reimbursement_format_month($month . '-01') : date('M Y');
$chipMonthText = $month !== '' ? reimbursement_format_month($month . '-01') : 'Select Month';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
    <title>Approvals | Reimbursements</title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="reimbursements.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body class="dash-page reimburse-shell reimburse-list-page">
<div class="dash-layout">
    <aside class="dash-sidebar reimburse-sidebar">
        <div class="sidebar-brand">
            <img src="images/zoho-payroll-logo.svg" class="logo" alt="Zoho Payroll">
        </div>
        <div class="sidebar-scroll">
            <div class="sidebar-section">
                <div class="getting-started">
                    <div class="gs-top">
                        <i class="fa-solid fa-sparkles"></i>
                        <span>Getting Started</span>
                    </div>
                    <div class="progress-bar"><div class="progress-fill reimburse-progress"></div></div>
                </div>
            </div>
            <nav class="sidebar-nav">
                <a class="nav-item" href="dashboard.php"><i class="fa-regular fa-circle-dot"></i><span>Dashboard</span></a>
                <a class="nav-item" href="employees.php"><i class="fa-regular fa-user"></i><span>Employees</span></a>
                <a class="nav-item" href="payruns.php"><i class="fa-regular fa-calendar-check"></i><span>Pay Runs</span></a>
                <div class="nav-group open">
                    <button class="nav-item btn active" type="button" data-nav-toggle><i class="fa-regular fa-square-check"></i><span>Approvals</span></button>
                    <div class="nav-sub">
                        <a class="nav-sub-item active" href="reimbursements.php">Reimbursements</a>
                        <a class="nav-sub-item" href="proof_of_investments.php">Proof Of Investments</a>
                        <a class="nav-sub-item" href="salary_revision.php">Salary Revision</a>
                    </div>
                </div>
                <a class="nav-item" href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
                <a class="nav-item" href="loans.php"><i class="fa-solid fa-indian-rupee-sign"></i><span>Loans</span></a>
                <a class="nav-item" href="giving.php"><i class="fa-regular fa-heart"></i><span>Giving</span></a>
                <a class="nav-item" href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
                <a class="nav-item" href="reports.php"><i class="fa-regular fa-chart-bar"></i><span>Reports</span></a>
                <a class="nav-item" href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a>
            </nav>
        </div>
        <div class="sidebar-footer">
            <a class="support-link" href="#">Contact Support</a>
        </div>
    </aside>

    <main class="dash-main">
        <header class="dash-topbar">
            <div class="search-box">
                <i class="fa-solid fa-magnifying-glass search-icon"></i>
                <input type="text" placeholder="Search in Employee">
            </div>
            <div class="topbar-actions">
                <span class="trial">Your trial expires in 1 day(s). <a href="dashboard.php?modal=upgrade">Upgrade</a></span>
                <a class="pill ghost org-toggle" href="#"><span class="pill-label"><?php echo htmlspecialchars($orgName); ?></span><i class="fa-solid fa-angle-down"></i></a>
                <a class="top-icon icon-btn" href="#"><i class="fa-regular fa-user-group"></i></a>
                <a class="top-icon icon-btn" href="#"><i class="fa-regular fa-bell"></i></a>
                <a class="top-icon top-link" href="settings.php"><i class="fa-solid fa-gear"></i></a>
                <span class="avatar"><?php echo strtoupper(substr($orgName, 0, 1)); ?></span>
                <a class="top-icon icon-btn" href="#"><i class="fa-solid fa-table-cells-large"></i></a>
            </div>
        </header>

        <section class="dash-content reimburse-wrap">
            <div class="reimburse-toolbar">
                <div class="title-cluster">
                    <div class="title-wrap">
                        <button class="title-btn" type="button" data-toggle="statusMenu">
                            <?php echo htmlspecialchars($currentStatusLabel); ?>
                            <i class="fa-solid fa-angle-down"></i>
                        </button>
                        <div class="dropdown-menu status-menu" id="statusMenu" aria-hidden="true">
                            <?php foreach ($statusLabelMap as $statusKey => $label): ?>
                                <a href="reimbursements.php?status=<?php echo urlencode($statusKey); ?>" class="<?php echo $status === $statusKey ? 'active' : ''; ?>">
                                    <span><?php echo htmlspecialchars($label); ?></span>
                                    <strong><?php echo htmlspecialchars((string) $countMap[$statusKey]); ?></strong>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="head-actions">
                    <a class="btn-add" href="reimbursements_new.php"><i class="fa-solid fa-plus"></i><span>Add</span></a>
                    <div class="menu-anchor">
                        <button class="btn-icon" type="button" data-toggle="moreMenu"><i class="fa-solid fa-ellipsis"></i></button>
                        <div class="dropdown-menu action-menu" id="moreMenu" aria-hidden="true">
                            <a href="reimbursements_import.php"><i class="fa-solid fa-download"></i><span>Import Reimbursements</span></a>
                            <button type="button" data-open-modal="export"><i class="fa-solid fa-upload"></i><span>Export Reimbursements</span></button>
                        </div>
                    </div>
                    <a class="btn-icon <?php echo $showFilters ? 'active' : ''; ?>" href="reimbursements.php?status=<?php echo urlencode($status); ?>&month=<?php echo urlencode($month); ?>&employee_id=<?php echo urlencode((string) $employeeFilter); ?>&filters=<?php echo $showFilters ? '0' : '1'; ?>"><i class="fa-solid fa-filter"></i></a>
                    <button class="btn-icon btn-help" type="button">?</button>
                </div>
            </div>

            <?php if ($hasActiveFilters): ?>
                <form class="filter-row" method="GET">
                    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status); ?>">
                    <div class="chip chip-month <?php echo $month !== '' ? 'has-value' : ''; ?>">
                        <span>Claim Month:</span>
                        <strong><?php echo htmlspecialchars($chipMonthText); ?></strong>
                        <?php if ($month !== ''): ?><i class="fa-solid fa-xmark"></i><?php endif; ?>
                    </div>
                    <div class="chip chip-select <?php echo $employeeFilter > 0 ? 'has-value' : ''; ?>">
                        <span>Employees:</span>
                        <strong><?php echo htmlspecialchars($selectedEmployeeName); ?></strong>
                        <i class="fa-solid <?php echo $employeeFilter > 0 ? 'fa-xmark' : 'fa-angle-down'; ?>"></i>
                    </div>
                    <input type="hidden" name="month" value="<?php echo htmlspecialchars($month); ?>">
                    <input type="hidden" name="employee_id" value="<?php echo htmlspecialchars((string) $employeeFilter); ?>">
                    <button class="sr-only" type="submit">Apply</button>
                    <a class="clear-link" href="reimbursements.php?status=<?php echo urlencode($status); ?>">
                        <i class="fa-solid fa-xmark"></i>
                        <span>Clear Filter</span>
                    </a>
                </form>
            <?php endif; ?>

            <?php if ($showFilters): ?>
                <form class="filter-panel" method="GET">
                    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status); ?>">
                    <input type="hidden" name="filters" value="1">
                    <div class="panel-field">
                        <label for="monthFilter">Claim month</label>
                        <input id="monthFilter" type="month" name="month" value="<?php echo htmlspecialchars($month); ?>">
                    </div>
                    <div class="panel-field">
                        <label for="employeeFilter">Employee</label>
                        <select id="employeeFilter" name="employee_id">
                            <option value="0">Select an Employee</option>
                            <?php foreach ($employeeFilterOptions as $employeeId => $employeeLabel): ?>
                                <option value="<?php echo $employeeId; ?>" <?php echo $employeeFilter === $employeeId ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($employeeLabel); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="panel-actions">
                        <button class="btn-primary" type="submit">Apply Filter</button>
                        <a class="btn-outline" href="reimbursements.php?status=<?php echo urlencode($status); ?>">Reset</a>
                    </div>
                </form>
            <?php endif; ?>

            <?php if (empty($claims)): ?>
                <div class="empty-state reimburse-empty">
                    <div class="empty-illustration" aria-hidden="true">
                        <div class="ghost-card">
                            <div class="ghost-head"></div>
                            <div class="ghost-eye eye-left"></div>
                            <div class="ghost-eye eye-right"></div>
                            <div class="ghost-body"></div>
                            <div class="ghost-tie"></div>
                        </div>
                    </div>
                    <h3>No results found</h3>
                    <p>Looks like you don't have any results for the filter applied</p>
                </div>
            <?php else: ?>
                <div class="claims-card">
                    <div class="claims-table">
                        <div class="claims-row head">
                            <div>Employee</div>
                            <div>Claim Month</div>
                            <div>Bills</div>
                            <div>Claim Amount</div>
                            <div>Approved Amount</div>
                            <div>Status</div>
                        </div>
                        <?php foreach ($claims as $claim): ?>
                            <div class="claims-row">
                                <div class="claim-main">
                                    <strong><?php echo htmlspecialchars($employeeMap[(int) $claim['employee_id']] ?? 'Employee'); ?></strong>
                                    <span>#<?php echo htmlspecialchars((string) $claim['id']); ?></span>
                                </div>
                                <div><?php echo htmlspecialchars(reimbursement_format_month($claim['claim_month'])); ?></div>
                                <div><?php echo htmlspecialchars((string) $claim['bill_count']); ?> bill(s)</div>
                                <div><?php echo htmlspecialchars(number_format((float) $claim['total_claim_amount'], 2)); ?></div>
                                <div><?php echo htmlspecialchars(number_format((float) $claim['total_approved_amount'], 2)); ?></div>
                                <div><span class="status-pill <?php echo htmlspecialchars($claim['status']); ?>"><?php echo htmlspecialchars(ucfirst($claim['status'])); ?></span></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </section>
    </main>
</div>

<div class="modal" id="exportModal" aria-hidden="true">
    <div class="modal-backdrop" data-close-modal></div>
    <div class="modal-card export-card">
        <div class="modal-head">
            <h3>Export Reimbursements</h3>
            <button class="modal-close" type="button" data-close-modal><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="modal-body export-body">
            <label class="modal-label" for="exportPeriod">Period</label>
            <input id="exportPeriod" class="modal-input" type="text" value="<?php echo htmlspecialchars($exportMonthText); ?>">

            <label class="modal-label" for="exportFilter">Filter By</label>
            <select id="exportFilter" class="modal-input">
                <option <?php echo $status === 'all' ? 'selected' : ''; ?>>All Claims</option>
                <option <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending Claims</option>
                <option <?php echo $status === 'approved' ? 'selected' : ''; ?>>Approved Claims</option>
                <option <?php echo $status === 'rejected' ? 'selected' : ''; ?>>Rejected Claims</option>
            </select>

            <label class="modal-label" for="exportAs">Export as</label>
            <select id="exportAs" class="modal-input">
                <option>CSV (Comma Separated Values)</option>
                <option selected>XLS (Microsoft Excel 1997-2004 Compatible)</option>
                <option>XLSX (Microsoft Excel)</option>
            </select>

            <label class="check-row">
                <input type="checkbox">
                <span>Protect this file with a password</span>
            </label>
        </div>
        <div class="modal-actions">
            <button class="btn-primary" type="button">Export</button>
            <button class="btn-outline" type="button" data-close-modal>Cancel</button>
        </div>
    </div>
</div>

<script>
  (function(){
    const toggles = document.querySelectorAll('[data-toggle]');
    toggles.forEach(function(btn){
      btn.addEventListener('click', function(event){
        const menuId = btn.getAttribute('data-toggle');
        const menu = document.getElementById(menuId);
        if (!menu) return;
        const nextState = menu.getAttribute('aria-hidden') === 'true';
        document.querySelectorAll('.dropdown-menu').forEach(function(item){
          item.setAttribute('aria-hidden', 'true');
        });
        menu.setAttribute('aria-hidden', nextState ? 'false' : 'true');
        event.stopPropagation();
      });
    });
    document.addEventListener('click', function(){
      document.querySelectorAll('.dropdown-menu').forEach(function(item){
        item.setAttribute('aria-hidden', 'true');
      });
    });
  })();

  (function(){
    document.querySelectorAll('[data-open-modal]').forEach(function(button){
      button.addEventListener('click', function(){
        const modal = document.getElementById('exportModal');
        if (!modal) return;
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('modal-open');
      });
    });
    document.querySelectorAll('[data-close-modal]').forEach(function(button){
      button.addEventListener('click', function(){
        document.querySelectorAll('.modal').forEach(function(modal){
          modal.setAttribute('aria-hidden', 'true');
        });
        document.body.classList.remove('modal-open');
      });
    });
  })();

  (function(){
    const toggles = document.querySelectorAll('[data-nav-toggle]');
    toggles.forEach(function(btn){
      btn.addEventListener('click', function(){
        const group = btn.closest('.nav-group');
        if (!group) return;
        group.classList.toggle('open');
      });
    });
  })();
</script>
</body>
</html>

