<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin']);
require_once DENTAL_ROOT . '/app/sms_service.php';
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string)($_POST['action'] ?? '');
        if ($action === 'save_sms_settings') {
            $provider = (string)($_POST['provider'] ?? 'log');
            if (!array_key_exists($provider, dental_sms_provider_options())) $provider = 'log';
            $senderName = trim((string)($_POST['sender_name'] ?? 'DentalCare')) ?: 'DentalCare';
            $country = trim((string)($_POST['default_country_code'] ?? '+63')) ?: '+63';
            if (!preg_match('/^\+[1-9]\d{0,3}$/', $country)) throw new RuntimeException('Default country code must be in international format, for example +63.');
            setting_set('sms','enabled',isset($_POST['enabled']) ? '1' : '0');
            setting_set('sms','automatic_enabled',isset($_POST['automatic_enabled']) ? '1' : '0');
            setting_set('sms','provider',$provider);
            setting_set('sms','sender_name',substr($senderName, 0, 40));
            setting_set('sms','default_country_code',$country);
            setting_set('sms','queue_batch_size',(string)max(1,min(50,(int)($_POST['queue_batch_size'] ?? 10))));
            setting_set('sms','semaphore_api_key',(string)($_POST['semaphore_api_key'] ?? ''), true);
            setting_set('sms','twilio_sid',trim((string)($_POST['twilio_sid'] ?? '')), true);
            setting_set('sms','twilio_token',(string)($_POST['twilio_token'] ?? ''), true);
            setting_set('sms','twilio_from',trim((string)($_POST['twilio_from'] ?? '')), true);
            setting_set('sms','android_gateway_url',trim((string)($_POST['android_gateway_url'] ?? '')), true);
            setting_set('sms','android_gateway_api_key',(string)($_POST['android_gateway_api_key'] ?? ''), true);
            setting_set('sms','android_gateway_device_id',trim((string)($_POST['android_gateway_device_id'] ?? '')), true);
            $androidHeader = trim((string)($_POST['android_gateway_header_name'] ?? 'x-api-key')) ?: 'x-api-key';
            setting_set('sms','android_gateway_header_name',preg_replace('/[^A-Za-z0-9_-]/','',$androidHeader) ?: 'x-api-key');
            setting_set('sms','generic_url',trim((string)($_POST['generic_url'] ?? '')), true);
            setting_set('sms','generic_method',strtoupper((string)($_POST['generic_method'] ?? 'POST')) === 'GET' ? 'GET' : 'POST');
            setting_set('sms','generic_auth_header',trim((string)($_POST['generic_auth_header'] ?? '')), true);
            audit('sms_settings_updated','settings',null,['provider'=>$provider,'enabled'=>isset($_POST['enabled'])]);
            flash('success','SMS readiness settings saved. Send a test message before enabling live client notifications.');
            header('Location: sms_settings.php'); exit;
        }
        if ($action === 'save_template') {
            if (!dental_sms_schema_ready()) throw new RuntimeException('Apply the SMS readiness update before editing SMS templates.');
            $id = (int)($_POST['id'] ?? 0);
            $body = trim((string)($_POST['body_template'] ?? ''));
            if ($id < 1) throw new RuntimeException('Select an SMS template.');
            if ($body === '') throw new RuntimeException('SMS template body is required.');
            if (mb_strlen($body) > 480) throw new RuntimeException('SMS template body must be 480 characters or less.');
            $pdo->prepare('UPDATE `' . table('sms_templates') . '` SET body_template=?,is_active=?,updated_by=?,updated_at=NOW() WHERE id=?')
                ->execute([$body, isset($_POST['is_active']) ? 1 : 0, (int)(current_user()['id'] ?? 0) ?: null, $id]);
            audit('sms_template_updated','sms_template',$id,[]);
            flash('success','SMS template saved.');
            header('Location: sms_settings.php?template_id=' . $id); exit;
        }
        if ($action === 'restore_template') {
            if (!dental_sms_schema_ready()) throw new RuntimeException('Apply the SMS readiness update before restoring SMS templates.');
            $id = (int)($_POST['id'] ?? 0);
            $stmt = $pdo->prepare('SELECT template_key FROM `' . table('sms_templates') . '` WHERE id=? LIMIT 1');
            $stmt->execute([$id]);
            $key = (string)($stmt->fetchColumn() ?: '');
            $fallback = dental_sms_template_fallbacks()[$key] ?? null;
            if (!$fallback) throw new RuntimeException('Packaged SMS fallback is not available for this template.');
            $pdo->prepare('UPDATE `' . table('sms_templates') . '` SET body_template=?,is_active=1,updated_by=?,updated_at=NOW() WHERE id=?')
                ->execute([(string)$fallback['body'], (int)(current_user()['id'] ?? 0) ?: null, $id]);
            audit('sms_template_restored','sms_template',$id,['template_key'=>$key]);
            flash('success','Packaged SMS template restored.');
            header('Location: sms_settings.php?template_id=' . $id); exit;
        }
        if ($action === 'send_test_sms') {
            $recipient = trim((string)($_POST['test_number'] ?? ''));
            $templateKey = (string)($_POST['template_key'] ?? 'appointment_reminder');
            $sample = [
                'recipient_name'=>'Sample Patient',
                'reference'=>'APT-SAMPLE',
                'service_name'=>'Dental Examination',
                'appointment_datetime'=>date('M j, Y g:i A', strtotime('+2 days 10:00')),
                'provider_name'=>'Dr. Demo Santos',
                'branch_name'=>(string)(public_clinic_profile()['name'] ?? 'Demo Dental Clinic'),
                'lead_time'=>'24 hours',
                'due_date'=>date('M j, Y', strtotime('+7 days')),
                'purpose'=>'Post-treatment review',
                'recall_type'=>'oral prophylaxis',
                'amount'=>'PHP 1,500.00',
                'receipt_number'=>'OR-SAMPLE-001',
                'payment_date'=>date('M j, Y'),
                'message'=>'This is a DentalCare SMS readiness test.',
            ];
            $delivery = dental_sms_queue_template($templateKey, $recipient, $sample, ['type'=>'sms_settings_test'], true);
            $status = (string)($delivery['status'] ?? 'pending');
            flash($status === 'sent' ? 'success' : 'warning', 'SMS test result: ' . strtoupper($status) . (!empty($delivery['message']) ? ' — ' . (string)$delivery['message'] : (!empty($delivery['error']) ? ' — ' . (string)$delivery['error'] : '')));
            header('Location: sms_settings.php'); exit;
        }
        if ($action === 'process_sms_queue') {
            $result = dental_sms_process_queue($pdo, max(1,min(50,(int)($_POST['queue_limit'] ?? 10))), 'manual_settings');
            flash(empty($result['failed']) ? 'success' : 'warning', 'SMS queue processed: ' . (int)$result['sent'] . ' sent/logged, ' . (int)$result['held'] . ' held, ' . (int)$result['failed'] . ' failed.');
            header('Location: sms_settings.php'); exit;
        }
        if ($action === 'retry_sms') {
            if (!dental_sms_schema_ready()) throw new RuntimeException('SMS outbox is not available.');
            $id = (int)($_POST['sms_id'] ?? 0);
            if ($id < 1) throw new RuntimeException('Select an SMS outbox record.');
            $pdo->prepare('UPDATE `' . table('sms_outbox') . '` SET status=\'pending\',available_at=NOW(),last_error=NULL,updated_at=NOW() WHERE id=? AND status IN (\'failed\',\'held\',\'retry\',\'pending\')')->execute([$id]);
            $one = dental_sms_process_one($id);
            flash((string)($one['status'] ?? '') === 'sent' ? 'success' : 'warning', 'SMS retry result: ' . strtoupper((string)($one['status'] ?? 'unknown')) . (!empty($one['error']) ? ' — ' . (string)$one['error'] : ''));
            header('Location: sms_settings.php'); exit;
        }
        throw new RuntimeException('Unsupported SMS action.');
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
        header('Location: sms_settings.php'); exit;
    }
}

