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

ensure_poi_schema($conn);
$orgContext = poi_org_context($conn);
$orgName = $orgContext['org_name'];
$orgId = $orgContext['org_id'];
poi_ensure_settings_row($conn, $orgId);
$settings = poi_get_settings($conn, $orgId);

$employees = poi_load_employees($conn);
$employeeOptions = [];
foreach ($employees as $employee) {
    $employeeOptions[(int) ($employee['id'] ?? 0)] = poi_employee_label($employee);
}

$fiscalYears = poi_fiscal_years();
$taxRegimes = poi_tax_regimes();
$viewType = $_GET['view'] ?? 'all';
$selectedFiscalYear = $_GET['fiscal_year'] ?? $fiscalYears[0];
$selectedTaxRegime = $_GET['tax_regime'] ?? 'Select Tax Regime';
$selectedEmployeeId = isset($_GET['employee_id']) ? (int) $_GET['employee_id'] : 0;
$unsubmittedEmployees = poi_unsubmitted_employees($conn, $orgId, $selectedFiscalYear);
$unsubmittedCount = count($unsubmittedEmployees);

$viewMap = [
    'all' => 'All Investments',
    'pending' => 'Approval Pending Investments',
    'unsubmitted' => 'Yet To Confirm Investments',
    'approved' => 'Approved Investments',
];
if (!isset($viewMap[$viewType])) {
    $viewType = 'all';
}

$statusFilter = '';
if ($viewType === 'pending') {
    $statusFilter = 'submitted';
} elseif ($viewType === 'approved') {
    $statusFilter = 'approved';
}

$submissionRows = poi_submission_rows($conn, $orgId, [
    'fiscal_year' => $selectedFiscalYear,
    'tax_regime' => $selectedTaxRegime,
    'employee_id' => $selectedEmployeeId,
    'status' => $statusFilter,
]);
?>
<!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 | POI</title>
  <link rel="stylesheet" href="dashboard.css">
  <link rel="stylesheet" href="poi.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body class="dash-page poi-page">
