<?php
require_once __DIR__ . "/../../config/config.php";
require_once __DIR__ . "/../../includes/functions.php";
startSession(); requireLogin();
$db = Database::getInstance();
$page = "Letter Generation";
$cid  = companyId();

$type      = $_GET["type"] ?? "offer";
$selEmp    = cleanInt($_GET["emp"] ?? 0);
// FIX (07 Jul 2026): letters include salary details — scope the dropdown
// to the current org and reject ?emp=<other org's employee>.
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
if ($selEmp && !in_array($selEmp, array_column($employees, 'id'))) { $selEmp = 0; }
$emp       = $selEmp ? $db->fetchOne("SELECT e.*,d.name AS dept,des.name AS designation,l.name AS location,CONCAT(m.first_name,' ',m.last_name) AS manager FROM employees e LEFT JOIN departments d ON d.id=e.department_id LEFT JOIN designations des ON des.id=e.designation_id LEFT JOIN locations l ON l.id=e.location_id LEFT JOIN employees m ON m.id=e.reporting_manager_id WHERE e.id=?",[$selEmp]) : null;
$salary    = $selEmp ? $db->fetchOne("SELECT * FROM employee_salary WHERE employee_id=?",[$selEmp]) : null;
$company   = $db->fetchOne("SELECT * FROM company_settings LIMIT 1");

// ── Letter types: 7 built-in + any custom ones this company created ──
$builtInTitles = ["offer"=>"Offer Letter","appointment"=>"Appointment Letter","confirmation"=>"Confirmation Letter","increment"=>"Increment Letter","experience"=>"Experience Letter","salary_cert"=>"Salary Certificate","noc"=>"NOC Letter"];
$customTemplates = $db->fetchAll("SELECT type_key,title FROM letter_templates WHERE company_id=? AND is_active=1 ORDER BY title", [$cid]);
$letterTypes = $builtInTitles;
foreach ($customTemplates as $ct) { $letterTypes[$ct['type_key']] = $ct['title']; } // also overrides built-in titles if customized

// The template this company saved for the currently-viewed type, if any
$activeTemplate = $db->fetchOne("SELECT * FROM letter_templates WHERE company_id=? AND type_key=? AND is_active=1", [$cid, $type]);

