<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db   = Database::getInstance();
$page = 'Letter Templates';
$cid  = companyId();

// The 7 built-in types still have a hardcoded fallback in letter.php, so
// a company doesn't HAVE to create a template for these to use them —
// they only need to if they want to change the wording. Custom types
// (anything else) only work once a template is created here.
$builtIn = [
    'offer'        => 'Offer Letter',
    'appointment'  => 'Appointment Letter',
    'confirmation' => 'Confirmation Letter',
    'increment'    => 'Increment Letter',
    'experience'   => 'Experience Letter',
    'salary_cert'  => 'Salary Certificate',
    'noc'          => 'NOC Letter',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');

    if ($action === 'delete') {
        $id = postInt('id');
        $db->execute("DELETE FROM letter_templates WHERE id=? AND company_id=?", [$id, $cid]);
        setFlash('success', 'Template deleted. It will fall back to the built-in wording (if this was one of the 7 standard types) or stop showing (if custom).');
        header('Location: letter_templates.php'); exit;
    }

    // save (create or edit)
    $typeKey = strtolower(trim(preg_replace('/[^a-zA-Z0-9_]/', '_', post('type_key'))));
    $title   = trim(post('title'));
    $body    = post('body_html');
    if (!$typeKey || !$title || !$body) {
        setFlash('error', 'Type key, title and body are all required.');
        header('Location: letter_templates.php'); exit;
    }

    $id = postInt('id');
    if ($id) {
        // Confirm ownership before editing
        $owned = $db->fetchOne("SELECT id FROM letter_templates WHERE id=? AND company_id=?", [$id, $cid]);
        if (!$owned) { setFlash('error', 'Template not found.'); header('Location: letter_templates.php'); exit; }
        $db->execute("UPDATE letter_templates SET type_key=?,title=?,body_html=?,is_active=? WHERE id=?",
            [$typeKey, $title, $body, postInt('is_active'), $id]);
        setFlash('success', 'Template updated.');
    } else {
        try {
            $db->execute("INSERT INTO letter_templates (company_id,type_key,title,body_html,is_active) VALUES (?,?,?,?,?)",
                [$cid, $typeKey, $title, $body, 1]);
            setFlash('success', 'Template created.');
        } catch (Throwable $e) {
            setFlash('error', "A template with type key '$typeKey' already exists. Edit it instead, or use a different key.");
        }
    }
    header('Location: letter_templates.php'); exit;
}