<div class="dash-layout">
  <aside class="dash-sidebar poi-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"></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" href="reimbursements.php">Reimbursements</a>
            <a class="nav-sub-item active" 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">
      <div class="poi-toolbar">
        <div class="poi-title-wrap">
          <button class="poi-title-btn" type="button" data-toggle="poiViewMenu">
            <?php echo htmlspecialchars($viewMap[$viewType]); ?>
            <i class="fa-solid fa-angle-down"></i>
          </button>
          <div class="poi-dropdown" id="poiViewMenu" aria-hidden="true">
            <a href="proof_of_investments.php?view=all" class="<?php echo $viewType === 'all' ? 'active' : ''; ?>">All Investments</a>
            <a href="proof_of_investments.php?view=pending" class="<?php echo $viewType === 'pending' ? 'active' : ''; ?>">Approval Pending Investments</a>
            <a href="proof_of_investments.php?view=unsubmitted" class="<?php echo $viewType === 'unsubmitted' ? 'active' : ''; ?>">Yet To Confirm Investments</a>
            <a href="proof_of_investments.php?view=approved" class="<?php echo $viewType === 'approved' ? 'active' : ''; ?>">Approved Investments</a>
          </div>
        </div>

        <div class="poi-actions">
          <div class="poi-warning">
            <i class="fa-solid fa-circle-exclamation"></i>
            <span><?php echo $unsubmittedCount; ?> employee(s) yet to submit POI</span>
            <a href="poi_unsubmitted.php">View</a>
          </div>
          <div class="poi-menu-anchor">
            <button class="poi-icon-btn" type="button" data-toggle="poiMoreMenu"><i class="fa-solid fa-ellipsis"></i></button>
            <div class="poi-dropdown right" id="poiMoreMenu" aria-hidden="true">
              <a href="poi_settings.php"><i class="fa-solid fa-lock-open"></i>Release POI</a>
            </div>
          </div>
          <button class="poi-icon-btn" type="button"><i class="fa-solid fa-filter"></i></button>
          <button class="poi-icon-btn" type="button">?</button>
        </div>
      </div>

      <form class="poi-filter-row" method="GET">
        <input type="hidden" name="view" value="<?php echo htmlspecialchars($viewType); ?>">
        <div class="poi-chip">
          <span>Fiscal Year:</span>
          <select name="fiscal_year">
            <?php foreach ($fiscalYears as $year): ?>
              <option value="<?php echo htmlspecialchars($year); ?>" <?php echo $selectedFiscalYear === $year ? 'selected' : ''; ?>><?php echo htmlspecialchars($year); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="poi-chip">
          <span>Tax Regime:</span>
          <select name="tax_regime">
            <?php foreach ($taxRegimes as $regime): ?>
              <option value="<?php echo htmlspecialchars($regime); ?>" <?php echo $selectedTaxRegime === $regime ? 'selected' : ''; ?>><?php echo htmlspecialchars($regime); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="poi-chip">
          <span>Employees:</span>
          <select name="employee_id">
            <option value="0">Select an Employee</option>
            <?php foreach ($employeeOptions as $employeeId => $label): ?>
              <option value="<?php echo $employeeId; ?>" <?php echo $selectedEmployeeId === $employeeId ? 'selected' : ''; ?>><?php echo htmlspecialchars($label); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </form>

      <?php if ($submissionRows): ?>
        <div class="poi-table-wrap">
          <table class="poi-table">
            <thead>
              <tr>
                <th>EMPLOYEE NAME</th>
                <th>FISCAL YEAR</th>
                <th>TAX REGIME</th>
                <th>INVESTMENT</th>
                <th>DECLARED AMOUNT</th>
                <th>STATUS</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($submissionRows as $submission): ?>
                <tr>
                  <td><?php echo htmlspecialchars($submission['employee'] ? poi_employee_label($submission['employee']) : ('Employee #' . (int) $submission['employee_id'])); ?></td>
                  <td><?php echo htmlspecialchars((string) $submission['fiscal_year']); ?></td>
                  <td><?php echo htmlspecialchars((string) $submission['tax_regime']); ?></td>
                  <td><?php echo htmlspecialchars((string) ($submission['investment_name'] ?: '-')); ?></td>
                  <td><?php echo htmlspecialchars(number_format((float) $submission['declared_amount'], 2)); ?></td>
                  <td><span class="poi-status-pill <?php echo $submission['status'] === 'approved' ? 'enabled' : 'locked'; ?>"><?php echo htmlspecialchars(ucfirst((string) $submission['status'])); ?></span></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php else: ?>
        <div class="poi-empty">
          <div class="poi-empty-card">
            <div class="poi-empty-figure" aria-hidden="true">
              <div class="poi-step left">1. Employee submits proof of investments</div>
              <div class="poi-board">
                <div class="poi-card-line"></div>
                <div class="poi-card-line-2"></div>
                <div class="poi-cross"></div>
                <div class="poi-check"></div>
              </div>
              <div class="poi-step right">2. Payroll Admin approves or rejects the submitted proofs</div>
              <div class="poi-step bottom">3. Employee enjoys tax savings for the declared investment</div>
            </div>
            <h2>This is your space to review your employees' investment proofs!</h2>
            <p>Your employees can submit their investment proofs through the employee portal once you enable the option in <a href="poi_settings.php" style="color:#2463d3;text-decoration:none;">Settings &gt; Preferences</a>.</p>
          </div>
        </div>
      <?php endif; ?>
    </section>
  </main>
</div>

<script>
  (function(){
    document.querySelectorAll('[data-toggle]').forEach(function(button){
      button.addEventListener('click', function(event){
        const menu = document.getElementById(button.getAttribute('data-toggle'));
        if (!menu) return;
        const nextState = menu.getAttribute('aria-hidden') === 'true';
        document.querySelectorAll('.poi-dropdown').forEach(function(item){ item.setAttribute('aria-hidden', 'true'); });
        menu.setAttribute('aria-hidden', nextState ? 'false' : 'true');
        event.stopPropagation();
      });
    });
    document.addEventListener('click', function(){
      document.querySelectorAll('.poi-dropdown').forEach(function(item){ item.setAttribute('aria-hidden', 'true'); });
    });
    document.querySelectorAll('[data-nav-toggle]').forEach(function(button){
      button.addEventListener('click', function(){
        const group = button.closest('.nav-group');
        if (group) group.classList.toggle('open');
      });
    });
  })();
</script>
</body>
</html>