include __DIR__ . "/../../includes/header.php";
?>
<div class="row g-3">
  <div class="col-md-3">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-file-invoice me-2"></i>Letter Options</div>
      <?php foreach($letterTypes as $t=>$l): ?>
      <a href="?type=<?=$t?>&emp=<?=$selEmp?>" class="d-block p-2 rounded mb-1 <?=$type===$t?"fw-bold":""?>" style="font-size:12.5px;color:<?=$type===$t?"var(--pc-brand)":"var(--pc-text)"?>;background:<?=$type===$t?"var(--pc-brand-light)":"transparent"?>">
        <i class="ti ti-file-text me-2"></i><?=clean($l)?>
      </a>
      <?php endforeach; ?>
      <hr>
      <div><label class="pc-label">Employee</label>
        <select class="form-select form-select-sm" onchange="location='?type=<?=$type?>&emp='+this.value">
          <option value="">Select</option>
          <?php foreach($employees as $e): ?><option value="<?=$e["id"]?>" <?=$selEmp==$e["id"]?"selected":""?>><?=clean($e["label"])?></option><?php endforeach; ?>
        </select></div>
      <hr>
      <a href="<?= BASE_URL ?>/modules/reports/letter_templates.php?<?= $activeTemplate ? 'edit='.$activeTemplate['id'] : 'new='.$type ?>" class="btn btn-outline-secondary btn-sm w-100">
        <i class="ti ti-pencil me-1"></i><?= $activeTemplate ? 'Edit This Template' : 'Customize This Letter' ?>
      </a>
    </div>
  </div>
  <div class="col-md-9">
    <?php if($emp):
      $date     = date("d F Y");
      $empName  = clean($emp["first_name"].' '.$emp["last_name"]);
      $coName   = clean($company["company_name"] ?? "Company Name");
      $titles   = $letterTypes;
      $grossVal = $salary["gross_monthly"] ?? 0;

      // Values every template (built-in or custom) can use via {{token}}
      $vars = [
          'employee_name'        => $empName,
          'employee_code'        => clean($emp["employee_id"] ?? ''),
          'designation'          => clean($emp["designation"] ?? ''),
          'department'           => clean($emp["dept"] ?? ''),
          'location'             => clean($emp["location"] ?? ''),
          'manager'              => clean($emp["manager"] ?? 'your Manager'),
          'doj'                  => fmtDate($emp["date_of_joining"] ?? null),
          'date'                 => $date,
          'company_name'         => $coName,
          'company_address'      => clean($company["address"] ?? ''),
          'company_logo'         => ($company["logo_path"] ?? '') ? '<img src="' . BASE_URL . '/uploads/' . clean($company["logo_path"]) . '" alt="' . $coName . '" style="max-height:60px;max-width:200px;object-fit:contain">' : '',
          'gross_monthly'        => number_format($grossVal, 2),
          'ctc_annual'           => number_format($salary["ctc_annual"] ?? 0, 2),
          'gross_monthly_words'  => numToWords(intval($grossVal)),
          'address'              => clean($emp["residential_address"] ?? '') . (($emp["residential_city"] ?? '') ? ', ' . clean($emp["residential_city"]) : ''),
          'employment_type'      => ucfirst($emp["employment_type"] ?? ''),
      ];
    ?>
    <div class="pc-card mb-2">
      <div class="d-flex gap-2">
        <button onclick="window.print()" class="btn btn-pc btn-sm"><i class="ti ti-printer me-1"></i>Print Letter</button>
        <span class="text-muted small align-self-center">Letter for: <strong><?=$empName?></strong></span>
      </div>
    </div>
    <div class="pc-card" id="letterBody">
      <!-- Header: logo left, company details right -->
      <div class="d-flex justify-content-between align-items-center lh-header">
        <div>
          <?php if ($company["logo_path"] ?? ""): ?>
            <img src="<?= BASE_URL ?>/uploads/<?= clean($company["logo_path"]) ?>" alt="<?= $coName ?>" style="max-height:64px;max-width:180px;object-fit:contain">
          <?php endif; ?>
        </div>
        <div class="text-end">
          <div class="lh-company-name"><?=$coName?></div>
          <?php if($company["address"]??""): ?><div class="lh-company-address"><?=clean($company["address"]??"")?></div><?php endif; ?>
        </div>
      </div>

      <!-- Letter title -->
      <div class="lh-title"><?=clean($titles[$type] ?? ucfirst($type))?></div>

      <div class="d-flex justify-content-between lh-date-row"><span></span><span>Date: <?=$date?></span></div>
      <div class="lh-to-block">
        <strong>To,</strong><br>
        <?=$empName?><br>
        <?=clean($emp["residential_address"]??"")?><?=($emp["residential_city"]??"")?", ".clean($emp["residential_city"]):"" ?>
      </div>
      <div class="lh-subject">Subject: <?=clean($titles[$type] ?? ucfirst($type))?></div>

      <div class="lh-body">
      <?php if ($activeTemplate): ?>
        <?= fillLetterTemplate($activeTemplate['body_html'], $vars) ?>

      <?php elseif($type==="offer"): ?>
      <p>Dear <?=$empName?>,</p>
      <p>We are pleased to offer you the position of <strong><?=clean($emp["designation"]??"")?></strong> in our <strong><?=clean($emp["dept"]??"")?></strong> department at <?=$coName?>. Your employment will commence from <strong><?=fmtDate($emp["date_of_joining"])?></strong>.</p>
      <p>You will be reporting to <?=clean($emp["manager"]??"your Manager")?> at our <?=clean($emp["location"]??"")?> office. Your employment will be on a <strong><?=ucfirst($emp["employment_type"])?></strong> basis.</p>
      <?php if($salary): ?><p>Your gross monthly compensation will be <strong>₹<?=number_format($salary["gross_monthly"],2)?></strong> (Rupees <?=clean($salary["gross_monthly"])?> only) and annual CTC will be <strong>₹<?=number_format($salary["ctc_annual"],2)?></strong>.</p><?php endif; ?>
      <p>This offer is subject to successful completion of background verification and submission of all required documents.</p>

      <?php elseif($type==="experience"): ?>
      <p>To Whom It May Concern,</p>
      <p>This is to certify that <strong><?=$empName?></strong> (Employee Code: <?=clean($emp["employee_id"])?>), has been working with <?=$coName?> as <strong><?=clean($emp["designation"]??"")?></strong> in the <strong><?=clean($emp["dept"]??"")?></strong> department since <strong><?=fmtDate($emp["date_of_joining"])?></strong>.</p>
      <p>During their tenure, they have demonstrated excellent professional conduct and contributed significantly to the organisation.</p>
      <p>We wish them all the best in their future endeavours.</p>

      <?php elseif($type==="salary_cert"): ?>
      <p>To Whom It May Concern,</p>
      <p>This is to certify that <strong><?=$empName?></strong> (Employee Code: <?=clean($emp["employee_id"])?>), is currently employed with <?=$coName?> as <strong><?=clean($emp["designation"]??"")?></strong>.</p>
      <?php if($salary): ?><p>Their current Gross Monthly Salary is <strong>₹<?=number_format($salary["gross_monthly"],2)?></strong> (Rupees <?=numToWords(intval($salary["gross_monthly"]))?> Only).</p><?php endif; ?>
      <p>This certificate is issued at the request of the employee for their personal use.</p>

      <?php elseif(isset($builtInTitles[$type])): ?>
      <p>Dear <?=$empName?>,</p>
      <p>With reference to your employment with <?=$coName?> as <strong><?=clean($emp["designation"]??"")?></strong> in the <strong><?=clean($emp["dept"]??"")?></strong> department since <?=fmtDate($emp["date_of_joining"])?>, this letter serves as your <strong><?=clean($titles[$type] ?? '')?></strong>.</p>
      <p>We acknowledge your continued contributions and commitment to the organisation.</p>

      <?php else: ?>
      <p class="text-muted">No template has been created for this letter type yet. <a href="<?= BASE_URL ?>/modules/reports/letter_templates.php?new=<?= urlencode($type) ?>">Create one</a>.</p>
      <?php endif; ?>
      </div>

      <p class="lh-closing">Yours sincerely,</p>
      <div class="lh-signature">
        <div class="lh-signature-name"><?=$coName?></div>
        <div class="lh-signature-role">HR Department</div>
      </div>
    </div>
    <?php else: ?>
    <div class="pc-card"><div class="text-muted text-center py-4">Select an employee to generate a letter.</div></div>
    <?php endif; ?>
  </div>
