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

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

require_once __DIR__ . '/db.php';
ensure_tax_forms_schema($conn);

$orgContext = tax_forms_org_context($conn);
$orgName = $orgContext['org_name'];
$orgId = $orgContext['org_id'];
$taxDetails = tax_details_get($conn, $orgId);
$taxDeductorName = trim((string) ($taxDetails['deductor_name'] ?? ''));
$selectedDeductor = isset($_GET['deductor']) ? trim((string) $_GET['deductor']) : '';
$hasDeductor = $taxDeductorName !== '';
$selectedDeductor = ($hasDeductor && $selectedDeductor === '') ? $taxDeductorName : $selectedDeductor;
$form16Choices = $hasDeductor ? [$taxDeductorName] : [];
?>
<!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>Form 16 | Payroll</title>
  <link rel="stylesheet" href="dashboard.css">
  <link rel="stylesheet" href="tax_forms.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body class="dash-page tf-page">
<div class="dash-layout">
  <aside class="dash-sidebar tf-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">
          <button class="nav-item btn" 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" 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 active" 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>
    <div class="tf-support-tile">
      <div class="support-title">Track TDS Liabilities and Generate Form 24Q</div>
      <a class="support-action" href="#">View Details</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 0 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="tf-header">
        <div class="tf-title-row">
          <h1 class="tf-title">
            <span>Form 16:</span>
            <span class="tf-select-anchor" data-select-anchor>
              <button class="tf-title-button" type="button" data-select-toggle>
                <span class="tf-select-label"><?php echo $selectedDeductor !== '' ? htmlspecialchars($selectedDeductor) : 'Select'; ?></span>
                <i class="fa-solid fa-angle-down"></i>
              </button>
              <div class="tf-select-menu" aria-hidden="true">
                <div class="tf-select-search">
                  <i class="fa-solid fa-magnifying-glass"></i>
                  <input type="text" placeholder="" data-select-search>
                </div>
                <div class="tf-select-options" data-select-options>
                  <?php if ($form16Choices): ?>
                    <?php foreach ($form16Choices as $choice): ?>
                      <a class="tf-select-option<?php echo $selectedDeductor === $choice ? ' active' : ''; ?>" href="form16.php?deductor=<?php echo urlencode($choice); ?>"><?php echo htmlspecialchars($choice); ?></a>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <div class="tf-select-empty">SORRY! NO RESULTS FOUND</div>
                  <?php endif; ?>
                </div>
              </div>
            </span>
          </h1>
        </div>
        <div class="tf-header-tools">
          <a class="tf-help-btn" href="#" aria-label="Help">?</a>
        </div>
      </div>

      <?php if (!empty($_SESSION['tax_flash_ok'])): ?>
        <div class="tf-flash ok"><?php echo htmlspecialchars($_SESSION['tax_flash_ok']); unset($_SESSION['tax_flash_ok']); ?></div>
      <?php endif; ?>

      <div class="tf-center-block">
        <p class="tf-kicker">It's time to generate Form 16 for the financial year</p>
        <div class="tf-kicker-bar"></div>
        <h2 class="tf-section-title">Verify your tax deductor</h2>

        <div class="tf-deductor-card">
          <?php if ($hasDeductor): ?>
            <p><?php echo htmlspecialchars($taxDeductorName); ?></p>
            <a class="tf-link-btn" href="tax_details.php">Review Tax Deductor</a>
          <?php else: ?>
            <p>Tax Deductor is not found</p>
            <a class="tf-link-btn" href="tax_details.php">+ Add Tax Deductor</a>
          <?php endif; ?>
        </div>

        <div class="tf-note">Note: Remember that once you generate Form 16, you cannot change the deductor details.</div>
      </div>

      <div class="tf-steps-wrap">
        <h2>How to generate Form 16 for your employees?</h2>
        <div class="tf-steps-card">
          <div class="tf-steps-main">
            <div class="tf-steps-head">
              <span class="label">Steps to Generate Form 16</span>
              <a href="#"><i class="fa-regular fa-lightbulb"></i> Help Guide</a>
            </div>
            <div class="tf-steps-flow">
              <div class="tf-step-item upload">
                <div class="tf-step-icon"><i class="fa-solid fa-cloud-arrow-up"></i></div>
                <span>Upload Form 16 Part A</span>
              </div>
              <div class="tf-step-item generate">
                <div class="tf-step-icon"><i class="fa-regular fa-file-lines"></i></div>
                <span>Generate Form 16</span>
              </div>
              <div class="tf-step-item sign">
                <div class="tf-step-icon"><i class="fa-solid fa-signature"></i></div>
                <span>Sign Form 16</span>
              </div>
              <div class="tf-step-item publish">
                <div class="tf-step-icon"><i class="fa-solid fa-paper-plane"></i></div>
                <span>Publish/Email</span>
              </div>
            </div>
          </div>
          <aside class="tf-video-card">
            <div class="tf-video-inner">
              <div class="tf-video-play"><i class="fa-solid fa-play"></i></div>
              <div>Learn how to<br>generate Form 16</div>
            </div>
          </aside>
        </div>
      </div>
    </section>
  </main>
</div>

<a class="tf-fab-help" href="#" aria-label="Help">?</a>

<script>
  (function(){
    document.querySelectorAll('[data-nav-toggle]').forEach(function(button){
      button.addEventListener('click', function(){
        const group = button.closest('.nav-group');
        if (group) group.classList.toggle('open');
      });
    });

    const anchor = document.querySelector('[data-select-anchor]');
    const toggle = document.querySelector('[data-select-toggle]');
    const menu = anchor ? anchor.querySelector('.tf-select-menu') : null;
    const search = anchor ? anchor.querySelector('[data-select-search]') : null;
    const optionNodes = anchor ? Array.from(anchor.querySelectorAll('.tf-select-option')) : [];
    if (!anchor || !toggle || !menu) return;

    const setOpen = function(isOpen) {
      anchor.classList.toggle('open', isOpen);
      menu.setAttribute('aria-hidden', isOpen ? 'false' : 'true');
      if (isOpen && search) search.focus();
    };

    toggle.addEventListener('click', function(event){
      event.stopPropagation();
      setOpen(!anchor.classList.contains('open'));
    });

    document.addEventListener('click', function(event){
      if (!anchor.contains(event.target)) {
        setOpen(false);
      }
    });

    if (search) {
      search.addEventListener('input', function(){
        const term = search.value.trim().toLowerCase();
        let visibleCount = 0;
        optionNodes.forEach(function(node){
          const show = node.textContent.toLowerCase().indexOf(term) !== -1;
          node.style.display = show ? 'block' : 'none';
          if (show) visibleCount += 1;
        });
        let empty = anchor.querySelector('.tf-select-empty');
        if (!empty && visibleCount === 0) {
          empty = document.createElement('div');
          empty.className = 'tf-select-empty';
          empty.textContent = 'SORRY! NO RESULTS FOUND';
          menu.querySelector('[data-select-options]').appendChild(empty);
        }
        if (empty) {
          empty.style.display = visibleCount === 0 ? 'block' : 'none';
        }
      });
    }
  })();
</script>
</body>
</html>

