<?php
declare(strict_types=1);
require_once __DIR__ . '/queue_bootstrap.php';
qh_boot();
qh_admin_handle_request();

// Ensure the table exists
$pdo = db();
$pdo->exec("CREATE TABLE IF NOT EXISTS hospital_ads (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NULL,
    video_path VARCHAR(255) NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    sort_order INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS hospital_news (
    id INT AUTO_INCREMENT PRIMARY KEY,
    phrase VARCHAR(1000) NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    sort_order INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Handle Form Submissions
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'add_video' && !empty($_FILES['video']['name'])) {
        $uploadDir = __DIR__ . '/assets/videos/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $ext = strtolower(pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION));
        $allowed = ['mp4', 'webm', 'ogg'];
        
        if (!in_array($ext, $allowed)) {
            $message = qh_t("Invalid video format (.$ext). Allowed formats: MP4, WebM, OGG.", "تنسيق فيديو غير صالح (.$ext). الصيغ المسموحة: MP4, WebM, OGG.");
        } elseif ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
            $errorMap = [
                UPLOAD_ERR_INI_SIZE   => 'File exceeds max size in php.ini.',
                UPLOAD_ERR_FORM_SIZE  => 'File exceeds max size in HTML form.',
                UPLOAD_ERR_PARTIAL    => 'File was partially uploaded.',
                UPLOAD_ERR_NO_FILE    => 'No file was uploaded.',
                UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
                UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
                UPLOAD_ERR_EXTENSION  => 'A PHP extension stopped the upload.'
            ];
            $errMsg = $errorMap[$_FILES['video']['error']] ?? 'Unknown error';
            $message = qh_t('Upload error: ' . $errMsg, 'خطأ في الرفع: ' . $errMsg);
        } else {
            $filename = uniqid('vid_') . '.' . $ext;
            $dest = $uploadDir . $filename;
            
            if (move_uploaded_file($_FILES['video']['tmp_name'], $dest)) {
                $title = $_POST['title'] ?? '';
                $path = 'assets/videos/uploads/' . $filename;
                
                $stmt = $pdo->prepare("INSERT INTO hospital_ads (title, video_path, is_active) VALUES (?, ?, 1)");
                $stmt->execute([$title, $path]);
                $message = qh_t('Video uploaded successfully.', 'تم رفع الفيديو بنجاح.');
            } else {
                $message = qh_t('Failed to save uploaded file.', 'فشل في حفظ الملف المرفوع.');
            }
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'delete_video' && !empty($_POST['video_id'])) {
        $id = (int) $_POST['video_id'];
        $stmt = $pdo->prepare("SELECT video_path FROM hospital_ads WHERE id = ?");
        $stmt->execute([$id]);
        $video = $stmt->fetch();
        if ($video) {
            $fullPath = __DIR__ . '/' . $video['video_path'];
            if (file_exists($fullPath)) {
                unlink($fullPath);
            }
            $pdo->prepare("DELETE FROM hospital_ads WHERE id = ?")->execute([$id]);
            $message = qh_t('Video deleted successfully.', 'تم حذف الفيديو بنجاح.');
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'toggle_status' && !empty($_POST['video_id'])) {
        $id = (int) $_POST['video_id'];
        $stmt = $pdo->prepare("UPDATE hospital_ads SET is_active = NOT is_active WHERE id = ?");
        $stmt->execute([$id]);
        $message = qh_t('Video status updated.', 'تم تحديث حالة الفيديو.');
    } elseif (isset($_POST['action']) && $_POST['action'] === 'add_news' && !empty($_POST['phrase'])) {
        $phrase = trim($_POST['phrase']);
        $stmt = $pdo->prepare("INSERT INTO hospital_news (phrase, is_active) VALUES (?, 1)");
        $stmt->execute([$phrase]);
        $message = qh_t('Phrase added successfully.', 'تمت إضافة العبارة بنجاح.');
    } elseif (isset($_POST['action']) && $_POST['action'] === 'delete_news' && !empty($_POST['news_id'])) {
        $id = (int) $_POST['news_id'];
        $pdo->prepare("DELETE FROM hospital_news WHERE id = ?")->execute([$id]);
        $message = qh_t('Phrase deleted successfully.', 'تم حذف العبارة بنجاح.');
    } elseif (isset($_POST['action']) && $_POST['action'] === 'toggle_news_status' && !empty($_POST['news_id'])) {
        $id = (int) $_POST['news_id'];
        $pdo->prepare("UPDATE hospital_news SET is_active = NOT is_active WHERE id = ?")->execute([$id]);
        $message = qh_t('Phrase status updated.', 'تم تحديث حالة العبارة.');
    }
}

// Fetch existing ads
$stmt = $pdo->query("SELECT * FROM hospital_ads ORDER BY sort_order ASC, id DESC");
$ads = $stmt->fetchAll();

$stmt2 = $pdo->query("SELECT * FROM hospital_news ORDER BY sort_order ASC, id DESC");
$newsPhrases = $stmt2->fetchAll();

qh_page_start(
    'admin_ads',
    qh_t('Manage Advertisements', 'إدارة الإعلانات'),
    qh_t('Upload and manage videos to display on the queue screen.', 'رفع وإدارة الفيديوهات لعرضها على شاشة الطابور.')
);
?>
<div class="container-fluid container-xxl px-3 px-lg-4">
  <div class="admin-layout">
    <aside class="admin-sidebar-column">
      <?php qh_render_admin_sidebar('admin_ads.php'); ?>
    </aside>

    <div class="admin-content-stack">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h1 class="h3 mb-0 text-gray-800 fw-bold"><?= qh_h(qh_t('Advertisements (Videos)', 'الإعلانات (فيديوهات)')) ?></h1>
          <p class="text-muted mb-0 mt-1"><?= qh_h(qh_t('These videos will be played sequentially on the display screen.', 'سيتم تشغيل هذه الفيديوهات بالتتابع على شاشة العرض.')) ?></p>
        </div>
      </div>

      <?php if ($message): ?>
        <div class="alert alert-info shadow-sm"><?= qh_h($message) ?></div>
      <?php endif; ?>

      <div class="card shadow-sm border-0 mb-4">
        <div class="card-header bg-white border-bottom py-3">
          <h5 class="mb-0 font-weight-bold text-dark"><?= qh_h(qh_t('Upload New Video', 'رفع فيديو جديد')) ?></h5>
        </div>
        <div class="card-body">
          <form method="post" enctype="multipart/form-data" class="row g-3">
            <input type="hidden" name="action" value="add_video">
            <div class="col-md-6">
              <label class="form-label fw-semibold text-dark"><?= qh_h(qh_t('Video Title (Optional)', 'عنوان الفيديو (اختياري)')) ?></label>
              <input type="text" name="title" class="form-control" placeholder="<?= qh_h(qh_t('e.g. Summer Promo', 'مثال: عرض الصيف')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label fw-semibold text-dark"><?= qh_h(qh_t('Video File', 'ملف الفيديو')) ?></label>
              <input type="file" name="video" class="form-control" accept="video/mp4,video/webm,video/ogg" required>
              <div class="form-text"><?= qh_h(qh_t('Formats: MP4, WebM, OGG.', 'الصيغ: MP4, WebM, OGG.')) ?></div>
            </div>
            <div class="col-12 mt-3">
              <button type="submit" class="btn btn-primary px-4"><?= qh_h(qh_t('Upload Video', 'رفع الفيديو')) ?></button>
            </div>
          </form>
        </div>
      </div>

      <div class="card shadow-sm border-0">
        <div class="card-header bg-white border-bottom py-3">
          <h5 class="mb-0 font-weight-bold text-dark"><?= qh_h(qh_t('Uploaded Videos', 'الفيديوهات المرفوعة')) ?></h5>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
              <thead class="table-light">
                <tr>
                  <th class="border-0 px-4 py-3"><?= qh_h(qh_t('Preview', 'معاينة')) ?></th>
                  <th class="border-0 py-3"><?= qh_h(qh_t('Title', 'العنوان')) ?></th>
                  <th class="border-0 py-3 text-center"><?= qh_h(qh_t('Status', 'الحالة')) ?></th>
                  <th class="border-0 px-4 py-3 text-end"><?= qh_h(qh_t('Actions', 'الإجراءات')) ?></th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($ads)): ?>
                  <tr>
                    <td colspan="4" class="text-center py-4 text-muted"><?= qh_h(qh_t('No videos uploaded yet.', 'لم يتم رفع فيديوهات بعد.')) ?></td>
                  </tr>
                <?php else: ?>
                  <?php foreach ($ads as $ad): ?>
                    <tr>
                      <td class="px-4 py-3">
                        <video width="120" class="rounded shadow-sm border" muted>
                          <source src="<?= qh_h($ad['video_path']) ?>" type="video/mp4">
                        </video>
                      </td>
                      <td class="py-3 fw-semibold text-dark">
                        <?= qh_h($ad['title'] ?: qh_t('Untitled', 'بدون عنوان')) ?>
                      </td>
                      <td class="py-3 text-center">
                        <?php if ($ad['is_active']): ?>
                          <span class="badge bg-success rounded-pill px-3"><?= qh_h(qh_t('Active', 'مفعل')) ?></span>
                        <?php else: ?>
                          <span class="badge bg-secondary rounded-pill px-3"><?= qh_h(qh_t('Inactive', 'غير مفعل')) ?></span>
                        <?php endif; ?>
                      </td>
                      <td class="px-4 py-3 text-end">
                        <div class="d-flex justify-content-end gap-2">
                          <form method="post" class="m-0 p-0">
                            <input type="hidden" name="action" value="toggle_status">
                            <input type="hidden" name="video_id" value="<?= (int) $ad['id'] ?>">
                            <button type="submit" class="btn btn-sm <?= $ad['is_active'] ? 'btn-outline-secondary' : 'btn-outline-success' ?>">
                              <?= qh_h($ad['is_active'] ? qh_t('Disable', 'تعطيل') : qh_t('Enable', 'تفعيل')) ?>
                            </button>
                          </form>
                          <form method="post" class="m-0 p-0" onsubmit="return confirm('<?= qh_h(qh_t('Are you sure you want to delete this video?', 'هل أنت متأكد أنك تريد حذف هذا الفيديو؟')) ?>');">
                            <input type="hidden" name="action" value="delete_video">
                            <input type="hidden" name="video_id" value="<?= (int) $ad['id'] ?>">
                            <button type="submit" class="btn btn-sm btn-outline-danger"><?= qh_h(qh_t('Delete', 'حذف')) ?></button>
                          </form>
                        </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- News Ticker Section -->
      <div class="d-flex justify-content-between align-items-center mb-4 mt-5">
        <div>
          <h1 class="h3 mb-0 text-gray-800 fw-bold"><?= qh_h(qh_t('News Ticker Phrases', 'عبارات شريط الأخبار')) ?></h1>
          <p class="text-muted mb-0 mt-1"><?= qh_h(qh_t('These phrases will scroll at the bottom of the display screen.', 'ستتحرك هذه العبارات في أسفل شاشة العرض.')) ?></p>
        </div>
      </div>

      <div class="card shadow-sm border-0 mb-4">
        <div class="card-header bg-white border-bottom py-3">
          <h5 class="mb-0 font-weight-bold text-dark"><?= qh_h(qh_t('Add New Phrase', 'إضافة عبارة جديدة')) ?></h5>
        </div>
        <div class="card-body">
          <form method="post" class="row g-3">
            <input type="hidden" name="action" value="add_news">
            <div class="col-md-10">
              <label class="form-label fw-semibold text-dark"><?= qh_h(qh_t('Phrase Text', 'نص العبارة')) ?></label>
              <input type="text" name="phrase" class="form-control" placeholder="<?= qh_h(qh_t('e.g. Welcome to our hospital. Please wait for your turn.', 'مثال: أهلاً بكم في مستشفانا. يرجى انتظار دوركم.')) ?>" required>
            </div>
            <div class="col-md-2 d-flex align-items-end">
              <button type="submit" class="btn btn-primary w-100"><?= qh_h(qh_t('Add', 'إضافة')) ?></button>
            </div>
          </form>
        </div>
      </div>

      <div class="card shadow-sm border-0 mb-4">
        <div class="card-header bg-white border-bottom py-3">
          <h5 class="mb-0 font-weight-bold text-dark"><?= qh_h(qh_t('Ticker Phrases', 'عبارات الشريط')) ?></h5>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
              <thead class="table-light">
                <tr>
                  <th class="border-0 px-4 py-3"><?= qh_h(qh_t('Phrase', 'العبارة')) ?></th>
                  <th class="border-0 py-3 text-center" style="width:120px;"><?= qh_h(qh_t('Status', 'الحالة')) ?></th>
                  <th class="border-0 px-4 py-3 text-end" style="width:200px;"><?= qh_h(qh_t('Actions', 'الإجراءات')) ?></th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($newsPhrases)): ?>
                  <tr>
                    <td colspan="3" class="text-center py-4 text-muted"><?= qh_h(qh_t('No phrases added yet.', 'لم يتم إضافة عبارات بعد.')) ?></td>
                  </tr>
                <?php else: ?>
                  <?php foreach ($newsPhrases as $n): ?>
                    <tr>
                      <td class="px-4 py-3 fw-semibold text-dark">
                        <?= qh_h($n['phrase']) ?>
                      </td>
                      <td class="py-3 text-center">
                        <?php if ($n['is_active']): ?>
                          <span class="badge bg-success rounded-pill px-3"><?= qh_h(qh_t('Active', 'مفعل')) ?></span>
                        <?php else: ?>
                          <span class="badge bg-secondary rounded-pill px-3"><?= qh_h(qh_t('Inactive', 'غير مفعل')) ?></span>
                        <?php endif; ?>
                      </td>
                      <td class="px-4 py-3 text-end">
                        <div class="d-flex justify-content-end gap-2">
                          <form method="post" class="m-0 p-0">
                            <input type="hidden" name="action" value="toggle_news_status">
                            <input type="hidden" name="news_id" value="<?= (int) $n['id'] ?>">
                            <button type="submit" class="btn btn-sm <?= $n['is_active'] ? 'btn-outline-secondary' : 'btn-outline-success' ?>">
                              <?= qh_h($n['is_active'] ? qh_t('Disable', 'تعطيل') : qh_t('Enable', 'تفعيل')) ?>
                            </button>
                          </form>
                          <form method="post" class="m-0 p-0" onsubmit="return confirm('<?= qh_h(qh_t('Are you sure you want to delete this phrase?', 'هل أنت متأكد أنك تريد حذف هذه العبارة؟')) ?>');">
                            <input type="hidden" name="action" value="delete_news">
                            <input type="hidden" name="news_id" value="<?= (int) $n['id'] ?>">
                            <button type="submit" class="btn btn-sm btn-outline-danger"><?= qh_h(qh_t('Delete', 'حذف')) ?></button>
                          </form>
                        </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php qh_page_end(); ?>