$settings = dental_sms_settings();
$health = dental_sms_health($pdo);
$schemaReady = dental_sms_schema_ready();
$templates = [];
$selectedTemplate = null;
$templateId = (int)($_GET['template_id'] ?? 0);
$queue = ['pending'=>0,'sent'=>0,'failed'=>0,'held'=>0,'retry'=>0];
$recent = [];
if ($schemaReady) {
    try {
        $templates = $pdo->query('SELECT * FROM `' . table('sms_templates') . '` ORDER BY category,name')->fetchAll(PDO::FETCH_ASSOC);
        if ($templateId < 1 && $templates) $templateId = (int)$templates[0]['id'];
        foreach ($templates as $row) if ((int)$row['id'] === $templateId) { $selectedTemplate = $row; break; }
        if (!$selectedTemplate && $templates) $selectedTemplate = $templates[0];
        $rows = $pdo->query('SELECT status,COUNT(*) total FROM `' . table('sms_outbox') . '` GROUP BY status')->fetchAll(PDO::FETCH_KEY_PAIR);
        foreach ($queue as $key => $_) $queue[$key] = (int)($rows[$key] ?? 0);
        $recent = $pdo->query('SELECT id,recipient_number,body,status,provider,attempts,last_error,provider_reference,sent_at,updated_at,created_at FROM `' . table('sms_outbox') . '` ORDER BY created_at DESC LIMIT 25')->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $exception) {
        flash('error', 'SMS dashboard could not read all records: ' . $exception->getMessage());
    }
}

