<?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);

if (!function_exists('h')) {
    function h($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

$rows = [];
$errorMsg = '';

try {
    $sql = "
        SELECT
            t.id,
            t.template_name,
            t.template_code,
            t.contract_type_id,
            t.is_active,
            t.created_at,
            ct.contract_name
        FROM contract_templates t
        LEFT JOIN contract_types ct ON ct.id = t.contract_type_id
        ORDER BY t.id DESC
    ";

    $st = $pdo->query($sql);
    $rows = $st->fetchAll();
} catch (Throwable $e) {
    $errorMsg = 'تعذر تحميل قوالب العقود. تأكد من وجود جدول contract_templates و contract_types بشكل صحيح.';
}

render_layout_start('قوالب العقود');
?>

<style>
:root{
    --d:#00424f;
    --t:#006a7a;
    --line:#dce8eb;
    --shadow:0 18px 42px rgba(0,66,79,.08);
    --bg:#f4f8fa;
    --card:#ffffff;
    --text:#17323a;
    --muted:#6d7d82;
    --ok-bg:#eaf8f0;
    --ok-text:#157347;
    --off-bg:#fff1f1;
    --off-text:#c62828;
    --head-bg:#fbfdfe;
}

.ti-wrap{
    direction:rtl;
    font-family:'Tajawal',sans-serif;
    padding:24px;
    max-width:1200px;
    margin:0 auto;
    color:var(--text);
}

.hero{
    background:linear-gradient(135deg,var(--d),var(--t));
    color:#fff;
    border-radius:28px;
    padding:24px;
    box-shadow:var(--shadow);
    margin-bottom:18px;
}

.hero h1{
    margin:0 0 8px;
    font-size:30px;
    font-weight:800;
}

.hero p{
    margin:0;
    line-height:1.9;
    font-size:15px;
}

.actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-top:14px;
}

.btn{
    border:none;
    border-radius:15px;
    padding:12px 18px;
    text-decoration:none;
    font-size:14px;
    font-weight:800;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    transition:.18s ease;
}

.btn:hover{
    transform:translateY(-1px);
}

.btn1{
    background:#fff;
    color:var(--d);
}

.btn2{
    background:rgba(255,255,255,.1);
    color:#fff;
    border:1px solid rgba(255,255,255,.14);
}

.card{
    background:var(--card);
    border:1px solid var(--line);
    border-radius:24px;
    box-shadow:var(--shadow);
    overflow:hidden;
}

.head{
    padding:18px 20px;
    border-bottom:1px solid #e8eff2;
    background:linear-gradient(to left, #ffffff, #f8fbfc);
}

.head h2{
    margin:0;
    color:var(--d);
    font-size:22px;
    font-weight:800;
}

.body{
    padding:18px;
}

.alert{
    border-radius:16px;
    padding:14px 16px;
    margin-bottom:16px;
    font-size:14px;
    line-height:1.8;
}

.alert-error{
    background:#fff4f4;
    color:#b42318;
    border:1px solid #f3c7c7;
}

.empty-box{
    padding:28px 18px;
    text-align:center;
    color:var(--muted);
    border:1px dashed #d9e5e8;
    border-radius:18px;
    background:#fcfeff;
}

.tbl-wrap{
    width:100%;
    overflow-x:auto;
}

.tbl{
    width:100%;
    border-collapse:collapse;
    min-width:780px;
}

.tbl th,
.tbl td{
    padding:14px 12px;
    border-bottom:1px solid #edf2f4;
    text-align:right;
    vertical-align:middle;
}

.tbl th{
    color:var(--d);
    background:var(--head-bg);
    font-size:14px;
    font-weight:800;
}

.tbl td{
    font-size:14px;
    color:var(--text);
}

.code-badge{
    display:inline-block;
    padding:7px 10px;
    border-radius:12px;
    background:#f3f7f9;
    color:#32525b;
    font-size:12px;
    direction:ltr;
    unicode-bidi:embed;
}

.status-badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 12px;
    border-radius:999px;
    font-weight:800;
    font-size:12px;
    white-space:nowrap;
}

.status-active{
    background:var(--ok-bg);
    color:var(--ok-text);
}

.status-inactive{
    background:var(--off-bg);
    color:var(--off-text);
}

.row-actions{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}

.action-link{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:72px;
    padding:8px 12px;
    border-radius:12px;
    text-decoration:none;
    font-size:13px;
    font-weight:800;
    transition:.18s ease;
}

.action-edit{
    background:#eef7fb;
    color:#00556b;
}

.action-edit:hover{
    background:#dff1f7;
}

.action-preview{
    background:#f5f7fa;
    color:#334e68;
}

.action-preview:hover{
    background:#ebeff5;
}

.muted{
    color:var(--muted);
}

@media (max-width: 768px){
    .ti-wrap{
        padding:16px;
    }

    .hero{
        padding:20px;
        border-radius:22px;
    }

    .hero h1{
        font-size:24px;
    }

    .head h2{
        font-size:19px;
    }

    .body{
        padding:14px;
    }
}
</style>

<div class="ti-wrap">
    <div class="hero">
        <h1>قوالب العقود</h1>
        <p>أدر قوالب التوليد الذكي للعقود باستخدام المتغيرات مثل {client_name} و {amount} و {start_date}.</p>

        <div class="actions">
            <a class="btn btn1" href="create.php">إضافة قالب جديد</a>
            <a class="btn btn2" href="../index.php">رجوع للعقود</a>
        </div>
    </div>

    <div class="card">
        <div class="head">
            <h2>القوالب</h2>
        </div>

        <div class="body">
            <?php if ($errorMsg !== ''): ?>
                <div class="alert alert-error"><?= h($errorMsg) ?></div>
            <?php endif; ?>

            <?php if (!$errorMsg && !$rows): ?>
                <div class="empty-box">
                    لا توجد قوالب عقود بعد. ابدأ الآن بإضافة أول قالب جديد.
                </div>
            <?php elseif (!$errorMsg): ?>
                <div class="tbl-wrap">
                    <table class="tbl">
                        <thead>
                            <tr>
                                <th style="width:70px;">#</th>
                                <th>اسم القالب</th>
                                <th style="width:160px;">الكود</th>
                                <th style="width:180px;">النوع</th>
                                <th style="width:140px;">الحالة</th>
                                <th style="width:170px;">إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($rows as $r): ?>
                                <?php
                                    $isActive = ((int)($r['is_active'] ?? 0) === 1);
                                    $typeName = trim((string)($r['contract_name'] ?? ''));
                                ?>
                                <tr>
                                    <td><?= (int)($r['id'] ?? 0) ?></td>

                                    <td>
                                        <?= h($r['template_name'] ?? '') ?>
                                    </td>

                                    <td>
                                        <?php if (trim((string)($r['template_code'] ?? '')) !== ''): ?>
                                            <span class="code-badge"><?= h($r['template_code']) ?></span>
                                        <?php else: ?>
                                            <span class="muted">—</span>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <?= $typeName !== '' ? h($typeName) : '<span class="muted">—</span>' ?>
                                    </td>

                                    <td>
                                        <span class="status-badge <?= $isActive ? 'status-active' : 'status-inactive' ?>">
                                            <?= $isActive ? 'مفعل' : 'غير مفعل' ?>
                                        </span>
                                    </td>

                                    <td>
                                        <div class="row-actions">
                                            <a class="action-link action-edit" href="edit.php?id=<?= (int)($r['id'] ?? 0) ?>">
                                                تعديل
                                            </a>

                                            <a class="action-link action-preview" href="../generator/fill_data.php?template_id=<?= (int)($r['id'] ?? 0) ?>">
                                                استخدام
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php render_layout_end(); ?>