<?php
// /edenrms/pages/settings_sms.php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/sms.php';
require_once __DIR__ . '/../includes/whatsapp_helper.php';

ec_require_login();

if (!(ec_can('settings.manage') || ec_role() === 'super_admin')) {
    header('Location: /edenrms/pages/403.php');
    exit;
}

$ACTIVE = 'settings';
$db = ec_db();

if (!$db instanceof mysqli) {
    die('DB connection failed');
}

$db->set_charset('utf8mb4');

$db->query("CREATE TABLE IF NOT EXISTS app_settings (
    k VARCHAR(64) PRIMARY KEY,
    v LONGTEXT NULL,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$db->query("ALTER TABLE app_settings MODIFY v LONGTEXT NULL");

$db->query("CREATE TABLE IF NOT EXISTS rms_email_templates (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template_key VARCHAR(100) NOT NULL UNIQUE,
    template_name VARCHAR(150) NOT NULL,
    subject VARCHAR(255) NOT NULL,
    body_html MEDIUMTEXT NOT NULL,
    is_enabled TINYINT(1) NOT NULL DEFAULT 1,
    updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$db->query("CREATE TABLE IF NOT EXISTS rms_email_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template_key VARCHAR(100) NULL,
    student_id INT NULL,
    payment_id INT NULL,
    email_to VARCHAR(255) NOT NULL,
    subject VARCHAR(255) NOT NULL,
    status ENUM('sent','failed','skipped') NOT NULL DEFAULT 'sent',
    error_message TEXT NULL,
    sent_at DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX (template_key),
    INDEX (student_id),
    INDEX (payment_id),
    INDEX (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$db->query("CREATE TABLE IF NOT EXISTS whatsapp_templates (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template_key VARCHAR(100) NOT NULL UNIQUE,
    template_name VARCHAR(150) NOT NULL,
    message_body MEDIUMTEXT NOT NULL,
    is_enabled TINYINT(1) NOT NULL DEFAULT 1,
    updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$db->query("CREATE TABLE IF NOT EXISTS whatsapp_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template_key VARCHAR(100) NULL,
    student_id INT NULL,
    payment_id INT NULL,
    phone_to VARCHAR(50) NULL,
    provider VARCHAR(50) NOT NULL DEFAULT 'dev_log',
    message_body MEDIUMTEXT NULL,
    status ENUM('sent','failed','skipped') NOT NULL DEFAULT 'skipped',
    response TEXT NULL,
    sent_at DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX (template_key),
    INDEX (student_id),
    INDEX (payment_id),
    INDEX (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");


function ec_col_exists(mysqli $db, string $table, string $col): bool {
    $st = $db->prepare("
        SELECT COUNT(*) c
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
    ");
    if (!$st) return false;

    $st->bind_param('ss', $table, $col);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();

    return ((int)($row['c'] ?? 0)) > 0;
}

if (!ec_col_exists($db, 'whatsapp_templates', 'template_key')) {
    $db->query("ALTER TABLE whatsapp_templates ADD COLUMN template_key VARCHAR(100) NULL");
}

if (!ec_col_exists($db, 'whatsapp_templates', 'template_name')) {
    $db->query("ALTER TABLE whatsapp_templates ADD COLUMN template_name VARCHAR(150) NULL");
}

if (!ec_col_exists($db, 'whatsapp_templates', 'message_body')) {
    $db->query("ALTER TABLE whatsapp_templates ADD COLUMN message_body MEDIUMTEXT NULL");
}

if (!ec_col_exists($db, 'whatsapp_templates', 'is_enabled')) {
    $db->query("ALTER TABLE whatsapp_templates ADD COLUMN is_enabled TINYINT(1) NOT NULL DEFAULT 1");
}

if (!ec_col_exists($db, 'whatsapp_logs', 'phone_to')) {
    $db->query("ALTER TABLE whatsapp_logs ADD COLUMN phone_to VARCHAR(50) NULL");
}

if (!ec_col_exists($db, 'whatsapp_logs', 'message_body')) {
    $db->query("ALTER TABLE whatsapp_logs ADD COLUMN message_body MEDIUMTEXT NULL");
}


function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function sget(mysqli $db, string $k, string $d = ''): string {
    $st = $db->prepare("SELECT v FROM app_settings WHERE k=? LIMIT 1");
    if (!$st) return $d;

    $st->bind_param('s', $k);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();

    return $row ? (string)$row['v'] : $d;
}

function sset(mysqli $db, string $k, string $v): void {
    $st = $db->prepare("
        INSERT INTO app_settings (k, v)
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE v = VALUES(v)
    ");

    if (!$st) {
        die('Settings prepare failed: ' . h($db->error));
    }

    $st->bind_param('ss', $k, $v);

    if (!$st->execute()) {
        die('Settings save failed for ' . h($k) . ': ' . h($st->error));
    }

    $st->close();
}

function email_template_seed(mysqli $db): void {
    $defaults = [
        ['registration_confirmation','Registration Confirmation','Welcome to Eden Campus - Registration Confirmation',
'<h2>Welcome {{student_name}}</h2>
<p>Your registration has been completed successfully.</p>
<p><strong>Student ID:</strong> {{student_id}}</p>
<p><strong>Reference No:</strong> {{reference_no}}</p>
<p><strong>Center Reg No:</strong> {{center_reg_no}}</p>
<p><strong>Academic Email:</strong> {{academic_email}}</p>
<p><strong>Academic Password:</strong> {{academic_password}}</p>
<p><strong>Existing Student:</strong> {{is_existing}}</p>
<p><strong>Course References:</strong></p>
<table cellpadding="8" cellspacing="0" style="border-collapse:collapse;width:100%;">{{reference_rows}}</table>
<p>Thank you,<br>Eden Campus</p>',1],

        ['payment_receipt','Payment Receipt','Payment Receipt - {{receipt_no}}',
'<h2>Payment Receipt</h2>
<p>Dear {{student_name}},</p>
<p>We have received your payment.</p>
<p><strong>Registration No:</strong> {{reg_no}}</p>
<p><strong>Receipt No:</strong> {{receipt_no}}</p>
<p><strong>Amount:</strong> {{amount}}</p>
<p><strong>Payment Date:</strong> {{payment_date}}</p>
<p><strong>Balance:</strong> {{balance}}</p>
<p>Thank you,<br>Eden Campus</p>',1],

        ['fee_due_reminder','Fee Due Reminder','Fee Reminder - Eden Campus',
'<h2>Fee Reminder</h2>
<p>Dear {{student_name}},</p>
<p>This is a reminder that your course fee payment is due.</p>
<p><strong>Due Amount:</strong> {{due_amount}}</p>
<p><strong>Due Date:</strong> {{due_date}}</p>
<p>Please make the payment on or before the due date.</p>
<p>Thank you,<br>Eden Campus</p>',1],

        ['overdue_reminder','Overdue Reminder','Overdue Payment Reminder - Eden Campus',
'<h2>Overdue Payment Reminder</h2>
<p>Dear {{student_name}},</p>
<p>Your payment is overdue.</p>
<p><strong>Overdue Amount:</strong> {{overdue_amount}}</p>
<p><strong>Due Date:</strong> {{due_date}}</p>
<p>Please settle the payment as soon as possible.</p>
<p>Thank you,<br>Eden Campus</p>',1],

        ['marks_result_release','Marks / Results Released','Your Results Have Been Released - Eden Campus',
'<h2>Results Released</h2>
<p>Dear {{student_name}},</p>
<p>Your marks/results have been released.</p>
<p><strong>Course:</strong> {{course_name}}</p>
<p><strong>Module:</strong> {{module_name}}</p>
<p><strong>Marks:</strong> {{marks}}</p>
<p><strong>Grade:</strong> {{grade}}</p>
<p>Thank you,<br>Eden Campus</p>',1],
    ];

    $st = $db->prepare("
        INSERT INTO rms_email_templates(template_key, template_name, subject, body_html, is_enabled)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
            template_name = VALUES(template_name),
            subject = IF(subject IS NULL OR subject='', VALUES(subject), subject),
            body_html = IF(body_html IS NULL OR body_html='', VALUES(body_html), body_html)
    ");

    if (!$st) return;

    foreach ($defaults as $d) {
        [$key, $name, $subject, $body, $enabled] = $d;
        $st->bind_param('ssssi', $key, $name, $subject, $body, $enabled);
        $st->execute();
    }

    $st->close();
}

function whatsapp_template_seed(mysqli $db): void {
    $defaults = [
        ['registration_confirmation','Registration Confirmation',
"Hello {{student_name}}, your registration has been completed successfully.

Student ID: {{student_id}}
Reference No: {{reference_no}}
Center Reg No: {{center_reg_no}}
Academic Email: {{academic_email}}
Password: {{academic_password}}
Existing Student: {{is_existing}}

Course References:
{{course_references_text}}

Thank you,
EDEN CAMPUS",1],

        ['payment_receipt','Payment Receipt / Payment Confirmation',
"Hello {{student_name}}, payment received successfully.

Registration No: {{reg_no}}
Receipt No: {{receipt_no}}
Amount: LKR {{amount}}
Payment Date: {{payment_date}}
Balance: {{balance}}

Thank you,
EDEN CAMPUS",1],

        ['fee_due_reminder','Fee Due Reminder',
"Hello {{student_name}}, this is a reminder that your course fee payment is due.

Due Amount: LKR {{due_amount}}
Due Date: {{due_date}}

Please make the payment on or before the due date.
EDEN CAMPUS",1],

        ['overdue_reminder','Overdue Reminder',
"Hello {{student_name}}, your payment is overdue.

Overdue Amount: LKR {{overdue_amount}}
Due Date: {{due_date}}

Please settle the payment as soon as possible.
EDEN CAMPUS",1],

        ['marks_result_release','Marks / Results Released',
"Hello {{student_name}}, your marks/results have been released.

Course: {{course_name}}
Module: {{module_name}}
Marks: {{marks}}
Grade: {{grade}}

Please login to view more details.
EDEN CAMPUS",1],
    ];

    $st = $db->prepare("
        INSERT INTO whatsapp_templates(template_key, template_name, message_body, is_enabled)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
            template_name = VALUES(template_name),
            message_body = IF(message_body IS NULL OR message_body='', VALUES(message_body), message_body)
    ");

    if (!$st) return;

    foreach ($defaults as $d) {
        [$key, $name, $body, $enabled] = $d;
        $st->bind_param('sssi', $key, $name, $body, $enabled);
        $st->execute();
    }

    $st->close();
}

email_template_seed($db);
whatsapp_template_seed($db);

$flash = '';
$oldWhatsAppEnabled = sget($db, 'whatsapp_enabled', '0');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    sset($db, 'sms_enabled', isset($_POST['sms_enabled']) ? '1' : '0');
    sset($db, 'birthday_sms_enabled', isset($_POST['birthday_sms_enabled']) ? '1' : '0');
    sset($db, 'sms_provider', trim((string)($_POST['sms_provider'] ?? 'devlog')));
    sset($db, 'sms_default_country', trim((string)($_POST['sms_default_country'] ?? 'LK')));

    sset($db, 'twilio_sid', trim((string)($_POST['twilio_sid'] ?? '')));
    if (trim((string)($_POST['twilio_token'] ?? '')) !== '') {
        sset($db, 'twilio_token', trim((string)$_POST['twilio_token']));
    }
    sset($db, 'twilio_from', trim((string)($_POST['twilio_from'] ?? '')));

    sset($db, 'vonage_key', trim((string)($_POST['vonage_key'] ?? '')));
    if (trim((string)($_POST['vonage_secret'] ?? '')) !== '') {
        sset($db, 'vonage_secret', trim((string)$_POST['vonage_secret']));
    }
    sset($db, 'vonage_from', trim((string)($_POST['vonage_from'] ?? '')));
    sset($db, 'textbelt_key', trim((string)($_POST['textbelt_key'] ?? 'textbelt')));

    $emailIds = $_POST['email_id'] ?? [];
    $emailSubjects = $_POST['email_subject'] ?? [];
    $emailBodies = $_POST['email_body_html'] ?? [];
    $emailEnabled = $_POST['email_enabled'] ?? [];

    foreach ($emailIds as $rawId) {
        $id = (int)$rawId;
        if ($id <= 0) continue;

        $subject = trim((string)($emailSubjects[$id] ?? ''));
        $body = trim((string)($emailBodies[$id] ?? ''));
        $enabled = ((string)($emailEnabled[$id] ?? '0') === '1') ? 1 : 0;

        $st = $db->prepare("
            UPDATE rms_email_templates 
            SET subject=?, body_html=?, is_enabled=? 
            WHERE id=? 
            LIMIT 1
        ");

        if (!$st) {
            die('Email template prepare failed: ' . h($db->error));
        }

        $st->bind_param('ssii', $subject, $body, $enabled, $id);

        if (!$st->execute()) {
            die('Email template save failed: ' . h($st->error));
        }

        $st->close();
    }

    $newWhatsAppEnabled = ((string)($_POST['whatsapp_enabled'] ?? '0') === '1') ? '1' : '0';

sset($db, 'whatsapp_enabled', $newWhatsAppEnabled);
sset($db, 'whatsapp_provider', trim((string)($_POST['whatsapp_provider'] ?? 'dev_log')));
sset($db, 'wa_cloud_api_version', trim((string)($_POST['wa_cloud_api_version'] ?? 'v23.0')));
sset($db, 'wa_phone_number_id', trim((string)($_POST['wa_phone_number_id'] ?? '')));
sset($db, 'wa_access_token', trim((string)($_POST['wa_access_token'] ?? '')));

$waIds = $_POST['wa_id'] ?? [];
$waBodies = $_POST['wa_message_body'] ?? [];
$waEnabled = $_POST['wa_enabled'] ?? [];

foreach ($waIds as $rawId) {
    $id = (int)$rawId;
    if ($id <= 0) continue;

    $body = trim((string)($waBodies[$id] ?? ''));

    // Global OFF nam okkoma OFF
    // Global ON nam individual select value eka save wenawa
    $enabled = 0;
    if ($newWhatsAppEnabled === '1') {
        $enabled = ((string)($waEnabled[$id] ?? '0') === '1') ? 1 : 0;
    }

    $st = $db->prepare("
        UPDATE whatsapp_templates 
        SET message_body=?, is_enabled=? 
        WHERE id=? 
        LIMIT 1
    ");

    if (!$st) {
        die('WhatsApp template prepare failed: ' . h($db->error));
    }

    $st->bind_param('sii', $body, $enabled, $id);

    if (!$st->execute()) {
        die('WhatsApp template save failed: ' . h($st->error));
    }

    $st->close();
}
    sset($db, 'whatsapp_provider', trim((string)($_POST['whatsapp_provider'] ?? 'dev_log')));
    sset($db, 'wa_cloud_api_version', trim((string)($_POST['wa_cloud_api_version'] ?? 'v23.0')));
    sset($db, 'wa_phone_number_id', trim((string)($_POST['wa_phone_number_id'] ?? '')));
    sset($db, 'wa_access_token', trim((string)($_POST['wa_access_token'] ?? '')));

    $waIds = $_POST['wa_id'] ?? [];
    $waBodies = $_POST['wa_message_body'] ?? [];
    $waEnabled = $_POST['wa_enabled'] ?? [];

    foreach ($waIds as $rawId) {
        $id = (int)$rawId;
        if ($id <= 0) continue;

        $body = trim((string)($waBodies[$id] ?? ''));

        if ($newWhatsAppEnabled === '0') {
            $enabled = 0;
        } elseif ($globalChanged && $newWhatsAppEnabled === '1') {
            $enabled = 1;
        } else {
            $enabled = ((string)($waEnabled[$id] ?? '0') === '1') ? 1 : 0;
        }

        $st = $db->prepare("
            UPDATE whatsapp_templates 
            SET message_body=?, is_enabled=? 
            WHERE id=? 
            LIMIT 1
        ");

        if (!$st) {
            die('WhatsApp template prepare failed: ' . h($db->error));
        }

        $st->bind_param('sii', $body, $enabled, $id);

        if (!$st->execute()) {
            die('WhatsApp template save failed: ' . h($st->error));
        }

        $st->close();
    }

    $test = trim((string)($_POST['test_phone'] ?? ''));

    if ($test !== '') {
        $err = null;
        $ok = sms_send($test, 'Test SMS from Eden Campus RMS ✅', $err);
        $flash = $ok ? 'Saved. Test SMS sent.' : ('Saved. Test SMS failed: ' . h((string)$err));
    } else {
        $flash = 'Saved successfully.';
    }

    $oldWhatsAppEnabled = $newWhatsAppEnabled;
}

$cfg = sms_cfg();

$emailTemplates = [];
$rs = $db->query("SELECT * FROM rms_email_templates ORDER BY id ASC");
if ($rs) {
    while ($row = $rs->fetch_assoc()) {
        $emailTemplates[] = $row;
    }
}

$waTemplates = [];
$rs = $db->query("SELECT * FROM whatsapp_templates ORDER BY id ASC");
if ($rs) {
    while ($row = $rs->fetch_assoc()) {
        $waTemplates[] = $row;
    }
}

$whatsappEnabled = sget($db, 'whatsapp_enabled', '0');
$whatsappProvider = sget($db, 'whatsapp_provider', 'dev_log');

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<style>
.ec-main{background:#f6f8fb;min-height:100vh}
.ec-comm-wrap{max-width:1180px;margin:0 auto}
.ec-page-head{background:linear-gradient(135deg,#07162e,#0f766e);border-radius:24px;padding:26px;color:#fff;margin-bottom:18px;box-shadow:0 18px 42px rgba(15,23,42,.16)}
.ec-page-head h4{font-weight:900;margin:0;letter-spacing:-.02em}
.ec-page-head p{margin:7px 0 0;color:rgba(255,255,255,.78)}
.ec-card{background:#fff;border:1px solid #e8edf5;border-radius:22px;box-shadow:0 14px 34px rgba(15,23,42,.06);padding:20px;margin-bottom:18px}
.ec-card-title{display:flex;align-items:center;justify-content:space-between;gap:14px;margin-bottom:16px}
.ec-card-title h6{font-weight:900;margin:0;color:#0f172a}
.ec-muted{color:#64748b;font-size:.86rem}
.ec-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
.ec-grid-2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.ec-pill{display:inline-flex;align-items:center;gap:7px;padding:7px 12px;border-radius:999px;font-size:.76rem;font-weight:900;white-space:nowrap}
.ec-pill-on{background:#dcfce7;color:#166534}
.ec-pill-off{background:#e5e7eb;color:#475569}
.ec-pill-dev{background:#dbeafe;color:#1d4ed8}
.ec-alert{background:#f8fafc;border:1px solid #e2e8f0;border-radius:16px;padding:14px;color:#334155;font-size:.86rem;line-height:1.8}
.ec-alert code{color:#be123c;background:#fff;border:1px solid #fee2e2;border-radius:8px;padding:2px 6px}
.ec-template{border:1px solid #e6edf7;border-radius:18px;overflow:hidden;background:#fff;margin-bottom:12px}
.ec-template-head{width:100%;border:0;background:#f8fbff;padding:14px 16px;display:flex;align-items:center;justify-content:space-between;text-align:left;cursor:pointer}
.ec-template-head:hover{background:#f1f7ff}
.ec-template-head strong{font-size:.95rem;color:#0f172a}
.ec-template-head span{font-size:.78rem;color:#64748b}
.ec-template-body{display:none;padding:16px;border-top:1px solid #e6edf7;background:#fff}
.ec-template.open .ec-template-body{display:block}
.ec-template-arrow{font-size:1.1rem;color:#64748b;transition:.2s ease}
.ec-template.open .ec-template-arrow{transform:rotate(180deg)}
.ec-mini-label{font-size:.78rem;font-weight:800;color:#475569;margin-bottom:6px}
.ec-form-select,.ec-form-control{border-radius:13px;border:1px solid #dbe3ef;min-height:42px}
.ec-form-control:focus,.ec-form-select:focus{border-color:#0f766e;box-shadow:0 0 0 .18rem rgba(15,118,110,.12)}
.ec-savebar{position:sticky;bottom:0;background:rgba(248,250,252,.92);backdrop-filter:blur(10px);padding:14px;border-radius:20px;border:1px solid #e5e7eb;display:flex;justify-content:flex-end;z-index:20}
.ec-savebar .btn{border-radius:14px;font-weight:800}
.ec-section-line{border-color:#edf2f7;margin:18px 0}
@media(max-width:900px){
    .ec-grid,.ec-grid-2{grid-template-columns:1fr}
    .ec-card-title{align-items:flex-start;flex-direction:column}
}
</style>

<main class="ec-main">
    <div class="container-fluid py-4">
        <div class="ec-comm-wrap">

            <div class="ec-page-head">
                <h4>Communication Settings</h4>
                <p>Manage SMS, Email and WhatsApp automated notifications from one place.</p>
            </div>

            <?php if ($flash): ?>
                <div class="alert alert-info border-0 shadow-sm rounded-4"><?= h($flash) ?></div>
            <?php endif; ?>

            <form method="post" autocomplete="off">

                <div class="ec-card">
                    <div class="ec-card-title">
                        <div>
                            <h6>SMS Settings</h6>
                            <div class="ec-muted">SMS provider, birthday SMS and test SMS.</div>
                        </div>
                        <span class="ec-pill <?= !empty($cfg['sms_enabled']) ? 'ec-pill-on' : 'ec-pill-off' ?>">
                            <?= !empty($cfg['sms_enabled']) ? 'SMS ON' : 'SMS OFF' ?>
                        </span>
                    </div>

                    <div class="ec-grid">
                        <div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_enabled" name="sms_enabled" value="1" <?= !empty($cfg['sms_enabled']) ? 'checked' : '' ?>>
                                <label for="sms_enabled" class="form-check-label fw-semibold">Enable SMS</label>
                            </div>
                        </div>

                        <div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="birthday_sms_enabled" name="birthday_sms_enabled" value="1" <?= !empty($cfg['birthday_sms_enabled']) ? 'checked' : '' ?>>
                                <label for="birthday_sms_enabled" class="form-check-label fw-semibold">Birthday SMS</label>
                            </div>
                        </div>

                        <div>
                            <label class="ec-mini-label">Default Country</label>
                            <select name="sms_default_country" class="form-select ec-form-select">
                                <option value="LK" <?= ($cfg['default_country'] ?? '') === 'LK' ? 'selected' : '' ?>>Sri Lanka</option>
                                <option value="IN" <?= ($cfg['default_country'] ?? '') === 'IN' ? 'selected' : '' ?>>India</option>
                                <option value="US" <?= ($cfg['default_country'] ?? '') === 'US' ? 'selected' : '' ?>>United States</option>
                            </select>
                        </div>
                    </div>

                    <hr class="ec-section-line">

                    <div class="ec-grid">
                        <div>
                            <label class="ec-mini-label">SMS Provider</label>
                            <select class="form-select ec-form-select" name="sms_provider" id="sms_provider">
                                <option value="devlog" <?= ($cfg['sms_provider'] ?? '') === 'devlog' ? 'selected' : '' ?>>Dev Log</option>
                                <option value="textbelt" <?= ($cfg['sms_provider'] ?? '') === 'textbelt' ? 'selected' : '' ?>>Textbelt</option>
                                <option value="vonage" <?= ($cfg['sms_provider'] ?? '') === 'vonage' ? 'selected' : '' ?>>Vonage</option>
                                <option value="twilio" <?= ($cfg['sms_provider'] ?? '') === 'twilio' ? 'selected' : '' ?>>Twilio</option>
                            </select>
                        </div>

                        <div>
                            <label class="ec-mini-label">Send Test SMS To</label>
                            <input name="test_phone" class="form-control ec-form-control" placeholder="+94XXXXXXXXX or 07XXXXXXXX">
                        </div>
                    </div>

                    <div id="prov_textbelt" class="mt-3">
                        <div class="ec-grid">
                            <div>
                                <label class="ec-mini-label">Textbelt Key</label>
                                <input name="textbelt_key" class="form-control ec-form-control" value="<?= h($cfg['textbelt_key'] ?? '') ?>">
                            </div>
                        </div>
                    </div>

                    <div id="prov_vonage" class="mt-3">
                        <div class="ec-grid">
                            <div>
                                <label class="ec-mini-label">Vonage API Key</label>
                                <input name="vonage_key" class="form-control ec-form-control" value="<?= h($cfg['vonage_key'] ?? '') ?>">
                            </div>
                            <div>
                                <label class="ec-mini-label">Vonage API Secret</label>
                                <input name="vonage_secret" class="form-control ec-form-control" placeholder="<?= !empty($cfg['vonage_secret']) ? '•••••• keep existing' : '' ?>">
                            </div>
                            <div>
                                <label class="ec-mini-label">Vonage From</label>
                                <input name="vonage_from" class="form-control ec-form-control" value="<?= h($cfg['vonage_from'] ?? '') ?>">
                            </div>
                        </div>
                    </div>

                    <div id="prov_twilio" class="mt-3">
                        <div class="ec-grid">
                            <div>
                                <label class="ec-mini-label">Twilio SID</label>
                                <input name="twilio_sid" class="form-control ec-form-control" value="<?= h($cfg['twilio_sid'] ?? '') ?>">
                            </div>
                            <div>
                                <label class="ec-mini-label">Twilio Token</label>
                                <input name="twilio_token" class="form-control ec-form-control" placeholder="<?= !empty($cfg['twilio_token']) ? '•••••• keep existing' : '' ?>">
                            </div>
                            <div>
                                <label class="ec-mini-label">Twilio From</label>
                                <input name="twilio_from" class="form-control ec-form-control" value="<?= h($cfg['twilio_from'] ?? '') ?>">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="ec-card">
                    <div class="ec-card-title">
                        <div>
                            <h6>Email Notification Templates</h6>
                            <div class="ec-muted">Control each email message, subject and HTML body separately.</div>
                        </div>
                    </div>

                    <?php foreach ($emailTemplates as $tpl): ?>
                        <?php $id = (int)$tpl['id']; ?>
                        <div class="ec-template">
                            <button class="ec-template-head ec-toggle-template" type="button">
                                <div>
                                    <strong><?= h($tpl['template_name']) ?></strong><br>
                                    <span><?= h($tpl['template_key']) ?></span>
                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    <span class="ec-pill <?= (int)$tpl['is_enabled'] === 1 ? 'ec-pill-on' : 'ec-pill-off' ?>">
                                        <?= (int)$tpl['is_enabled'] === 1 ? 'ON' : 'OFF' ?>
                                    </span>
                                    <span class="ec-template-arrow">⌄</span>
                                </div>
                            </button>

                            <div class="ec-template-body">
                                <input type="hidden" name="email_id[]" value="<?= $id ?>">

                                <div class="ec-grid mb-3">
                                    <div>
                                        <label class="ec-mini-label">Email Template Status</label>
                                        <select name="email_enabled[<?= $id ?>]" class="form-select ec-form-select">
                                            <option value="1" <?= (int)$tpl['is_enabled'] === 1 ? 'selected' : '' ?>>ON</option>
                                            <option value="0" <?= (int)$tpl['is_enabled'] !== 1 ? 'selected' : '' ?>>OFF</option>
                                        </select>
                                    </div>
                                    <div class="grid-span-2">
                                        <label class="ec-mini-label">Subject / Title</label>
                                        <input type="text" name="email_subject[<?= $id ?>]" class="form-control ec-form-control" value="<?= h($tpl['subject']) ?>">
                                    </div>
                                </div>

                                <label class="ec-mini-label">Email Body HTML</label>
                                <textarea name="email_body_html[<?= $id ?>]" rows="9" class="form-control ec-form-control"><?= h($tpl['body_html']) ?></textarea>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <div class="ec-card">
                    <div class="ec-card-title">
                        <div>
                            <h6>WhatsApp Notification Settings</h6>
                            <div class="ec-muted">Global WhatsApp control, provider credentials and individual templates.</div>
                        </div>
                        <span class="ec-pill <?= $whatsappEnabled === '1' ? 'ec-pill-on' : 'ec-pill-off' ?>">
                            WhatsApp Global <?= $whatsappEnabled === '1' ? 'ON' : 'OFF' ?>
                        </span>
                    </div>

                    <div class="ec-grid">
                        <div>
                            <label class="ec-mini-label">WhatsApp Global Status</label>
                            <select name="whatsapp_enabled" id="whatsapp_enabled" class="form-select ec-form-select">
                                <option value="1" <?= $whatsappEnabled === '1' ? 'selected' : '' ?>>ON</option>
                                <option value="0" <?= $whatsappEnabled !== '1' ? 'selected' : '' ?>>OFF</option>
                            </select>
                        </div>

                        <div>
                            <label class="ec-mini-label">WhatsApp Provider</label>
                            <select name="whatsapp_provider" class="form-select ec-form-select" id="whatsapp_provider">
                                <option value="dev_log" <?= $whatsappProvider === 'dev_log' ? 'selected' : '' ?>>Dev Log Only</option>
                                <option value="cloud_api" <?= $whatsappProvider === 'cloud_api' ? 'selected' : '' ?>>WhatsApp Cloud API</option>
                                <option value="twilio" <?= $whatsappProvider === 'twilio' ? 'selected' : '' ?>>Twilio WhatsApp Later</option>
                            </select>
                        </div>
                    </div>

                    <div id="wa_cloud_block" class="mt-3">
                        <div class="ec-grid">
                            <div>
                                <label class="ec-mini-label">Cloud API Version</label>
                                <input type="text" name="wa_cloud_api_version" class="form-control ec-form-control" value="<?= h(sget($db, 'wa_cloud_api_version', 'v23.0')) ?>">
                            </div>
                            <div>
                                <label class="ec-mini-label">Phone Number ID</label>
                                <input type="text" name="wa_phone_number_id" class="form-control ec-form-control" value="<?= h(sget($db, 'wa_phone_number_id', '')) ?>">
                            </div>
                            <div>
                                <label class="ec-mini-label">Access Token</label>
                                <textarea name="wa_access_token" class="form-control ec-form-control" rows="2"><?= h(sget($db, 'wa_access_token', '')) ?></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="ec-alert mt-3">
                        <strong>Placeholders:</strong>
                        <code>{{student_name}}</code> <code>{{student_id}}</code> <code>{{reg_no}}</code>
                        <code>{{reference_no}}</code> <code>{{center_reg_no}}</code> <code>{{academic_email}}</code>
                        <code>{{academic_password}}</code> <code>{{course_references_text}}</code>
                        <code>{{receipt_no}}</code> <code>{{amount}}</code> <code>{{payment_date}}</code>
                        <code>{{balance}}</code> <code>{{due_amount}}</code> <code>{{due_date}}</code>
                        <code>{{overdue_amount}}</code> <code>{{course_name}}</code> <code>{{module_name}}</code>
                        <code>{{marks}}</code> <code>{{grade}}</code>
                    </div>

                    <div class="mt-3">
                        <?php foreach ($waTemplates as $tpl): ?>
                            <?php $id = (int)$tpl['id']; ?>
                            <div class="ec-template">
                                <button class="ec-template-head ec-toggle-template" type="button">
                                    <div>
                                        <strong><?= h($tpl['template_name']) ?></strong><br>
                                        <span><?= h($tpl['template_key']) ?></span>
                                    </div>
                                    <div class="d-flex align-items-center gap-2">
                                        <span class="ec-pill <?= (int)$tpl['is_enabled'] === 1 ? 'ec-pill-on' : 'ec-pill-off' ?>">
                                            <?= (int)$tpl['is_enabled'] === 1 ? 'ON' : 'OFF' ?>
                                        </span>
                                        <span class="ec-template-arrow">⌄</span>
                                    </div>
                                </button>

                                <div class="ec-template-body">
                                    <input type="hidden" name="wa_id[]" value="<?= $id ?>">

                                    <div class="ec-grid mb-3">
                                        <div>
                                            <label class="ec-mini-label">WhatsApp Template Status</label>
                                            <select name="wa_enabled[<?= $id ?>]" class="form-select ec-form-select wa-template-status">
                                                <option value="1" <?= (int)$tpl['is_enabled'] === 1 ? 'selected' : '' ?>>ON</option>
                                                <option value="0" <?= (int)$tpl['is_enabled'] !== 1 ? 'selected' : '' ?>>OFF</option>
                                            </select>
                                        </div>
                                    </div>

                                    <label class="ec-mini-label">WhatsApp Message</label>
                                    <textarea name="wa_message_body[<?= $id ?>]" rows="8" class="form-control ec-form-control"><?= h($tpl['message_body']) ?></textarea>
                                    <div class="ec-muted mt-2">Plain text only. Do not use HTML tags.</div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="ec-savebar">
                    <button class="btn btn-primary px-4" type="submit">
                        <i class="bi bi-check2-circle me-1"></i> Save settings
                    </button>
                </div>

            </form>
        </div>
    </div>
</main>

<script>
(function(){
    const smsSel = document.getElementById('sms_provider');
    const blocks = {
        textbelt: document.getElementById('prov_textbelt'),
        vonage: document.getElementById('prov_vonage'),
        twilio: document.getElementById('prov_twilio')
    };

    function refreshSms(){
        if(!smsSel) return;

        Object.keys(blocks).forEach(function(k){
            if(blocks[k]){
                blocks[k].style.display = smsSel.value === k ? 'block' : 'none';
            }
        });
    }

    if(smsSel){
        smsSel.addEventListener('change', refreshSms);
        refreshSms();
    }

    const waSel = document.getElementById('whatsapp_provider');
    const waBlock = document.getElementById('wa_cloud_block');

    function refreshWAProvider(){
        if(!waSel || !waBlock) return;
        waBlock.style.display = waSel.value === 'cloud_api' ? 'block' : 'none';
    }

    if(waSel){
        waSel.addEventListener('change', refreshWAProvider);
        refreshWAProvider();
    }

    document.querySelectorAll('.ec-toggle-template').forEach(function(btn){
        btn.addEventListener('click', function(){
            const card = btn.closest('.ec-template');
            if(card){
                card.classList.toggle('open');
            }
        });
    });

const waGlobal = document.getElementById('whatsapp_enabled');

if (waGlobal) {
    waGlobal.addEventListener('change', function () {
        document.querySelectorAll('.wa-template-status').forEach(function(sel){
            sel.value = waGlobal.value === '1' ? '1' : '0';
        });
    });
}
})();
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>