<?php
declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
require_once __DIR__ . '/../../db.php';
require_once __DIR__ . '/../../inc/layout.php';
if (empty($_SESSION['user_id'])) { header('Location: ../../index.html?e=1'); exit; }
$pdo = db(); if (!$pdo instanceof PDO) { http_response_code(500); exit('DB not ready'); }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
$id = (int)($_GET['id'] ?? 0); if ($id <= 0) exit('القالب غير موجود');
$types = $pdo->query("SELECT id, contract_name FROM contract_types ORDER BY contract_name ASC")->fetchAll();
$st = $pdo->prepare("SELECT * FROM contract_templates WHERE id=? LIMIT 1"); $st->execute([$id]); $row = $st->fetch(); if (!$row) exit('القالب غير موجود');
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim((string)($_POST['template_name'] ?? ''));
    $code = trim((string)($_POST['template_code'] ?? ''));
    $typeId = (int)($_POST['contract_type_id'] ?? 0);
    $body = trim((string)($_POST['body_html'] ?? ''));
    $active = isset($_POST['is_active']) ? 1 : 0;
    if ($name === '') $errors[] = 'يرجى كتابة اسم القالب.';
    if ($body === '') $errors[] = 'يرجى كتابة محتوى القالب.';
    if (!$errors) {
        $up = $pdo->prepare("UPDATE contract_templates SET template_name=?, template_code=?, contract_type_id=?, body_html=?, is_active=? WHERE id=?");
        $up->execute([$name, $code, $typeId > 0 ? $typeId : null, $body, $active, $id]);
        header('Location: index.php'); exit;
    }
    $row = array_merge($row, $_POST, ['is_active' => $active]);
}
render_layout_start('تعديل القالب');
?>
<style>
:root{--d:#00424f;--t:#006a7a;--line:#dce8eb;--shadow:0 18px 42px rgba(0,66,79,.08)}
.tc-wrap{direction:rtl;font-family:'Tajawal',sans-serif;padding:24px;max-width:1100px;margin:0 auto}.card{background:#fff;border:1px solid var(--line);border-radius:24px;box-shadow:var(--shadow);overflow:hidden}.head{padding:18px 20px;border-bottom:1px solid #e8eff2}.body{padding:22px}.grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.field{display:flex;flex-direction:column;gap:8px}.input,.select,.textarea{width:100%;min-height:50px;border:1px solid var(--line);border-radius:15px;padding:12px 14px;font-size:14px}.textarea{min-height:340px;resize:vertical;line-height:1.9}.btns{display:flex;gap:10px;flex-wrap:wrap;margin-top:18px}.btn{border:none;border-radius:15px;padding:12px 18px;text-decoration:none;font-size:14px;font-weight:800;cursor:pointer}.btn1{background:linear-gradient(135deg,var(--d),var(--t));color:#fff}.btn2{background:#fff;border:1px solid var(--line);color:var(--d)}.err{background:#fff4f4;border:1px solid #f1c7c7;color:#c62828;padding:14px 16px;border-radius:16px;margin-bottom:16px}
@media(max-width:900px){.tc-wrap{padding:16px}.grid{grid-template-columns:1fr}}
</style>
<div class="tc-wrap"><div class="card"><div class="head"><h1 style="margin:0;color:var(--d);font-size:24px">تعديل القالب #<?= (int)$id ?></h1></div><div class="body">
<?php if ($errors): ?><div class="err"><ul style="margin:0;padding-right:18px"><?php foreach ($errors as $e): ?><li><?= h($e) ?></li><?php endforeach; ?></ul></div><?php endif; ?>
<form method="post">
  <div class="grid">
    <div class="field"><label>اسم القالب</label><input class="input" type="text" name="template_name" value="<?= h($row['template_name'] ?? '') ?>"></div>
    <div class="field"><label>كود القالب</label><input class="input" type="text" name="template_code" value="<?= h($row['template_code'] ?? '') ?>"></div>
    <div class="field"><label>نوع العقد</label><select class="select" name="contract_type_id"><option value="">اختياري</option><?php foreach ($types as $t): ?><option value="<?= (int)$t['id'] ?>" <?= ((int)($row['contract_type_id'] ?? 0)===(int)$t['id'])?'selected':'' ?>><?= h($t['contract_name']) ?></option><?php endforeach; ?></select></div>
    <div class="field" style="justify-content:end"><label><input type="checkbox" name="is_active" value="1" <?= (int)($row['is_active'] ?? 0)===1?'checked':'' ?>> قالب مفعل</label></div>
    <div class="field" style="grid-column:1/-1"><label>محتوى القالب HTML</label><textarea class="textarea" name="body_html"><?= h($row['body_html'] ?? '') ?></textarea></div>
  </div>
  <div class="btns"><button class="btn btn1" type="submit">حفظ التعديلات</button><a class="btn btn2" href="index.php">رجوع</a></div>
</form>
</div></div></div>
<?php render_layout_end(); ?>
