<?php

declare(strict_types=1);
require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin']);
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();
if (!email_template_schema_ready()) {
    render_header('Email Templates');
    ?><section class="card"><h2>Update required</h2><p>Apply Version 0.5.8.3 before editing email templates.</p><?php if(actual_role()==='super_admin'):?><a class="btn primary" href="system_setup.php?tab=updates">Open Updates &amp; Database</a><?php endif;?></section><?php
    render_footer();
    return;
}

function template_target(PDO $pdo, int $id): array
{
    $stmt = $pdo->prepare('SELECT * FROM `' . table('email_templates') . '` WHERE id=? LIMIT 1');
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) throw new RuntimeException('Email template not found.');
    return $row;
}

function template_validate_markup(string $html): void
{
    if ($html === '') throw new RuntimeException('HTML message content is required.');
    if (preg_match('/<(script|iframe|object|embed|form)\b/i', $html)) {
        throw new RuntimeException('Scripts, frames, embedded objects, and forms are not allowed in email templates.');
    }
}

$selectedId = (int)($_GET['id'] ?? 0);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string)($_POST['action'] ?? 'save');
        $id = (int)($_POST['id'] ?? 0);
        $target = template_target($pdo, $id);
        if ($action === 'save') {
            $subject = trim((string)($_POST['subject_template'] ?? ''));
            $html = trim((string)($_POST['html_template'] ?? ''));
            $text = trim((string)($_POST['text_template'] ?? ''));
            if ($subject === '' || preg_match('/[\r\n]/', $subject)) throw new RuntimeException('Enter a one-line email subject.');
            template_validate_markup($html);
            $pdo->prepare('UPDATE `' . table('email_templates') . '` SET subject_template=?,html_template=?,text_template=?,is_active=?,updated_by=?,updated_at=NOW() WHERE id=?')
                ->execute([$subject,$html,$text,isset($_POST['is_active'])?1:0,(int)current_user()['id'],$id]);
            audit('email_template_updated','email_template',$id,['template_key'=>$target['template_key'],'active'=>isset($_POST['is_active'])]);
            flash('success','Email template saved.');
        } elseif ($action === 'restore') {
            $fallback = email_template_fallbacks()[(string)$target['template_key']] ?? null;
            if (!$fallback) throw new RuntimeException('A packaged fallback is not available for this template. You can still edit it manually.');
            $pdo->prepare('UPDATE `' . table('email_templates') . '` SET subject_template=?,html_template=?,text_template=?,is_active=1,updated_by=?,updated_at=NOW() WHERE id=?')
                ->execute([$fallback['subject'],$fallback['html'],$fallback['text'],(int)current_user()['id'],$id]);
            audit('email_template_restored','email_template',$id,['template_key'=>$target['template_key']]);
            flash('success','Packaged template restored.');
        } elseif ($action === 'send_test') {
            $recipient = strtolower(trim((string)($_POST['test_recipient'] ?? '')));
            if (!filter_var($recipient,FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Enter a valid test recipient.');
            $sample = [
                'recipient_name'=>'Sample Patient','role_name'=>'Dentist','activation_url'=>app_absolute_url('account-activate.php?token=sample'),
                'expires_hours'=>'72','reference'=>'APT-SAMPLE','service_name'=>'Dental Examination','appointment_datetime'=>date('F j, Y g:i A',strtotime('+2 days 10:00')),
                'provider_name'=>'Dr. Sample','branch_name'=>(string)(public_clinic_profile()['name']??'Dental Clinic'),'calendar_url'=>app_absolute_url('calendar.php?id=sample'),
                'lead_time'=>'24 hours','due_date'=>date('F j, Y',strtotime('+7 days')),'purpose'=>'Post-treatment review','instructions'=>'Please bring your previous prescription.',
                'recall_type'=>'oral prophylaxis','amount'=>'₱1,500.00','receipt_number'=>'OR-SAMPLE-001','payment_date'=>date('F j, Y'),
                'message'=>'This is a DentalCare template test.','booking_url'=>app_absolute_url('appointment-returning.php'),
            ];
            $message = email_template_message((string)$target['template_key'],$sample);
            $delivery = queue_mail_message_with_attempt($recipient,$message['subject'],$message['html'],$message['text'],['type'=>'email_template_test','template_key'=>$target['template_key']]);
            $status = (string)($delivery['status']??'pending');
            if ($status === 'sent') flash('success','The mail server accepted the test message. Check the inbox and spam folder.');
            else flash('warning','The test message is ' . email_delivery_label($status) . '. Review Email & SMTP for the exact error and retry schedule.');
        } else {
            throw new RuntimeException('Unsupported email-template action.');
        }
        header('Location: email_templates.php?id=' . $id);
        exit;
    } catch (Throwable $exception) {
        flash('error',$exception->getMessage());
        header('Location: email_templates.php' . ($selectedId ? '?id=' . $selectedId : ''));
        exit;
    }
}

