<?php
/**
 * قوالب خلاصة النتائج — إدارة result_summary_templates
 */
use App\Core\Auth;
use App\Core\Tenant;

if (!($auth instanceof Auth) || !$auth->can('tests.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول';
    return;
}

$tenantId = Tenant::id();
$action = $_GET['action'] ?? 'index';

$tenantAnd = '';
$tenantParams = [$tenantId];
try {
    $db->query('SELECT tenant_id FROM result_summary_templates LIMIT 1');
    $tenantAnd = ' AND tenant_id = ?';
} catch (Throwable $e) {
    $tenantAnd = '';
    $tenantParams = [];
}

// إنشاء الجدول إن لم يكن موجوداً
try {
    $db->query('SELECT id FROM result_summary_templates LIMIT 1');
} catch (Throwable $e) {
    try {
        $db->exec("CREATE TABLE result_summary_templates (
            id INT AUTO_INCREMENT PRIMARY KEY,
            tenant_id INT NULL,
            title VARCHAR(100) NOT NULL,
            template_text TEXT NOT NULL,
            category VARCHAR(50) NULL,
            sort_order INT NOT NULL DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_tenant (tenant_id)
        )");
    } catch (Throwable $e2) {}
}

// حفظ (إضافة/تعديل)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $auth->can('tests.update')) {
    $title = trim($_POST['title'] ?? '');
    $templateText = trim($_POST['template_text'] ?? '');
    $category = trim($_POST['category'] ?? '') ?: null;
    $editId = (int)($_POST['id'] ?? 0);

    if ($title !== '' && $templateText !== '') {
        try {
            if ($editId > 0) {
                $stmt = $db->prepare('UPDATE result_summary_templates SET title = ?, template_text = ?, category = ? WHERE id = ?' . ($tenantAnd ? ' AND tenant_id = ?' : ''));
                $params = [$title, $templateText, $category, $editId];
                if ($tenantAnd) $params[] = $tenantId;
                $stmt->execute($params);
                $_SESSION['result_templates_msg'] = 'تم تحديث القالب.';
            } else {
                $stmt = $db->prepare('INSERT INTO result_summary_templates (tenant_id, title, template_text, category, sort_order) VALUES (?, ?, ?, ?, 0)');
                $stmt->execute([$tenantId, $title, $templateText, $category]);
                $_SESSION['result_templates_msg'] = 'تم إضافة القالب.';
            }
        } catch (Throwable $e) {
            $_SESSION['result_templates_error'] = 'حدث خطأ أثناء الحفظ.';
        }
    } else {
        $_SESSION['result_templates_error'] = 'العنوان والنص مطلوبان.';
    }
    header('Location: index.php?page=result_templates');
    exit;
}

// حذف
if ($action === 'delete' && isset($_GET['id']) && $auth->can('tests.update')) {
    $delId = (int)$_GET['id'];
    if ($delId > 0) {
        try {
            $stmt = $db->prepare('DELETE FROM result_summary_templates WHERE id = ?' . $tenantAnd);
            $stmt->execute(array_merge([$delId], $tenantParams));
            $_SESSION['result_templates_msg'] = 'تم حذف القالب.';
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=result_templates');
    exit;
}

// جلب القوالب
$templates = [];
try {
    $sql = 'SELECT * FROM result_summary_templates WHERE 1=1' . $tenantAnd . ' ORDER BY category ASC, sort_order ASC, title ASC';
    $stmt = $db->prepare($sql);
    $stmt->execute($tenantParams);
    $templates = $stmt->fetchAll();
} catch (Throwable $e) {}

$editing = null;
if ($action === 'edit' && isset($_GET['id'])) {
    $editId = (int)$_GET['id'];
    foreach ($templates as $t) {
        if ((int)$t['id'] === $editId) {
            $editing = $t;
            break;
        }
    }
}
?>
<div class="page-header">
    <h1>قوالب خلاصة النتائج</h1>
    <a href="index.php?page=results" class="btn-secondary">← النتائج</a>
</div>

<?php if (!empty($_SESSION['result_templates_msg'])): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['result_templates_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['result_templates_msg']); ?></div>
<?php endif; ?>
<?php if (!empty($_SESSION['result_templates_error'])): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['result_templates_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['result_templates_error']); ?></div>
<?php endif; ?>

<div class="section-card">
    <h3><?php echo $editing ? 'تعديل القالب' : 'إضافة قالب جديد'; ?></h3>
    <form method="post" class="form-grid">
        <?php if ($editing): ?>
        <input type="hidden" name="id" value="<?php echo (int)$editing['id']; ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>عنوان القالب</label>
            <input type="text" name="title" required placeholder="مثال: طبيعي، يحتاج متابعة" value="<?php echo htmlspecialchars($editing['title'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div class="form-group">
            <label>التصنيف (اختياري)</label>
            <input type="text" name="category" placeholder="مثال: عام، كيمياء" value="<?php echo htmlspecialchars($editing['category'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <div class="form-group full-width">
            <label>نص القالب</label>
            <textarea name="template_text" rows="3" required placeholder="النص الذي سيُدرج في ملاحظات النتيجة"><?php echo htmlspecialchars($editing['template_text'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
        </div>
        <div class="form-actions full-width">
            <button type="submit" class="btn-primary"><?php echo $editing ? 'حفظ التعديلات' : 'إضافة'; ?></button>
            <?php if ($editing): ?>
            <a href="index.php?page=result_templates" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
        </div>
    </form>
</div>

<div class="section-card">
    <h3>القوالب الحالية</h3>
    <?php if (empty($templates)): ?>
    <p style="color:var(--text-muted);">لا توجد قوالب. أضف قوالباً لتظهر كاختيارات سريعة عند إدخال النتائج.</p>
    <?php else: ?>
    <table class="data-table">
        <thead>
            <tr>
                <th>العنوان</th>
                <th>التصنيف</th>
                <th>معاينة النص</th>
                <th>إجراءات</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($templates as $t): ?>
            <tr>
                <td><?php echo htmlspecialchars($t['title'], ENT_QUOTES, 'UTF-8'); ?></td>
                <td><?php echo htmlspecialchars($t['category'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                <td style="max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php echo htmlspecialchars($t['template_text'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars(mb_substr($t['template_text'], 0, 60) . (mb_strlen($t['template_text']) > 60 ? '...' : ''), ENT_QUOTES, 'UTF-8'); ?></td>
                <td>
                    <?php if ($auth->can('tests.update')): ?>
                    <a href="index.php?page=result_templates&action=edit&id=<?php echo (int)$t['id']; ?>" class="btn-link">تعديل</a>
                    <a href="index.php?page=result_templates&action=delete&id=<?php echo (int)$t['id']; ?>" class="btn-link" onclick="return confirm('حذف هذا القالب؟');">حذف</a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>