$editId   = cleanInt($_GET['edit'] ?? 0);
$edit     = $editId ? $db->fetchOne("SELECT * FROM letter_templates WHERE id=? AND company_id=?", [$editId, $cid]) : null;
$prefill  = $_GET['new'] ?? null; // e.g. ?new=offer to start from a built-in type's key
$templates = $db->fetchAll("SELECT * FROM letter_templates WHERE company_id=? ORDER BY title", [$cid]);
$existingKeys = array_column($templates, 'type_key');
$keyToId = array_combine(array_column($templates, 'type_key'), array_column($templates, 'id'));

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-file-pencil me-2"></i><?= $edit ? 'Edit' : 'New' ?> Letter Template</div>
      <form method="POST">
        <?= csrfField() ?><input type="hidden" name="action" value="save">
        <?php if ($edit): ?><input type="hidden" name="id" value="<?= $edit['id'] ?>"><?php endif; ?>

        <div class="mb-2">
          <label class="pc-label">Type Key <span class="text-muted">(unique code, no spaces)</span></label>
          <input type="text" name="type_key" class="form-control form-control-sm" placeholder="e.g. offer, bonus_letter"
                 value="<?= clean($edit['type_key'] ?? $prefill ?? '') ?>" <?= $edit ? 'readonly' : '' ?> required>
        </div>
        <div class="mb-2">
          <label class="pc-label">Display Title</label>
          <input type="text" name="title" class="form-control form-control-sm" placeholder="e.g. Offer Letter"
                 value="<?= clean($edit['title'] ?? ($builtIn[$prefill] ?? '')) ?>" required>
        </div>
        <div class="mb-2">
          <label class="pc-label">Letter Body <span class="text-muted">(HTML + placeholders)</span></label>
          <textarea name="body_html" class="form-control form-control-sm" rows="14" style="font-family:monospace;font-size:12px" required><?= clean($edit['body_html'] ?? "<p>Dear {{employee_name}},</p>\n<p>...</p>") ?></textarea>
        </div>
        <div class="mb-3 form-check">
          <input type="checkbox" name="is_active" value="1" class="form-check-input" id="ltActive" <?= ($edit['is_active'] ?? 1) ? 'checked' : '' ?>>
          <label class="form-check-label small" for="ltActive">Active</label>
        </div>
        <div class="d-flex gap-2">
          <button class="btn btn-pc btn-sm flex-fill">Save Template</button>
          <?php if ($edit): ?><a href="?" class="btn btn-outline-secondary btn-sm">Cancel</a><?php endif; ?>
        </div>
      </form>
    </div>

    <div class="pc-card mt-3">
      <div class="pc-card-title"><i class="ti ti-tags me-2"></i>Available Placeholders</div>
      <p class="text-muted small mb-2">Paste these anywhere in the body — they'll be replaced with the real employee data when the letter is generated.</p>
      <div class="d-flex flex-wrap gap-1">
        <?php foreach (['employee_name','employee_code','designation','department','location','manager','doj','date','company_name','company_logo','company_address','gross_monthly','ctc_annual','gross_monthly_words','address'] as $tok): ?>
          <code class="small bg-light px-1 rounded"><?= "{{" . $tok . "}}" ?></code>
        <?php endforeach; ?>
      </div>
      <p class="text-muted small mt-2 mb-0"><i class="ti ti-info-circle me-1"></i>Your logo and company name are already printed above the letter body automatically on every letter — you only need <code>{{company_logo}}</code> / <code>{{company_name}}</code> if you want to place them again somewhere inside the body itself. Set the logo under <a href="<?= BASE_URL ?>/modules/company/branding.php">Company Branding &amp; Logo</a>.</p>
    </div>
  </div>

  <div class="col-md-7">
    <div class="pc-card mb-3">
      <div class="pc-card-title">Your Custom Templates</div>
      <table class="pc-table">
        <thead><tr><th>Type Key</th><th>Title</th><th>Status</th><th></th></tr></thead>
        <tbody>
        <?php foreach ($templates as $t): ?>
        <tr>
          <td><code><?= clean($t['type_key']) ?></code></td>
          <td><?= clean($t['title']) ?></td>
          <td><?= statusBadge($t['is_active'] ? 'active' : 'inactive') ?></td>
          <td class="text-nowrap">
            <a href="?edit=<?= $t['id'] ?>" class="btn btn-xs btn-outline-primary py-0 px-1">Edit</a>
            <a href="<?= BASE_URL ?>/modules/reports/letter.php?type=<?= urlencode($t['type_key']) ?>" class="btn btn-xs btn-outline-secondary py-0 px-1">Preview</a>
            <form method="POST" class="d-inline" onsubmit="return confirm('Delete this template?')">
              <?= csrfField() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $t['id'] ?>">
              <button class="btn btn-xs btn-outline-danger py-0 px-1">Del</button>
            </form>
          </td>
        </tr>
        <?php endforeach; if (!$templates): ?><tr><td colspan="4" class="text-center text-muted">No custom templates yet.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>

    <div class="pc-card">
      <div class="pc-card-title">Standard Letter Types</div>
      <p class="text-muted small mb-2">These work out of the box with built-in wording. Click "Customize" to override the wording for your company.</p>
      <table class="pc-table">
        <thead><tr><th>Type</th><th>Status</th><th></th></tr></thead>
        <tbody>
        <?php foreach ($builtIn as $key => $label): $has = in_array($key, $existingKeys); ?>
        <tr>
          <td><?= clean($label) ?> <code class="small text-muted"><?= $key ?></code></td>
          <td><?= $has ? '<span class="badge bg-primary">Customized</span>' : '<span class="badge bg-secondary">Built-in wording</span>' ?></td>
          <td><a href="<?= $has ? '?edit=' . $keyToId[$key] : '?new=' . $key ?>" class="btn btn-xs btn-outline-primary py-0 px-1"><?= $has ? 'Edit' : 'Customize' ?></a></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>