render_header('SMS Readiness');
?>
<section class="role-welcome card">
    <div>
        <span class="eyebrow">Communication readiness</span>
        <h2>SMS Readiness Center</h2>
        <p>Configure SMS provider credentials, test delivery, review SMS templates, and keep messages in log/held mode until the client supplies a live SMS provider account.</p>
        <div class="status-actions"><a class="btn ghost" href="email_settings.php">Email &amp; SMTP</a><a class="btn ghost" href="email_templates.php">Email Templates</a></div>
    </div>
    <div class="setup-progress-ring"><strong><?= e(strtoupper((string)$settings['provider'])) ?></strong><span><?= !empty($settings['enabled']) ? 'SMS enabled' : 'SMS disabled / setup mode' ?></span></div>
</section>

<?php if (!$schemaReady): ?>
<div class="alert warning"><strong>SMS update is pending.</strong> Open System Setup → Updates &amp; Database and apply Version 0.5.9.8.68 before sending or queueing SMS.</div>
<?php endif; ?>
<?php if (function_exists('app_orientation_mode_active') && app_orientation_mode_active()): ?>
<div class="alert warning"><strong>Orientation Mode is active.</strong> Live SMS delivery is paused. Test messages will be held/logged for safety.</div>
<?php endif; ?>

<section class="stats mini-stats">
    <?php stat_card('Provider', dental_sms_provider_options()[(string)$settings['provider']] ?? (string)$settings['provider'], !empty($settings['enabled']) ? 'Enabled' : 'Disabled'); ?>
    <?php stat_card('Pending', $queue['pending'] ?? 0, 'Ready to process'); ?>
    <?php stat_card('Held', $queue['held'] ?? 0, 'Disabled/orientation'); ?>
    <?php stat_card('Sent/logged', $queue['sent'] ?? 0, 'Accepted or logged'); ?>
    <?php stat_card('Failed', $queue['failed'] ?? 0, 'Needs review'); ?>
</section>

