<?php
/**
 * settings-announcement.php (Layout-based)
 * Admin-only: Manage Announcements (thread)
 * - Add/Edit/Delete
 * - Active/Inactive toggle
 * - Upload image/video (png/jpg/jpeg/mp4/webm)
 * - CSRF + mime validation + safe filename
 * - Flash via GET (?success=... / ?error=...) -> SweetAlert2 toast (gaya profile.php)
 */

session_start();
require_once __DIR__ . "/db.php";

/* ===== Auth: admin only ===== */
if (!isset($_SESSION['user']) || (($_SESSION['user']['role'] ?? '') !== 'admin')) {
    header("Location: dashboard.php"); exit;
}

/* ===== CSRF ===== */
if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf_token'];

/* ===== Helpers ===== */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function flash_redirect(string $type, string $msg, string $extraQuery=''): void {
    $q = http_build_query([$type=>$msg]);
    if ($extraQuery) $q .= '&'.$extraQuery;
    header("Location: settings-announcement.php?$q"); exit;
}
function require_post_csrf(): void {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit("Method Not Allowed"); }
    $tok = $_POST['csrf_token'] ?? '';
    if (!hash_equals($_SESSION['csrf_token'] ?? '', $tok)) { http_response_code(403); exit("Invalid CSRF token"); }
}

/* ===== Upload config ===== */
$UPLOAD_DIR  = __DIR__ . "/uploads/announcements";
$PUBLIC_BASE = "uploads/announcements"; // relative URL path
if (!is_dir($UPLOAD_DIR)) { @mkdir($UPLOAD_DIR, 0775, true); }

$ALLOWED_IMAGE = ['image/png','image/jpeg']; // png, jpg, jpeg
$ALLOWED_VIDEO = ['video/mp4','video/webm'];
$MAX_SIZE      = 10 * 1024 * 1024; // 10MB

function detect_mime(string $tmpPath): string {
    $f = finfo_open(FILEINFO_MIME_TYPE);
    $m = finfo_file($f, $tmpPath);
    finfo_close($f);
    return $m ?: 'application/octet-stream';
}
function save_upload(array $file, string $UPLOAD_DIR, array $ALLOWED_IMAGE, array $ALLOWED_VIDEO, int $MAX_SIZE): array {
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) return [null, null]; // no file
    if ($file['error'] !== UPLOAD_ERR_OK) throw new RuntimeException("Upload error code ".$file['error']);
    if ($file['size'] > $MAX_SIZE) throw new RuntimeException("File too large (max 10MB).");

    $mime = detect_mime($file['tmp_name']);
    $type = null;
    if (in_array($mime, $ALLOWED_IMAGE, true)) $type = 'image';
    if (in_array($mime, $ALLOWED_VIDEO, true)) $type = $type ?: 'video';
    if (!$type) throw new RuntimeException("Invalid file type. Allowed: PNG/JPG/JPEG/MP4/WEBM.");

    $ext = ($type === 'image')
        ? ($mime === 'image/png' ? 'png' : 'jpg')
        : ($mime === 'video/webm' ? 'webm' : 'mp4');

    $fname = bin2hex(random_bytes(8)) . "." . $ext;
    $dest  = rtrim($UPLOAD_DIR, "/") . "/" . $fname;
    if (!move_uploaded_file($file['tmp_name'], $dest)) throw new RuntimeException("Failed to move uploaded file.");
    @chmod($dest, 0644);
    return [$fname, $type]; // returns (filename, media_type)
}