$templates = $pdo->query('SELECT * FROM `' . table('email_templates') . '` ORDER BY category,name')->fetchAll();
if ($selectedId < 1 && $templates) $selectedId = (int)$templates[0]['id'];
$selected = null;
foreach ($templates as $row) if ((int)$row['id'] === $selectedId) {$selected=$row;break;}
if (!$selected && $templates) $selected=$templates[0];
$variables = $selected ? json_decode((string)($selected['allowed_variables_json']??'[]'),true) : [];
if (!is_array($variables)) $variables=[];

render_header('Email Templates');
?>
<section class="role-welcome card"><div><span class="eyebrow">Communication control</span><h2>Email Template Manager</h2><p>Edit the messages used for account invitations, appointments, reminders, follow-ups, recalls, and receipts. SMTP credentials and delivery diagnostics remain under Email &amp; SMTP.</p></div><a class="btn ghost" href="email_settings.php">Email &amp; SMTP</a></section>
<div class="template-manager-layout">
    <aside class="card template-list"><h2>Templates</h2><?php $category='';foreach($templates as $template):if($category!==$template['category']):$category=(string)$template['category'];?><h3><?=e($category)?></h3><?php endif;?><a class="<?=$selected&&(int)$selected['id']===(int)$template['id']?'active':''?>" href="email_templates.php?id=<?=(int)$template['id']?>"><strong><?=e((string)$template['name'])?></strong><small><?=e((string)$template['template_key'])?> · <?=$template['is_active']?'Active':'Disabled'?></small></a><?php endforeach;?></aside>
    <?php if($selected):?>
    <section class="card template-editor">
        <div class="card-head"><div><span class="eyebrow"><?=e((string)$selected['category'])?></span><h2><?=e((string)$selected['name'])?></h2><p><code><?=e((string)$selected['template_key'])?></code></p></div><span class="badge"><?=$selected['is_active']?'Active':'Disabled'?></span></div>
        <form method="post" class="form-grid">
            <input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?=(int)$selected['id']?>">
            <label class="wide">Subject<input name="subject_template" maxlength="255" value="<?=e((string)$selected['subject_template'])?>" required></label>
            <label class="wide">HTML email<textarea name="html_template" rows="16" required><?=e((string)$selected['html_template'])?></textarea><small>Basic email HTML is allowed. Scripts, forms, frames, and embedded objects are blocked.</small></label>
            <label class="wide">Plain-text alternative<textarea name="text_template" rows="7"><?=e((string)$selected['text_template'])?></textarea></label>
            <label class="choice wide"><input type="checkbox" name="is_active" value="1" <?=$selected['is_active']?'checked':''?>><span><strong>Use this template</strong><small>When disabled, the packaged fallback is used where one exists.</small></span></label>
            <div class="wide inline-actions"><button class="btn primary">Save Template</button></div>
        </form>
        <section class="template-variables"><h3>Available variables</h3><div class="chip-row"><?php foreach($variables as $variable):?><code>{{<?=e((string)$variable)?>}}</code><?php endforeach;?></div><p class="muted">Variables are replaced safely when the message is queued. Keep the double braces.</p></section>
        <div class="template-test-grid">
            <form method="post" class="compact-form"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="send_test"><input type="hidden" name="id" value="<?=(int)$selected['id']?>"><label>Send test to<input type="email" name="test_recipient" value="<?=e((string)(current_user()['email']??''))?>" required></label><button class="btn ghost">Send Test</button></form>
            <?php if(isset(email_template_fallbacks()[(string)$selected['template_key']])):?><form method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="restore"><input type="hidden" name="id" value="<?=(int)$selected['id']?>"><button class="btn ghost" data-confirm="Restore the packaged version of this template?">Restore Packaged Template</button></form><?php endif;?>
        </div>
    </section>
    <?php endif;?>
</div>
<?php render_footer();
