<?php
require_once __DIR__.'/../../config/app.php';
require_once __DIR__.'/../../app/Models/DocumentTemplate.php';
require_once __DIR__.'/../../app/Models/ActivityLog.php';

$user = requireAuth(['admin']);

// ── معالجة الإجراءات (POST) ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $act = $_POST['action'] ?? '';

    if ($act === 'create' || $act === 'update') {
        $data = [
            'name_ar' => trim($_POST['name_ar'] ?? ''),
            'name_en' => trim($_POST['name_en'] ?? ''),
            'name_fr' => trim($_POST['name_fr'] ?? ''),
            'icon'    => trim($_POST['icon'] ?? '📄'),
            'scope'   => in_array($_POST['scope'] ?? '', ['vehicle','driver'], true) ? $_POST['scope'] : 'vehicle',
            'requires_expiry' => isset($_POST['requires_expiry']) ? 1 : 0,
            'is_active'       => isset($_POST['is_active']) ? 1 : 0,
            'sort_order'      => (int)($_POST['sort_order'] ?? 0),
        ];

        if ($act === 'create') {
            $code = strtolower(trim($_POST['code'] ?? ''));
            if (!preg_match('/^[a-z][a-z0-9_]{1,49}$/', $code)) {
                flash('dash', t('invalid_code'), 'danger');
                redirect(BASE_URL.'/admin/templates.php');
            }
            if (DocumentTemplate::findByCode($code)) {
                flash('dash', t('code_exists'), 'danger');
                redirect(BASE_URL.'/admin/templates.php');
            }
            if (!$data['name_ar'] || !$data['name_en'] || !$data['name_fr']) {
                flash('dash', t('fill_all_fields'), 'danger');
                redirect(BASE_URL.'/admin/templates.php');
            }
            $data['code'] = $code;
            $data['created_by'] = $user['id'];
            $id = DocumentTemplate::create($data);
            ActivityLog::record($user['id'], 'create_template', 'document_template', $id, $code);
            flash('dash', t('template_saved'));
        } else {
            $id = (int)($_POST['id'] ?? 0);
            if ($id && DocumentTemplate::find($id)) {
                DocumentTemplate::update($id, $data);
                ActivityLog::record($user['id'], 'update_template', 'document_template', $id);
                flash('dash', t('template_saved'));
            }
        }
        redirect(BASE_URL.'/admin/templates.php');
    }

    if ($act === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) { DocumentTemplate::toggle($id); ActivityLog::record($user['id'],'toggle_template','document_template',$id); }
        redirect(BASE_URL.'/admin/templates.php');
    }

    if ($act === 'delete') {
        $id  = (int)($_POST['id'] ?? 0);
        $tpl = $id ? DocumentTemplate::find($id) : null;
        if ($tpl) {
            if (DocumentTemplate::usageCount($tpl['code']) > 0) {
                flash('dash', t('template_in_use'), 'danger');
            } else {
                DocumentTemplate::delete($id);
                ActivityLog::record($user['id'],'delete_template','document_template',$id,$tpl['code']);
                flash('dash', t('template_deleted'));
            }
        }
        redirect(BASE_URL.'/admin/templates.php');
    }
}

$templates = DocumentTemplate::all();
$editId  = (int)($_GET['edit'] ?? 0);
$editTpl = $editId ? DocumentTemplate::find($editId) : null;

$pageTitle  = t('doc_templates');
$activePage = BASE_URL.'/admin/templates.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>

<div class="page-header" style="display:flex;justify-content:space-between;align-items:center">
  <div><h2>🧩 <?= t('doc_templates') ?></h2></div>
  <button class="btn btn-primary" onclick="document.getElementById('tplForm').style.display='block';document.getElementById('tplForm').scrollIntoView()">
    ➕ <?= t('add_template') ?>
  </button>
</div>

