<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/tax_forms_module.php';
require_once 'includes/settings_helpers.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'];

$values = tax_details_get($conn, $orgId);
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values = [
        'pan' => strtoupper(trim((string) ($_POST['pan'] ?? ''))),
        'tan' => strtoupper(trim((string) ($_POST['tan'] ?? ''))),
        'tds_circle' => strtoupper(trim((string) ($_POST['tds_circle'] ?? ''))),
        'tds_ao_code' => strtoupper(trim((string) ($_POST['tds_ao_code'] ?? ''))),
        'tds_ao_number' => trim((string) ($_POST['tds_ao_number'] ?? '')),
        'tds_ao_type' => trim((string) ($_POST['tds_ao_type'] ?? '')),
        'tax_payment_frequency' => trim((string) ($_POST['tax_payment_frequency'] ?? 'Monthly')),
        'deductor_type' => trim((string) ($_POST['deductor_type'] ?? 'employee')),
        'deductor_name' => trim((string) ($_POST['deductor_name'] ?? '')),
        'deductor_father_name' => trim((string) ($_POST['deductor_father_name'] ?? '')),
    ];

    if ($values['pan'] !== '' && !preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]$/', $values['pan'])) {
        $errors[] = 'PAN format should be AAAAA0000A.';
    }
    if ($values['tan'] !== '' && !preg_match('/^[A-Z]{4}[0-9]{5}[A-Z]$/', $values['tan'])) {
        $errors[] = 'TAN format should be AAAA00000A.';
    }
    if ($values['deductor_name'] === '') {
        $errors[] = 'Select or enter a tax deductor name.';
    }

    if (!$errors) {
        if (tax_details_save($conn, $orgId, $values)) {
            $_SESSION['tax_flash_ok'] = 'Tax details saved successfully.';
            header('Location: form16.php?deductor=' . urlencode($values['deductor_name']));
            exit();
        }
        $errors[] = 'Unable to save tax details right now.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Taxes | Settings | Payroll</title>
  <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="tf-settings-page">
  <header class="tf-settings-top">
    <div class="tf-settings-brand">
      <div class="tf-settings-brand-icon"><i class="fa-regular fa-file-lines"></i></div>
      <div>
        <h1>All Settings</h1>
        <p><?php echo htmlspecialchars($orgName); ?></p>
      </div>
    </div>
    <div class="tf-settings-search">
      <i class="fa-solid fa-magnifying-glass"></i>
      <input type="text" placeholder="Search settings ( / )">
    </div>
    <a class="tf-settings-close" href="dashboard.php">Close Settings <span>&times;</span></a>
  </header>

  <div class="tf-settings-layout">
    <aside class="tf-settings-sidebar">
      <div class="tf-sidebar-heading">Organisation Settings</div>
      <nav class="tf-side-nav">
        <a class="tf-side-parent" href="orgprofile.php"><i class="fa-solid fa-chevron-right"></i>Organisation</a>
        <a class="tf-side-parent" href="users.php"><i class="fa-solid fa-chevron-down"></i>Users and Roles</a>
        <a class="tf-side-subnav-link tf-side-link" href="users.php" style="padding-left:42px;">Users</a>
        <a class="tf-side-subnav-link tf-side-link" href="roles.php" style="padding-left:42px;">Roles</a>
        <a class="tf-side-parent active" href="tax_details.php"><i class="fa-solid fa-chevron-down"></i>Taxes</a>
        <a class="tf-side-subnav-link tf-side-link active" href="tax_details.php" style="padding-left:42px;">Tax Details</a>
        <a class="tf-side-parent" href="pay_schedule.php"><i class="fa-solid fa-chevron-down"></i>Setup &amp; Configurations</a>
        <a class="tf-side-subnav-link tf-side-link" href="pay_schedule.php" style="padding-left:42px;">Pay Schedule</a>
        <a class="tf-side-subnav-link tf-side-link" href="statutory_components.php" style="padding-left:42px;">Statutory Components</a>
      </nav>

      <a class="tf-side-parent" href="settings.php"><i class="fa-solid fa-chevron-right"></i>Customisations</a>
      <a class="tf-side-link" href="workflow_rules.php"><i class="fa-solid fa-chevron-right"></i>Automations</a>

      <div class="tf-sidebar-heading">Module Settings</div>
      <nav class="tf-side-nav">
        <a class="tf-side-link" href="employees.php"><i class="fa-solid fa-chevron-right"></i>General</a>
        <a class="tf-side-link" href="payruns.php"><i class="fa-solid fa-chevron-right"></i>Payments</a>
      </nav>

      <div class="tf-sidebar-heading">Extensions &amp; Developer Data</div>
      <nav class="tf-side-nav">
        <a class="tf-side-link" href="settings.php"><i class="fa-solid fa-chevron-right"></i>Integrations</a>
        <a class="tf-side-link" href="settings.php"><i class="fa-solid fa-chevron-right"></i>Developer Data</a>
      </nav>
    </aside>

    <main class="tf-settings-main">
      <div class="tf-settings-panel">
        <h2>Tax Details</h2>

        <?php if ($errors): ?>
          <div class="tf-flash err"><?php echo htmlspecialchars(implode(' ', $errors)); ?></div>
        <?php endif; ?>

        <form method="post">
          <section>
            <h3>Organisation Tax Details</h3>
            <div class="tf-form-grid">
              <div class="tf-field">
                <label for="pan">PAN<span class="tf-required">*</span></label>
                <input class="tf-input" id="pan" name="pan" type="text" maxlength="10" placeholder="AAAAA0000A" value="<?php echo htmlspecialchars($values['pan']); ?>">
                <small>Format: AAAAA0000A</small>
              </div>
              <div class="tf-field">
                <label for="tan">TAN</label>
                <input class="tf-input" id="tan" name="tan" type="text" maxlength="10" placeholder="AAAA00000A" value="<?php echo htmlspecialchars($values['tan']); ?>">
              </div>
              <div class="tf-field">
                <label>TDS circle / AO code</label>
                <div class="tf-code-grid">
                  <input class="tf-input" type="text" name="tds_circle" maxlength="3" placeholder="AAA" value="<?php echo htmlspecialchars($values['tds_circle']); ?>">
                  <span class="tf-code-sep">/</span>
                  <input class="tf-input" type="text" name="tds_ao_code" maxlength="2" placeholder="AA" value="<?php echo htmlspecialchars($values['tds_ao_code']); ?>">
                  <span class="tf-code-sep">/</span>
                  <input class="tf-input" type="text" name="tds_ao_number" maxlength="3" placeholder="000" value="<?php echo htmlspecialchars($values['tds_ao_number']); ?>">
                  <span class="tf-code-sep">/</span>
                  <input class="tf-input" type="text" name="tds_ao_type" maxlength="2" placeholder="00" value="<?php echo htmlspecialchars($values['tds_ao_type']); ?>">
                </div>
              </div>
              <div class="tf-field">
                <label for="tax_payment_frequency">Tax Payment Frequency</label>
                <select class="tf-select" id="tax_payment_frequency" name="tax_payment_frequency">
                  <option value="Monthly" <?php echo $values['tax_payment_frequency'] === 'Monthly' ? 'selected' : ''; ?>>Monthly</option>
                  <option value="Quarterly" <?php echo $values['tax_payment_frequency'] === 'Quarterly' ? 'selected' : ''; ?>>Quarterly</option>
                  <option value="Annually" <?php echo $values['tax_payment_frequency'] === 'Annually' ? 'selected' : ''; ?>>Annually</option>
                </select>
              </div>
            </div>
          </section>

          <section>
            <h3>Tax Deductor Details</h3>
            <div class="tf-form-grid">
              <div class="tf-field">
                <label>Deductor's Type</label>
                <div class="tf-segmented">
                  <label class="tf-radio"><input type="radio" name="deductor_type" value="employee" <?php echo $values['deductor_type'] === 'employee' ? 'checked' : ''; ?>>Employee</label>
                  <label class="tf-radio"><input type="radio" name="deductor_type" value="non-employee" <?php echo $values['deductor_type'] === 'non-employee' ? 'checked' : ''; ?>>Non-Employee</label>
                </div>
              </div>
              <div></div>
              <div class="tf-field">
                <label for="deductor_name">Deductor's Name</label>
                <input class="tf-input" id="deductor_name" name="deductor_name" type="text" placeholder="Select a Tax Deductor" value="<?php echo htmlspecialchars($values['deductor_name']); ?>">
              </div>
              <div class="tf-field">
                <label for="deductor_father_name">Deductor's Father's Name</label>
                <input class="tf-input" id="deductor_father_name" name="deductor_father_name" type="text" value="<?php echo htmlspecialchars($values['deductor_father_name']); ?>">
              </div>
            </div>
          </section>

          <div class="tf-actions">
            <button class="tf-primary-btn" type="submit">Save</button>
          </div>
        </form>

        <div class="tf-footnote"><span class="tf-required">*</span> indicates mandatory fields</div>
      </div>
    </main>
  </div>
</body>
</html>