<div class="setup-grid sms-admin-grid">
<section class="card">
    <div class="card-head"><div><h2>Provider setup</h2><p>Use log-only mode for demos, Android gateway for phone/SIM testing, then switch to Semaphore, Twilio, or a generic gateway when live credentials are available.</p></div></div>
    <form method="post" class="form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="save_sms_settings">
        <label class="choice wide"><input type="checkbox" name="enabled" value="1" <?= !empty($settings['enabled']) ? 'checked' : '' ?>><span><strong>Enable SMS sending</strong><small>Leave disabled until provider credentials are tested. Disabled mode holds new SMS messages.</small></span></label>
        <label>Provider<select name="provider"><?php foreach (dental_sms_provider_options() as $code => $label): ?><option value="<?= e($code) ?>" <?= $settings['provider'] === $code ? 'selected' : '' ?>><?= e($label) ?></option><?php endforeach; ?></select></label>
        <label>Sender name<input name="sender_name" maxlength="40" value="<?= e((string)$settings['sender_name']) ?>"><small>Some carriers limit sender IDs to 11 characters.</small></label>
        <label>Default country code<input name="default_country_code" value="<?= e((string)$settings['default_country_code']) ?>" placeholder="+63"></label>
        <label>Queue batch size<input type="number" min="1" max="50" name="queue_batch_size" value="<?= e((string)$settings['queue_batch_size']) ?>"></label>
        <label class="choice wide"><input type="checkbox" name="automatic_enabled" value="1" <?= !empty($settings['automatic_enabled']) ? 'checked' : '' ?>><span><strong>Allow future automatic SMS queue processing</strong><small>Queue automation is readiness-only until a live provider is validated.</small></span></label>
        <h3 class="wide">Semaphore PH</h3>
        <label class="wide">API key<input type="password" name="semaphore_api_key" value="<?= e((string)$settings['semaphore_api_key']) ?>" autocomplete="new-password"></label>
        <h3 class="wide">Twilio</h3>
        <label>Account SID<input name="twilio_sid" value="<?= e((string)$settings['twilio_sid']) ?>"></label>
        <label>From number<input name="twilio_from" value="<?= e((string)$settings['twilio_from']) ?>" placeholder="+1234567890"></label>
        <label class="wide">Auth token<input type="password" name="twilio_token" value="<?= e((string)$settings['twilio_token']) ?>" autocomplete="new-password"></label>
        <h3 class="wide">Android phone/SIM gateway (TextBee compatible)</h3>
        <label class="wide">Gateway endpoint URL<input name="android_gateway_url" value="<?= e((string)$settings['android_gateway_url']) ?>" placeholder="https://gateway.example/api/send-sms"><small>Use this for a spare Android phone/SIM gateway. Keep the phone online and test before live use.</small></label>
        <label class="wide">API key / token<input type="password" name="android_gateway_api_key" value="<?= e((string)$settings['android_gateway_api_key']) ?>" autocomplete="new-password"></label>
        <label>Device ID<input name="android_gateway_device_id" value="<?= e((string)$settings['android_gateway_device_id']) ?>" placeholder="optional"></label>
        <label>API-key header<input name="android_gateway_header_name" value="<?= e((string)$settings['android_gateway_header_name']) ?>" placeholder="x-api-key"></label>
        <div class="wide alert info"><strong>Android gateway note:</strong> This mode posts a JSON payload with <code>to</code>, <code>number</code>, <code>recipients</code>, <code>message</code>, and optional <code>device_id</code>. If the selected Android gateway needs a different format, use Generic HTTP provider or adjust the endpoint adapter.</div>
        <h3 class="wide">Generic HTTP provider</h3>
        <label class="wide">Endpoint URL<input name="generic_url" value="<?= e((string)$settings['generic_url']) ?>" placeholder="https://sms-provider.example/send"></label>
        <label>Method<select name="generic_method"><option value="POST" <?= $settings['generic_method'] === 'POST' ? 'selected' : '' ?>>POST</option><option value="GET" <?= $settings['generic_method'] === 'GET' ? 'selected' : '' ?>>GET</option></select></label>
        <label>Optional auth header<input name="generic_auth_header" value="<?= e((string)$settings['generic_auth_header']) ?>" placeholder="Authorization: Bearer ..."></label>
        <div class="wide"><button class="btn primary">Save SMS Settings</button></div>
    </form>
</section>

<section class="card">
    <div class="card-head"><div><h2>Health and test send</h2><p>Send a controlled test before enabling live patient notifications.</p></div></div>
    <?php if (!empty($health['issues'])): ?><div class="alert warning"><strong>Review needed:</strong><ul><?php foreach ($health['issues'] as $issue): ?><li><?= e((string)$issue) ?></li><?php endforeach; ?></ul></div><?php else: ?><div class="alert success"><strong>SMS setup has no blocking issue.</strong> Continue with a test send.</div><?php endif; ?>
    <form method="post" class="form-grid compact-form">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="send_test_sms">
        <label class="wide">Test mobile number<input name="test_number" placeholder="0917 000 0000 or +639170000000" required></label>
        <label class="wide">Template<select name="template_key"><?php foreach (dental_sms_template_fallbacks() as $key => $row): ?><option value="<?= e($key) ?>"><?= e((string)$row['name']) ?></option><?php endforeach; ?></select></label>
        <div class="wide"><button class="btn primary" <?= $schemaReady ? '' : 'disabled' ?>>Queue and Send Test SMS</button></div>
    </form>
    <form method="post" class="inline-form">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="process_sms_queue"><input type="hidden" name="queue_limit" value="<?= e((string)$settings['queue_batch_size']) ?>">
        <button class="btn ghost" <?= $schemaReady ? '' : 'disabled' ?>>Process SMS Queue</button>
    </form>
