<?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);

$employeeId = isset($_GET['emp_id']) ? (int) $_GET['emp_id'] : 0;
$employee = $employeeId > 0 ? poi_find_employee($conn, $employeeId) : null;
if (!$employee) {
    header("Location: employees.php?step=list");
    exit();
}

$fiscalYears = poi_fiscal_years();
$taxRegimes = array_values(array_filter(poi_tax_regimes(), static function ($item) {
    return $item !== 'Select Tax Regime';
}));
$selectedFiscalYear = $_GET['fiscal_year'] ?? $fiscalYears[0];
$existing = poi_submission_record($conn, $orgId, $employeeId, $selectedFiscalYear);

$form = [
    'fiscal_year' => $selectedFiscalYear,
    'tax_regime' => $existing['tax_regime'] ?? $taxRegimes[0],
    'investment_name' => $existing['investment_name'] ?? '',
    'declared_amount' => $existing['declared_amount'] ?? '',
    'notes' => $existing['notes'] ?? '',
];
$success = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['fiscal_year'] = trim((string) ($_POST['fiscal_year'] ?? $fiscalYears[0]));
    $form['tax_regime'] = trim((string) ($_POST['tax_regime'] ?? $taxRegimes[0]));
    $form['investment_name'] = trim((string) ($_POST['investment_name'] ?? ''));
    $form['declared_amount'] = trim((string) ($_POST['declared_amount'] ?? ''));
    $form['notes'] = trim((string) ($_POST['notes'] ?? ''));

    if ($form['investment_name'] === '') {
        $errors[] = 'Enter an investment name.';
    }
    if ($form['declared_amount'] === '' || !is_numeric($form['declared_amount'])) {
        $errors[] = 'Enter a valid declared amount.';
    }
    if (!in_array($form['fiscal_year'], $fiscalYears, true)) {
        $errors[] = 'Select a valid fiscal year.';
    }
    if (!in_array($form['tax_regime'], $taxRegimes, true)) {
        $errors[] = 'Select a valid tax regime.';
    }

    if (!$errors) {
        $saved = poi_save_submission($conn, $orgId, $employeeId, [
            'fiscal_year' => $form['fiscal_year'],
            'tax_regime' => $form['tax_regime'],
            'investment_name' => $form['investment_name'],
            'notes' => $form['notes'],
            'declared_amount' => (float) $form['declared_amount'],
            'approved_amount' => $existing['approved_amount'] ?? 0,
            'status' => 'submitted',
        ]);

        if ($saved) {
            $success = 'Proof of investment submitted successfully.';
            $existing = poi_submission_record($conn, $orgId, $employeeId, $form['fiscal_year']);
            $form['declared_amount'] = $existing['declared_amount'] ?? $form['declared_amount'];
        } else {
            $errors[] = 'Unable to save proof of investment right now.';
        }
    }
}

$employeeLabel = poi_employee_label($employee);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Employee POI Submission</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/b2l_mobitech_pvt_ltd_logo.jpg" class="logo" alt="B2L Mobitech Pvt Ltd">
    </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 active" 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>
      </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>
        <span class="avatar"><?php echo strtoupper(substr($orgName, 0, 1)); ?></span>
      </div>
    </header>

    <section class="dash-content">
      <div class="poi-list-toolbar">
        <div class="poi-list-title">
          <a class="poi-back-btn" href="employee_overview.php?emp_id=<?php echo urlencode((string) $employeeId); ?>"><i class="fa-solid fa-chevron-left"></i></a>
          <h1>Proof Of Investments</h1>
        </div>
      </div>

      <div class="poi-entry-card">
        <div class="poi-entry-head">
          <h2><?php echo htmlspecialchars($employeeLabel); ?></h2>
          <p>Submit and store the employee's proof of investment details for payroll approvals.</p>
        </div>

        <?php if ($success): ?>
          <div class="poi-flash ok"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($errors): ?>
          <div class="poi-flash err">
            <?php foreach ($errors as $error): ?>
              <div><?php echo htmlspecialchars($error); ?></div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>

        <form method="POST" class="poi-entry-form">
          <div class="poi-entry-grid">
            <div class="poi-form-group">
              <label for="poi_fiscal_year">Fiscal Year</label>
              <select id="poi_fiscal_year" name="fiscal_year" class="poi-modal-select">
                <?php foreach ($fiscalYears as $year): ?>
                  <option value="<?php echo htmlspecialchars($year); ?>" <?php echo $form['fiscal_year'] === $year ? 'selected' : ''; ?>><?php echo htmlspecialchars($year); ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="poi-form-group">
              <label for="poi_tax_regime">Tax Regime</label>
              <select id="poi_tax_regime" name="tax_regime" class="poi-modal-select">
                <?php foreach ($taxRegimes as $regime): ?>
                  <option value="<?php echo htmlspecialchars($regime); ?>" <?php echo $form['tax_regime'] === $regime ? 'selected' : ''; ?>><?php echo htmlspecialchars($regime); ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

          <div class="poi-form-group">
            <label for="poi_investment_name">Investment Name</label>
            <input id="poi_investment_name" class="poi-text-input" type="text" name="investment_name" value="<?php echo htmlspecialchars((string) $form['investment_name']); ?>" placeholder="Example: LIC / PPF / Home Loan Interest">
          </div>

          <div class="poi-entry-grid">
            <div class="poi-form-group">
              <label for="poi_declared_amount">Declared Amount</label>
              <input id="poi_declared_amount" class="poi-text-input" type="number" name="declared_amount" min="0" step="0.01" value="<?php echo htmlspecialchars((string) $form['declared_amount']); ?>" placeholder="0.00">
            </div>
            <div class="poi-form-group">
              <label>Current Status</label>
              <div class="poi-static-field"><?php echo htmlspecialchars($existing['status'] ?? 'Not Submitted'); ?></div>
            </div>
          </div>

          <div class="poi-form-group">
            <label for="poi_notes">Notes</label>
            <textarea id="poi_notes" class="poi-textarea" name="notes" rows="5" placeholder="Add short supporting details"><?php echo htmlspecialchars((string) $form['notes']); ?></textarea>
          </div>

          <div class="poi-entry-actions">
            <button class="poi-primary-btn" type="submit">Submit POI</button>
            <a class="poi-outline-btn" href="employee_overview.php?emp_id=<?php echo urlencode((string) $employeeId); ?>">Cancel</a>
          </div>
        </form>
      </div>
    </section>
  </main>
</div>
</body>
</html>