<!-- جدول القوالب -->
<div class="card">
  <div style="overflow-x:auto">
    <table class="table" style="width:100%;border-collapse:collapse">
      <thead>
        <tr style="text-align:start;border-bottom:1px solid var(--border)">
          <th style="padding:12px"><?= t('icon') ?></th>
          <th style="padding:12px">code</th>
          <th style="padding:12px"><?= t('name_ar') ?></th>
          <th style="padding:12px"><?= t('scope') ?></th>
          <th style="padding:12px"><?= t('expiry_date') ?></th>
          <th style="padding:12px"><?= t('status') ?></th>
          <th style="padding:12px"><?= t('usage') ?></th>
          <th style="padding:12px"><?= t('actions') ?></th>
        </tr>
      </thead>
      <tbody>
      <?php if(empty($templates)): ?>
        <tr><td colspan="8" style="padding:24px;text-align:center;color:var(--text-muted)"><?= t('no_data') ?></td></tr>
      <?php else: foreach($templates as $tpl):
        $used = DocumentTemplate::usageCount($tpl['code']); ?>
        <tr style="border-bottom:1px solid var(--border)">
          <td style="padding:12px;font-size:20px"><?= e($tpl['icon']) ?></td>
          <td style="padding:12px"><code><?= e($tpl['code']) ?></code></td>
          <td style="padding:12px"><?= e($tpl['name_ar']) ?></td>
          <td style="padding:12px"><?= $tpl['scope']==='vehicle'?t('scope_vehicle'):t('scope_driver') ?></td>
          <td style="padding:12px"><?= $tpl['requires_expiry']?'✓':'—' ?></td>
          <td style="padding:12px">
            <span class="badge <?= $tpl['is_active']?'badge-success':'badge-info' ?>">
              <?= $tpl['is_active']?t('active'):t('inactive') ?>
            </span>
          </td>
          <td style="padding:12px"><?= $used ?></td>
          <td style="padding:12px;white-space:nowrap">
            <a href="?edit=<?= (int)$tpl['id'] ?>" class="btn btn-sm btn-secondary">✏️</a>
            <form method="POST" style="display:inline">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="toggle">
              <input type="hidden" name="id" value="<?= (int)$tpl['id'] ?>">
              <button class="btn btn-sm btn-secondary" title="<?= t('toggle') ?>"><?= $tpl['is_active']?'🔕':'🔔' ?></button>
            </form>
            <?php if($used === 0): ?>
            <form method="POST" style="display:inline" onsubmit="return confirm('<?= e(t('confirm')) ?>?')">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= (int)$tpl['id'] ?>">
              <button class="btn btn-sm btn-danger">🗑️</button>
            </form>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- نموذج إضافة/تعديل قالب -->
<div class="card" id="tplForm" style="margin-top:20px;<?= $editTpl?'':'display:none' ?>">
  <div class="card-header">
    <span class="card-title"><?= $editTpl ? t('edit_template') : t('new_template') ?></span>
  </div>
  <div class="card-body">
    <form method="POST">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="<?= $editTpl?'update':'create' ?>">
      <?php if($editTpl): ?><input type="hidden" name="id" value="<?= (int)$editTpl['id'] ?>"><?php endif; ?>

      <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
        <div class="form-group">
          <label class="form-label"><?= t('template_code') ?></label>
          <input type="text" name="code" class="form-control"
                 value="<?= e($editTpl['code'] ?? '') ?>"
                 <?= $editTpl?'disabled':'required' ?> placeholder="pollution_cert">
          <div style="font-size:12px;color:var(--text-muted);margin-top:4px"><?= t('template_code_hint') ?></div>
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('icon') ?></label>
          <input type="text" name="icon" class="form-control" maxlength="8"
                 value="<?= e($editTpl['icon'] ?? '📄') ?>" placeholder="📄">
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('name_ar') ?></label>
          <input type="text" name="name_ar" class="form-control" required value="<?= e($editTpl['name_ar'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('name_en') ?></label>
          <input type="text" name="name_en" class="form-control" required value="<?= e($editTpl['name_en'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('name_fr') ?></label>
          <input type="text" name="name_fr" class="form-control" required value="<?= e($editTpl['name_fr'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('scope') ?></label>
          <select name="scope" class="form-control">
            <option value="vehicle" <?= (($editTpl['scope']??'')==='vehicle')?'selected':'' ?>><?= t('scope_vehicle') ?></option>
            <option value="driver"  <?= (($editTpl['scope']??'')==='driver')?'selected':'' ?>><?= t('scope_driver') ?></option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label"><?= t('sort_order') ?></label>
          <input type="number" name="sort_order" class="form-control" value="<?= (int)($editTpl['sort_order'] ?? 0) ?>">
        </div>
      </div>

      <div style="display:flex;gap:20px;margin:8px 0 16px">
        <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
          <input type="checkbox" name="requires_expiry" <?= (!$editTpl || $editTpl['requires_expiry'])?'checked':'' ?>>
          <?= t('requires_expiry') ?>
        </label>
        <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
          <input type="checkbox" name="is_active" <?= (!$editTpl || $editTpl['is_active'])?'checked':'' ?>>
          <?= t('active') ?>
        </label>
      </div>

      <div style="display:flex;gap:10px">
        <button type="submit" class="btn btn-primary">💾 <?= t('save') ?></button>
        <a href="<?= BASE_URL ?>/admin/templates.php" class="btn btn-secondary"><?= t('cancel') ?></a>
      </div>
    </form>
  </div>
</div>

<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