/* ===== Actions ===== */
$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    if ($action === 'create') {
        require_post_csrf();
        $title = trim($_POST['title'] ?? '');
        $body  = trim($_POST['body'] ?? '');
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        if ($title === '' || $body === '') {
            flash_redirect('error', 'Please fill in all required fields (title & body).');
        }

        [$fname, $type] = [null, null];
        if (isset($_FILES['media'])) {
            [$fname, $type] = save_upload($_FILES['media'], $UPLOAD_DIR, $ALLOWED_IMAGE, $ALLOWED_VIDEO, $MAX_SIZE);
        }

        $created_by   = (int)($_SESSION['user']['id'] ?? 0);
        $created_name = $_SESSION['user']['name'] ?? ($_SESSION['user']['full_name'] ?? '');

        $sql = "INSERT INTO announcements (title, body, media_path, media_type, is_active, created_by, created_name, created_at)
                VALUES (?,?,?,?,?,?,?,NOW())";
        $stmt = $conn->prepare($sql);
        $path = $fname ? ($PUBLIC_BASE."/".$fname) : null;
        $stmt->bind_param("ssssiss",
            $title, $body, $path, $type, $is_active, $created_by, $created_name
        );
        $stmt->execute(); $stmt->close();

        flash_redirect('success', 'Announcement created.');
    }
    else if ($action === 'update') {
        require_post_csrf();
        $id   = (int)($_POST['id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $body  = trim($_POST['body'] ?? '');
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        if ($id<=0 || $title==='' || $body==='') {
            flash_redirect('error', 'Invalid data for update.');
        }

        // fetch current for possible unlink if new upload exists
        $curr = null;
        if ($st = $conn->prepare("SELECT media_path FROM announcements WHERE id=? LIMIT 1")) {
            $st->bind_param("i", $id); $st->execute();
            $curr = $st->get_result()->fetch_assoc();
            $st->close();
        }

        $new_path = null; $new_type = null;
        if (isset($_FILES['media']) && ($_FILES['media']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
            [$fname, $t] = save_upload($_FILES['media'], $UPLOAD_DIR, $ALLOWED_IMAGE, $ALLOWED_VIDEO, $MAX_SIZE);
            $new_path = $fname ? ($PUBLIC_BASE."/".$fname) : null;
            $new_type = $t;

            // remove old media if exist
            if ($curr && !empty($curr['media_path'])) {
                $old = $UPLOAD_DIR . "/" . basename($curr['media_path']);
                if (is_file($old)) @unlink($old);
            }

            $sql = "UPDATE announcements SET title=?, body=?, media_path=?, media_type=?, is_active=?, updated_at=NOW() WHERE id=?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssisi", $title, $body, $new_path, $new_type, $is_active, $id);
            $stmt->execute(); $stmt->close();
        } else {
            $sql = "UPDATE announcements SET title=?, body=?, is_active=?, updated_at=NOW() WHERE id=?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssii", $title, $body, $is_active, $id);
            $stmt->execute(); $stmt->close();
        }

        flash_redirect('success', 'Announcement updated.');
    }
    else if ($action === 'toggle') {
        require_post_csrf();
        $id = (int)($_POST['id'] ?? 0);
        $to = (int)($_POST['to'] ?? 0);
        if ($id<=0) flash_redirect('error','Invalid ID.');
        $stmt = $conn->prepare("UPDATE announcements SET is_active=?, updated_at=NOW() WHERE id=?");
        $stmt->bind_param("ii", $to, $id);
        $stmt->execute(); $stmt->close();
        flash_redirect('success', $to ? 'Announcement activated.' : 'Announcement deactivated.');
    }
    else if ($action === 'delete') {
        require_post_csrf();
        $id = (int)$_POST['id'];
        if ($id<=0) flash_redirect('error','Invalid ID.');

        // unlink media if any
        $curr = null;
        if ($st = $conn->prepare("SELECT media_path FROM announcements WHERE id=? LIMIT 1")) {
            $st->bind_param("i", $id); $st->execute();
            $curr = $st->get_result()->fetch_assoc();
            $st->close();
        }
        if ($curr && !empty($curr['media_path'])) {
            $old = $UPLOAD_DIR . "/" . basename($curr['media_path']);
            if (is_file($old)) @unlink($old);
        }

        $stmt = $conn->prepare("DELETE FROM announcements WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute(); $stmt->close();
        flash_redirect('success', 'Announcement deleted.');
    }
} catch (Throwable $e) {
    flash_redirect('error', $e->getMessage());
}

/* ===== Read (list + optionally edit one) ===== */
$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editRow = null;
if ($editId > 0) {
    $st = $conn->prepare("SELECT * FROM announcements WHERE id=? LIMIT 1");
    $st->bind_param("i", $editId);
    $st->execute(); $editRow = $st->get_result()->fetch_assoc(); $st->close();
}

$rows = [];
if ($rs = $conn->query("SELECT * FROM announcements ORDER BY created_at DESC, id DESC")) {
    while ($r = $rs->fetch_assoc()) $rows[] = $r;
}

/* ====================== RENDER (layout.php) ====================== */
ob_start();
?>
<style>
/* Selaras gaya umum dashboard */
.card{background:#fff;border:1px solid #e5e7eb;border-radius:10px;box-shadow:0 1px 2px rgba(0,0,0,.04)}
.card-header{padding:14px 16px;border-bottom:1px solid #f0f0f0;font-weight:600;display:flex;align-items:center;justify-content:space-between;gap:8px}
.card-body{padding:12px 16px}
.row{display:flex;gap:16px;flex-wrap:wrap}
.col{flex:1 1 300px}
.small{font-size:12px;color:#6b7280}
.btn{border:1px solid #d1d5db;background:#fff;border-radius:8px;padding:6px 10px;font-size:13px;cursor:pointer;text-decoration:none;display:inline-block}
.btn-primary{background:#2563eb;color:#fff;border-color:#2563eb}
.btn-secondary{background:#6b7280;color:#fff;border-color:#6b7280}
.btn-outline{background:#fff}
.btn-outline-primary{border-color:#2563eb;color:#2563eb}
.btn-outline-secondary{border-color:#6b7280;color:#374151}
.btn-outline-danger{border-color:#dc2626;color:#dc2626}
.input, .textarea, .file{width:100%;padding:8px;border:1px solid #d1d5db;border-radius:8px;font-size:14px}
.checkbox{width:auto;height:16px}
.form-check{display:flex;align-items:center;gap:8px;margin-top:10px}
.form-check-label{font-size:14px;color:#374151}
.textarea{min-height:140px;resize:vertical}
.badge{display:inline-block;padding:3px 8px;border-radius:9999px;font-size:12px;font-weight:600;vertical-align:middle}
.badge-on{background:#eafff0;color:#047857;border:1px solid #bbf7d0}
.badge-off{background:#f3f4f6;color:#4b5563;border:1px solid #e5e7eb}
.thread-media{max-width:100%;height:auto;border-radius:.5rem}
.thread-video{max-width:100%;border-radius:.5rem}
.grid{display:grid;grid-template-columns:1fr}
@media (min-width: 960px){ .grid{grid-template-columns: 420px 1fr;gap:16px} }
.form-label{display:block;font-size:13px;margin:6px 0 6px 0;color:#374151}
</style>

<div class="content">
  <h2 style="margin:0">Announcement Settings</h2>
  <p class="small" style="margin-top:6px">Tambah, kemas kini, aktif/tidak aktif, dan padam pengumuman. Sokong imej (PNG/JPG/JPEG) & video (MP4/WEBM).</p>

  <div class="grid">
    <!-- ============ Form (Add/Edit) ============ -->
    <div>
      <div class="card">
        <div class="card-header"><?= $editRow ? 'Edit Announcement' : 'Add Announcement' ?></div>
        <div class="card-body">
          <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= h($CSRF) ?>">
            <input type="hidden" name="action" value="<?= $editRow?'update':'create' ?>">
            <?php if($editRow): ?><input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>"><?php endif; ?>

            <label class="form-label">Title <span style="color:#dc2626">*</span></label>
            <input class="input" type="text" name="title" maxlength="200" value="<?= h($editRow['title'] ?? '') ?>" required>

            <label class="form-label" style="margin-top:10px">Body <span style="color:#dc2626">*</span></label>
            <textarea class="textarea" name="body" required><?= h($editRow['body'] ?? '') ?></textarea>

            <label class="form-label" style="margin-top:10px">Media (PNG/JPG/JPEG/MP4/WEBM, max 10MB)</label>
            <input class="file" type="file" name="media" accept=".png,.jpg,.jpeg,.mp4,.webm">
            <?php if($editRow && $editRow['media_path']): ?>
              <div class="small" style="margin-top:6px">Current: <a href="<?= h($editRow['media_path']) ?>" target="_blank">view file</a></div>
            <?php endif; ?>

            <div class="form-check">
              <input class="checkbox" id="is_active" type="checkbox" name="is_active"
                     <?= $editRow ? ((int)$editRow['is_active']===1?'checked':'') : 'checked' ?>>
              <label class="form-check-label" for="is_active">Active</label>
            </div>

            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px">
              <button class="btn btn-primary" type="submit"><?= $editRow?'Update':'Create' ?></button>
              <?php if($editRow): ?>
                <a class="btn btn-secondary" href="settings-announcement.php">Cancel</a>
              <?php endif; ?>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- ============ List (Thread) ============ -->
    <div>
      <div class="card">
        <div class="card-header">All Announcements</div>
        <div class="card-body">
          <?php if (!$rows): ?>
            <div class="small">No announcements yet.</div>
          <?php else: foreach ($rows as $r): ?>
            <div class="card" style="margin-bottom:12px">
              <div class="card-body">
                <div style="display:flex;align-items:center;justify-content:space-between;gap:10px">
                  <h4 style="margin:0;font-size:16px"><?= h($r['title']) ?></h4>
                  <span class="badge <?= ((int)$r['is_active']===1?'badge-on':'badge-off') ?>">
                    <?= ((int)$r['is_active']===1?'Active':'Inactive') ?>
                  </span>
                </div>
                <div class="small" style="margin-top:4px">
                  By <?= h($r['created_name'] ?? 'System') ?> • <?= h($r['created_at']) ?>
                  <?php if(!empty($r['updated_at'])): ?> • updated <?= h($r['updated_at']) ?><?php endif; ?>
                </div>

                <div style="margin-top:8px"><?= nl2br(h($r['body'])) ?></div>

                <?php if (!empty($r['media_path'])): ?>
                  <?php if ($r['media_type'] === 'image'): ?>
                    <img src="<?= h($r['media_path']) ?>" class="thread-media" alt="media">
                  <?php elseif ($r['media_type'] === 'video'): ?>
                    <video class="thread-video" controls preload="metadata">
                      <source src="<?= h($r['media_path']) ?>">
                      Your browser does not support the video tag.
                    </video>
                  <?php endif; ?>
                <?php endif; ?>

                <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px">
                  <a href="settings-announcement.php?edit=<?= (int)$r['id'] ?>" class="btn btn-outline-primary">Edit</a>

                  <form method="post" onsubmit="return confirm('Toggle status for this announcement?');" style="display:inline">
                    <input type="hidden" name="csrf_token" value="<?= h($CSRF) ?>">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <input type="hidden" name="to" value="<?= ((int)$r['is_active']===1?0:1) ?>">
                    <button class="btn btn-outline-secondary" type="submit">
                      <?= ((int)$r['is_active']===1?'Set Inactive':'Set Active') ?>
                    </button>
                  </form>

                  <form method="post" onsubmit="return confirm('Delete this announcement? This cannot be undone.');" style="display:inline">
                    <input type="hidden" name="csrf_token" value="<?= h($CSRF) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-outline-danger" type="submit">Delete</button>
                  </form>
                </div>
              </div>
            </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- SweetAlert2 (flash gaya profile.php) -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function(){
  const type = <?=
    json_encode(isset($_GET['success']) ? 'success' : (isset($_GET['error']) ? 'error' : ''))
  ?>;
  const msg  = <?= json_encode($_GET['success'] ?? ($_GET['error'] ?? '')) ?>;
  if (!type || !msg) return;

  Swal.fire({
    toast: true,
    position: 'top-end',
    icon: type,
    title: msg,
    showConfirmButton: false,
    timer: 2800,
    timerProgressBar: true
  });
})();
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
