<?php
$page_title = 'قوالب الرسائل';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidMessagesTemplates = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidMessagesTemplates) $UA_PAGE_CSS = ['assets/css/android_messages_templates.css'];
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/messages_lib.php';

require_login('login.php');
if(function_exists('require_perm')) require_perm('can_manage_messages');
$conn = ensure_db(true);

$msg = '';
$err = '';

if(isset($_POST['save_all'])){
  try {
    if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
      throw new RuntimeException('CSRF validation failed.');
    }
    $conn->begin_transaction();
    foreach(($_POST['tpl'] ?? []) as $key => $row){
      if (!is_array($row)) continue;
      $title = (string)($row['title'] ?? '');
      $body = (string)($row['body'] ?? '');
      $channel = (string)($row['channel'] ?? 'whatsapp');
      $isEnabled = isset($row['is_enabled']) ? 1 : 0;
      if (!save_message_template($conn, (string)$key, $title, $body, $channel, $isEnabled)) {
        throw new RuntimeException('Failed to save message template: ' . (string)$key);
      }
    }
    $conn->commit();
    $msg = 'تم حفظ القوالب بنجاح ✅';
  } catch (Throwable $e) {
    try { $conn->rollback(); } catch (Throwable $rollbackError) {}
    error_log('[message_templates] save failed: ' . $e->getMessage());
    $err = 'تعذر حفظ القوالب. لم يتم تغيير أي قالب، يرجى إعادة المحاولة.';
  }
}

$templates = get_message_templates($conn);

$help_vars = '{name} {subscriber_id} {phone} {invoice_id} {amount} {due_date} {package} {speed} {username} {password} {days_left} {company_name} {device_type} {device_name} {device_host} {event_time} {offline_duration}';

require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
$active_tab = 'templates';
include __DIR__ . '/messages_tabs.php';
?>

<div class="content-wrapper ua-msg-page ua-extracted-page msg-templates-page">
  <section class="content">
    <div class="container-fluid">
      <header class="msg-page-hero">
        <div class="msg-page-hero__title">
          <i class="msg-page-hero__icon fa fa-file-text-o"></i>
          <div>
            <small>MESSAGE TEMPLATES</small>
            <h1>قوالب الرسائل</h1>
            <p>تحرير محتوى رسائل النظام وتحديد قناة الإرسال المناسبة لكل حدث.</p>
          </div>
        </div>
        <div class="msg-page-hero__meta"><i></i><?= count($templates) ?> قالب</div>
      </header>

      <?php if ($msg !== ''): ?><div class="msg-feedback" role="status"><i class="fa fa-check-circle"></i><span><?= h($msg) ?></span></div><?php endif; ?>
      <?php if ($err !== ''): ?><div class="msg-feedback is-error" role="alert"><i class="fa fa-exclamation-triangle"></i><span><?= h($err) ?></span></div><?php endif; ?>

      <div class="msg-template-meta" aria-label="المتغيرات المتاحة">
        <span><i class="fa fa-code"></i> المتغيرات المتاحة</span>
        <?php foreach (explode(' ', $help_vars) as $helpVar): ?><span dir="ltr"><?= h($helpVar) ?></span><?php endforeach; ?>
      </div>

      <form method="post">
        <?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?>
        <div class="msg-template-grid">
          <?php foreach ($templates as $key => $t): ?>
            <?php $ch = (string)($t['channel'] ?? 'whatsapp'); ?>
            <article class="msg-template-card">
              <header class="msg-template-card__head">
                <div>
                  <b><?= h($t['title'] ?? $key) ?></b>
                  <small dir="ltr"><?= h($key) ?></small>
                </div>
                <label class="msg-template-switch" for="sw_<?= h($key) ?>">
                  <input type="checkbox" id="sw_<?= h($key) ?>" name="tpl[<?= h($key) ?>][is_enabled]" <?= ((int)($t['is_enabled'] ?? 0)===1?'checked':'') ?>>
                  <span>تفعيل</span>
                </label>
              </header>
              <div class="msg-template-card__body">
                <label class="msg-field">
                  <span>العنوان</span>
                  <input type="text" name="tpl[<?= h($key) ?>][title]" value="<?= h($t['title'] ?? '') ?>">
                </label>
                <label class="msg-field">
                  <span>القناة</span>
                  <select name="tpl[<?= h($key) ?>][channel]">
                    <option value="whatsapp" <?= ($ch==='whatsapp'?'selected':'') ?>>واتساب</option>
                    <option value="sms" <?= ($ch==='sms'?'selected':'') ?>>SMS</option>
                    <option value="both" <?= ($ch==='both'?'selected':'') ?>>واتساب + SMS</option>
                  </select>
                </label>
                <label class="msg-field is-body">
                  <span>نص الرسالة</span>
                  <textarea name="tpl[<?= h($key) ?>][body]"><?= h($t['body'] ?? '') ?></textarea>
                </label>
              </div>
            </article>
          <?php endforeach; ?>
        </div>

        <div class="msg-template-save">
          <span><i class="fa fa-info-circle"></i> تُحفظ جميع القوالب دفعة واحدة، ولن يتغير أي قالب إذا فشلت العملية.</span>
          <button name="save_all" value="1"><i class="fa fa-save"></i> حفظ جميع القوالب</button>
        </div>
      </form>
    </div>
  </section>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