</section>
</div>

<?php if ($schemaReady): ?>
<div class="template-manager-layout sms-template-layout">
    <aside class="card template-list"><h2>SMS Templates</h2><?php $category=''; foreach ($templates as $template): if ($category !== (string)$template['category']): $category=(string)$template['category']; ?><h3><?= e($category) ?></h3><?php endif; ?><a class="<?= $selectedTemplate && (int)$selectedTemplate['id'] === (int)$template['id'] ? 'active' : '' ?>" href="sms_settings.php?template_id=<?= (int)$template['id'] ?>"><strong><?= e((string)$template['name']) ?></strong><small><?= e((string)$template['template_key']) ?> · <?= !empty($template['is_active']) ? 'Active' : 'Disabled' ?></small></a><?php endforeach; ?></aside>
    <?php if ($selectedTemplate): $variables = json_decode((string)($selectedTemplate['allowed_variables_json'] ?? '[]'), true); if (!is_array($variables)) $variables=[]; ?>
    <section class="card template-editor">
        <div class="card-head"><div><span class="eyebrow"><?= e((string)$selectedTemplate['category']) ?></span><h2><?= e((string)$selectedTemplate['name']) ?></h2><p><code><?= e((string)$selectedTemplate['template_key']) ?></code></p></div><span class="badge"><?= !empty($selectedTemplate['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_template"><input type="hidden" name="id" value="<?= (int)$selectedTemplate['id'] ?>">
            <label class="wide">SMS body<textarea name="body_template" rows="6" maxlength="480" required><?= e((string)$selectedTemplate['body_template']) ?></textarea><small>Keep SMS short. Recommended: 160 characters or less; maximum allowed here is 480 characters.</small></label>
            <label class="choice wide"><input type="checkbox" name="is_active" value="1" <?= !empty($selectedTemplate['is_active']) ? 'checked' : '' ?>><span><strong>Use this SMS 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 SMS 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></section>
        <?php if (isset(dental_sms_template_fallbacks()[(string)$selectedTemplate['template_key']])): ?><form method="post"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="restore_template"><input type="hidden" name="id" value="<?= (int)$selectedTemplate['id'] ?>"><button class="btn ghost" data-confirm="Restore the packaged SMS template?">Restore Packaged Template</button></form><?php endif; ?>
    </section>
    <?php endif; ?>
</div>

<section class="card table-wrap"><div class="card-head"><div><h2>Recent SMS outbox</h2><p>Newest SMS readiness records and provider responses.</p></div></div><table><thead><tr><th>ID</th><th>Recipient</th><th>Message</th><th>Status</th><th>Provider</th><th>Attempts</th><th>Last update</th><th></th></tr></thead><tbody><?php foreach ($recent as $row): ?><tr><td>#<?= (int)$row['id'] ?></td><td><?= e((string)$row['recipient_number']) ?></td><td><small><?= e(mb_strimwidth((string)$row['body'],0,90,'…')) ?></small><?php if (!empty($row['last_error'])): ?><small class="text-danger"><?= e((string)$row['last_error']) ?></small><?php endif; ?><?php if (!empty($row['provider_reference'])): ?><small>Ref: <?= e((string)$row['provider_reference']) ?></small><?php endif; ?></td><td><span class="badge"><?= e((string)$row['status']) ?></span></td><td><?= e((string)$row['provider']) ?></td><td><?= (int)$row['attempts'] ?></td><td><?= e((string)($row['updated_at'] ?? $row['created_at'])) ?></td><td><?php if (in_array((string)$row['status'], ['failed','held','retry','pending'], true)): ?><form method="post"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="retry_sms"><input type="hidden" name="sms_id" value="<?= (int)$row['id'] ?>"><button class="link-btn">Retry</button></form><?php endif; ?></td></tr><?php endforeach; ?><?php if (!$recent): ?><tr><td colspan="8" class="muted">No SMS messages have been queued yet.</td></tr><?php endif; ?></tbody></table></section>
<?php endif; ?>

<?php render_footer();