</div>
<style>
  #letterBody {
    font-family: Cambria, Georgia, 'Times New Roman', serif;
    font-size: 14.5px;
    line-height: 1.9;
    color: #232323;
    padding: 46px 56px;
  }
  #letterBody .lh-header { margin-bottom: 22px; padding-bottom: 18px; border-bottom: 2px solid var(--pc-brand); }
  #letterBody .lh-company-name { font-size: 21px; font-weight: 700; color: var(--pc-brand); letter-spacing: .3px; }
  #letterBody .lh-company-address { font-size: 12.5px; color: #6b7280; margin-top: 2px; }
  #letterBody .lh-title { text-align: center; font-size: 15.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 2px; color: #232323; margin-bottom: 30px; }
  #letterBody .lh-date-row { font-size: 13.5px; margin-bottom: 22px; }
  #letterBody .lh-to-block { margin-bottom: 22px; }
  #letterBody .lh-subject { font-weight: 700; margin-bottom: 26px; padding-bottom: 8px; border-bottom: 1px solid #d8dce2; }
  #letterBody .lh-body p { text-align: justify; margin-bottom: 16px; }
  #letterBody .lh-closing { margin-top: 34px; margin-bottom: 0; }
  #letterBody .lh-signature { margin-top: 56px; }
  #letterBody .lh-signature-name { font-weight: 700; font-size: 15px; }
  #letterBody .lh-signature-role { font-size: 12.5px; color: #6b7280; margin-top: 2px; }

  @media print {
    .pc-topbar,.pc-sidebar,.col-md-3,.btn,.pc-tabs,.pc-card:not(#letterBody) { display:none !important; }
    #letterBody { box-shadow:none !important; border:none !important; padding: 10mm 14mm; }
    @page { margin: 14mm 16mm; }
  }
</style>
<?php include __DIR__ . "/../../includes/footer.php"; ?>