<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BeritaModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class Berita extends BaseController
{
    protected BeritaModel $beritaModel;

    public function __construct()
    {
        $this->beritaModel = new BeritaModel();
    }

    // =========================================================
    // HELPER: bikin slug unik (agar tidak error unique slug)
    // =========================================================
    private function makeUniqueSlug(string $base, ?int $ignoreId = null): string
    {
        helper('text');

        $slug = url_title($base, '-', true);
        if ($slug === '') $slug = 'item';

        $i = 0;
        while (true) {
            $candidate = $i === 0 ? $slug : $slug . '-' . $i;

            $q = $this->beritaModel->where('slug', $candidate);
            if ($ignoreId !== null) $q->where('id !=', $ignoreId);

            $exists = $q->first();
            if (!$exists) return $candidate;

            $i++;
        }
    }

    // =========================================================
    // HELPER: sisipkan tag cek kelulusan di konten (1x saja)
    // =========================================================
    private function injectKelulusanTag(string $konten, bool $enable): string
    {
        $tag = '[CEK_KELULUSAN]';
        $konten = (string)$konten;

        if ($enable) {
            if (stripos($konten, $tag) === false) {
                $konten = rtrim($konten) . "\n\n" . $tag;
            }
            return $konten;
        }

        $konten = str_ireplace($tag, '', $konten);
        return trim($konten);
    }

    /**
     * LIST pengumuman (admin)
     * URL: /admin/pengumuman
     */
    public function pengumuman()
    {
        $data = [
            'title'    => 'Pengumuman',
            'items'    => $this->beritaModel->getForAdmin('pengumuman', 10),
            'pager'    => $this->beritaModel->pager,
            'kategori' => 'pengumuman',
        ];

        return view('admin/berita/index', $data);
    }

    /**
     * FORM create pengumuman
     * URL: /admin/pengumuman/create
     */
    public function createPengumuman()
    {
        return view('admin/berita/form', [
            'title'    => 'Tambah Pengumuman',
            'item'     => null,
            'kategori' => 'pengumuman',
            'errors'   => session()->getFlashdata('errors') ?? [],
        ]);
    }

    /**
     * STORE pengumuman (POST)
     * URL: /admin/pengumuman/store
     */
    public function storePengumuman()
{
    // ===== UPLOAD GAMBAR (optional) =====
    $file = $this->request->getFile('gambar');
    $namaFile = null;

    if ($file && $file->isValid() && !$file->hasMoved()) {
        $allowed = ['image/jpg', 'image/jpeg', 'image/png', 'image/webp'];

        if (!in_array($file->getMimeType(), $allowed, true)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', ['gambar' => 'File harus berupa gambar (jpg/jpeg/png/webp).']);
        }

        $namaFile = $file->getRandomName();
        $file->move(ROOTPATH . 'public/uploads/berita', $namaFile);
    }

    // ===== SLUG UNIK =====
    $slugInput = trim((string)$this->request->getPost('slug'));
    $baseSlug  = $slugInput !== '' ? $slugInput : (string)$this->request->getPost('judul');
    $slug      = $this->makeUniqueSlug($baseSlug);

    // =========================================================
    // ✅ AMBIL KONTEN (FALLBACK name textarea) + SISIPKAN TOKEN
    // =========================================================
    $konten = (string) (
        $this->request->getPost('konten')
        ?? $this->request->getPost('konten_lengkap')
        ?? $this->request->getPost('isi')
        ?? $this->request->getPost('content')
        ?? $this->request->getPost('body')
        ?? ''
    );

    // checkbox yang kamu pakai di atas: embed_kelulusan
    $embedKelulusan = (int)($this->request->getPost('embed_kelulusan') ?? 0) === 1;

    // kalau admin mengetik token manual, jangan dihilangkan
    $hasToken = stripos($konten, '[CEK_KELULUSAN]') !== false || stripos($konten, '[cek_kelulusan]') !== false;

    if ($embedKelulusan || $hasToken) {
        // normalisasi token
        $konten = preg_replace('/\[cek_kelulusan\]/i', '[CEK_KELULUSAN]', $konten);

        // kalau belum ada token, tambahkan
        if (stripos($konten, '[CEK_KELULUSAN]') === false) {
            $konten .= "\n\n[CEK_KELULUSAN]\n";
        }
    } else {
        // kalau tidak embed, bersihkan token jika ada
        $konten = preg_replace('/\[cek_kelulusan\]/i', '', $konten);
    }

    $payload = [
        'judul'           => trim((string)$this->request->getPost('judul')),
        'slug'            => $slug,
        'kategori'        => 'pengumuman', // DIKUNCI
        'ringkasan'       => $this->request->getPost('ringkasan'),
        'konten'          => $konten, // ✅ yang sudah diproses
        'gambar'          => $namaFile,
        'penulis'         => $this->request->getPost('penulis'),
        'is_published'    => (int)($this->request->getPost('is_published') ?? 0),
        'tanggal_publish' => $this->request->getPost('tanggal_publish') ?: null,
    ];

    if (!$this->beritaModel->insert($payload)) {
        if ($namaFile && is_file(ROOTPATH . 'public/uploads/berita/' . $namaFile)) {
            @unlink(ROOTPATH . 'public/uploads/berita/' . $namaFile);
        }

        return redirect()->back()
            ->withInput()
            ->with('errors', $this->beritaModel->errors());
    }

    return redirect()->to('/admin/pengumuman')->with('success', 'Pengumuman berhasil ditambahkan.');
}

    /**
     * FORM edit pengumuman
     * URL: /admin/pengumuman/edit/{id}
     */
    public function editPengumuman(int $id)
    {
        $item = $this->beritaModel->find($id);

        if (!$item || $item['kategori'] !== 'pengumuman') {
            throw PageNotFoundException::forPageNotFound('Pengumuman tidak ditemukan.');
        }

        return view('admin/berita/form', [
            'title'    => 'Edit Pengumuman',
            'item'     => $item,
            'kategori' => 'pengumuman',
            'errors'   => session()->getFlashdata('errors') ?? [],
        ]);
    }

    /**
     * UPDATE pengumuman (POST)
     * URL: /admin/pengumuman/update/{id}
     */
    public function updatePengumuman(int $id)
    {
        $item = $this->beritaModel->find($id);
    
        if (!$item || $item['kategori'] !== 'pengumuman') {
            throw PageNotFoundException::forPageNotFound('Pengumuman tidak ditemukan.');
        }
    
        // ===== SLUG UNIK (update) =====
        $slugInput = trim((string)$this->request->getPost('slug'));
        $baseSlug  = $slugInput !== '' ? $slugInput : (string)$this->request->getPost('judul');
        $slug      = $this->makeUniqueSlug($baseSlug, $id);
    
        // ===== UPLOAD GAMBAR (optional) =====
        $file = $this->request->getFile('gambar');
        $namaFile = $item['gambar'] ?? null;
    
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $allowed = ['image/jpg', 'image/jpeg', 'image/png', 'image/webp'];
    
            if (!in_array($file->getMimeType(), $allowed, true)) {
                return redirect()->back()
                    ->withInput()
                    ->with('errors', ['gambar' => 'File harus berupa gambar (jpg/jpeg/png/webp).']);
            }
    
            $namaBaru = $file->getRandomName();
            $file->move(ROOTPATH . 'public/uploads/berita', $namaBaru);
    
            if (!empty($item['gambar']) && is_file(ROOTPATH . 'public/uploads/berita/' . $item['gambar'])) {
                @unlink(ROOTPATH . 'public/uploads/berita/' . $item['gambar']);
            }
    
            $namaFile = $namaBaru;
        }
    
        // =========================================================
        // ✅ AMBIL KONTEN (FALLBACK name textarea) + SISIPKAN TOKEN
        // =========================================================
        $konten = (string) (
            $this->request->getPost('konten')
            ?? $this->request->getPost('konten_lengkap')
            ?? $this->request->getPost('isi')
            ?? $this->request->getPost('content')
            ?? $this->request->getPost('body')
            ?? ''
        );
    
        $embedKelulusan = (int)($this->request->getPost('embed_kelulusan') ?? 0) === 1;
    
        $hasToken = stripos($konten, '[CEK_KELULUSAN]') !== false || stripos($konten, '[cek_kelulusan]') !== false;
    
        if ($embedKelulusan || $hasToken) {
            $konten = preg_replace('/\[cek_kelulusan\]/i', '[CEK_KELULUSAN]', $konten);
    
            if (stripos($konten, '[CEK_KELULUSAN]') === false) {
                $konten .= "\n\n[CEK_KELULUSAN]\n";
            }
        } else {
            $konten = preg_replace('/\[cek_kelulusan\]/i', '', $konten);
        }
    
        $payload = [
            'id'              => $id,
            'judul'           => trim((string)$this->request->getPost('judul')),
            'slug'            => $slug,
            'kategori'        => 'pengumuman',
            'ringkasan'       => $this->request->getPost('ringkasan'),
            'konten'          => $konten, // ✅ yang sudah diproses
            'gambar'          => $namaFile,
            'penulis'         => $this->request->getPost('penulis'),
            'is_published'    => (int)($this->request->getPost('is_published') ?? 0),
            'tanggal_publish' => $this->request->getPost('tanggal_publish') ?: null,
        ];
    
        if (!$this->beritaModel->update($id, $payload)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->beritaModel->errors());
        }
    
        return redirect()->to('/admin/pengumuman')->with('success', 'Pengumuman berhasil diupdate.');
    }
    

    /**
     * DELETE pengumuman
     * URL: /admin/pengumuman/delete/{id}
     */
    public function deletePengumuman(int $id)
    {
        $item = $this->beritaModel->find($id);

        if (!$item || $item['kategori'] !== 'pengumuman') {
            throw PageNotFoundException::forPageNotFound('Pengumuman tidak ditemukan.');
        }

        if (!empty($item['gambar']) && is_file(ROOTPATH . 'public/uploads/berita/' . $item['gambar'])) {
            @unlink(ROOTPATH . 'public/uploads/berita/' . $item['gambar']);
        }

        $this->beritaModel->delete($id);

        return redirect()->to('/admin/pengumuman')->with('success', 'Pengumuman berhasil dihapus.');
    }

    public function beritaImage($row)
    {
        if (!empty($row['gambar'])) return base_url('uploads/berita/' . $row['gambar']);
        return base_url('assets/images/default-berita.jpg');
    }

    // =========================================================
    // KEGIATAN
    // =========================================================
    public function kegiatan()
    {
        $data = [
            'title'    => 'Kegiatan',
            'items'    => $this->beritaModel->getForAdmin('kegiatan', 10),
            'pager'    => $this->beritaModel->pager,
            'kategori' => 'kegiatan',
        ];

        return view('admin/berita/kegiatan', $data);
    }

    public function createKegiatan()
    {
        return view('admin/berita/kegiatann', [
            'title'    => 'Tambah Kegiatan',
            'item'     => null,
            'kategori' => 'kegiatan',
            'errors'   => session()->getFlashdata('errors') ?? [],
        ]);
    }

    public function storeKegiatan()
    {
        $file = $this->request->getFile('gambar');
        $namaFile = null;

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $allowed = ['image/jpg', 'image/jpeg', 'image/png', 'image/webp'];
            if (!in_array($file->getMimeType(), $allowed, true)) {
                return redirect()->back()
                    ->withInput()
                    ->with('errors', ['gambar' => 'File harus berupa gambar (jpg/jpeg/png/webp).']);
            }

            $namaFile = $file->getRandomName();
            $file->move(ROOTPATH . 'public/uploads/berita', $namaFile);
        }

        // slug unik (biar tidak error)
        $slugInput = trim((string)$this->request->getPost('slug'));
        $baseSlug  = $slugInput !== '' ? $slugInput : (string)$this->request->getPost('judul');
        $slug      = $this->makeUniqueSlug($baseSlug);

        $payload = [
            'judul'           => trim((string)$this->request->getPost('judul')),
            'slug'            => $slug,
            'kategori'        => 'kegiatan',
            'ringkasan'       => $this->request->getPost('ringkasan'),
            'konten'          => $this->request->getPost('konten'),
            'gambar'          => $namaFile,
            'penulis'         => $this->request->getPost('penulis'),
            'is_published'    => (int)($this->request->getPost('is_published') ?? 0),
            'tanggal_publish' => $this->request->getPost('tanggal_publish') ?: null,
        ];

        if (!$this->beritaModel->insert($payload)) {
            if ($namaFile && is_file(ROOTPATH . 'public/uploads/berita/' . $namaFile)) {
                @unlink(ROOTPATH . 'public/uploads/berita/' . $namaFile);
            }
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->beritaModel->errors());
        }

        return redirect()->to('/admin/kegiatan')->with('success', 'Kegiatan berhasil ditambahkan.');
    }

    public function editKegiatan(int $id)
    {
        $item = $this->beritaModel->find($id);

        if (!$item || $item['kategori'] !== 'kegiatan') {
            throw PageNotFoundException::forPageNotFound('Kegiatan tidak ditemukan.');
        }

        return view('admin/berita/kegiatann', [
            'title'    => 'Edit Kegiatan',
            'item'     => $item,
            'kategori' => 'kegiatan',
            'errors'   => session()->getFlashdata('errors') ?? [],
        ]);
    }

    public function updateKegiatan(int $id)
    {
        $item = $this->beritaModel->find($id);

        if (!$item || $item['kategori'] !== 'kegiatan') {
            throw PageNotFoundException::forPageNotFound('Kegiatan tidak ditemukan.');
        }

        $file = $this->request->getFile('gambar');
        $namaFile = $item['gambar'] ?? null;

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $allowed = ['image/jpg', 'image/jpeg', 'image/png', 'image/webp'];
            if (!in_array($file->getMimeType(), $allowed, true)) {
                return redirect()->back()
                    ->withInput()
                    ->with('errors', ['gambar' => 'File harus berupa gambar (jpg/jpeg/png/webp).']);
            }

            $namaBaru = $file->getRandomName();
            $file->move(ROOTPATH . 'public/uploads/berita', $namaBaru);

            if (!empty($item['gambar']) && is_file(ROOTPATH . 'public/uploads/berita/' . $item['gambar'])) {
                @unlink(ROOTPATH . 'public/uploads/berita/' . $item['gambar']);
            }

            $namaFile = $namaBaru;
        }

        // slug unik saat update
        $slugInput = trim((string)$this->request->getPost('slug'));
        $baseSlug  = $slugInput !== '' ? $slugInput : (string)$this->request->getPost('judul');
        $slug      = $this->makeUniqueSlug($baseSlug, $id);

        $payload = [
            'id'              => $id,
            'judul'           => trim((string)$this->request->getPost('judul')),
            'slug'            => $slug,
            'kategori'        => 'kegiatan',
            'ringkasan'       => $this->request->getPost('ringkasan'),
            'konten'          => $this->request->getPost('konten'),
            'gambar'          => $namaFile,
            'penulis'         => $this->request->getPost('penulis'),
            'is_published'    => (int)($this->request->getPost('is_published') ?? 0),
            'tanggal_publish' => $this->request->getPost('tanggal_publish') ?: null,
        ];

        if (!$this->beritaModel->update($id, $payload)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->beritaModel->errors());
        }

        return redirect()->to('/admin/kegiatan')->with('success', 'Kegiatan berhasil diupdate.');
    }

    public function deleteKegiatan(int $id)
    {
        $item = $this->beritaModel->find($id);

        if (!$item || $item['kategori'] !== 'kegiatan') {
            throw PageNotFoundException::forPageNotFound('Kegiatan tidak ditemukan.');
        }

        if (!empty($item['gambar']) && is_file(ROOTPATH . 'public/uploads/berita/' . $item['gambar'])) {
            @unlink(ROOTPATH . 'public/uploads/berita/' . $item['gambar']);
        }

        $this->beritaModel->delete($id);

        return redirect()->to('/admin/kegiatan')->with('success', 'Kegiatan berhasil dihapus.');
    }

    // =========================================================
    // PRESTASI
    // =========================================================
    public function prestasi()
    {
        $data = [
            'title'    => 'Prestasi',
            'items'    => $this->beritaModel->getForAdmin('prestasi', 10),
            'pager'    => $this->beritaModel->pager,
            'kategori' => 'prestasi',
        ];
        return view('admin/berita/prestasi', $data);
    }

    public function createPrestasi()
    {
        return view('admin/berita/prestasii', [
            'title'    => 'Tambah Prestasi',
            'item'     => null,
            'kategori' => 'prestasi',
            'errors'   => session()->getFlashdata('errors') ?? [],
        ]);
    }

    public function storePrestasi()
    {
        $file = $this->request->getFile('gambar');
        $namaFile = null;

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $allowed = ['image/jpg', 'image/jpeg', 'image/png', 'image/webp'];
            if (!in_array($file->getMimeType(), $allowed, true)) {
                return redirect()->back()->withInput()->with('errors', ['gambar' => 'File harus berupa gambar (jpg/jpeg/png/webp).']);
            }
            $namaFile = $file->getRandomName();
            $file->move(ROOTPATH . 'public/uploads/berita', $namaFile);
        }

        // slug unik
        $slugInput = trim((string)$this->request->getPost('slug'));
        $baseSlug  = $slugInput !== '' ? $slugInput : (string)$this->request->getPost('judul');
        $slug      = $this->makeUniqueSlug($baseSlug);

        $payload = [
            'judul'           => trim((string)$this->request->getPost('judul')),
            'slug'            => $slug,
            'kategori'        => 'prestasi',
            'ringkasan'       => $this->request->getPost('ringkasan'),
            'konten'          => $this->request->getPost('konten'),
            'gambar'          => $namaFile,
            'penulis'         => $this->request->getPost('penulis'),
            'is_published'    => (int)($this->request->getPost('is_published') ?? 0),
            'tanggal_publish' => $this->request->getPost('tanggal_publish') ?: null,
        ];

        if (!$this->beritaModel->insert($payload)) {
            if ($namaFile && is_file(ROOTPATH . 'public/uploads/berita/' . $namaFile)) {
                @unlink(ROOTPATH . 'public/uploads/berita/' . $namaFile);
            }
            return redirect()->back()->withInput()->with('errors', $this->beritaModel->errors());
        }

        return redirect()->to('/admin/prestasi')->with('success', 'Prestasi berhasil ditambahkan.');
    }

    public function editPrestasi(int $id)
    {
        $item = $this->beritaModel->find($id);
        if (!$item || $item['kategori'] !== 'prestasi') {
            throw PageNotFoundException::forPageNotFound('Prestasi tidak ditemukan.');
        }

        return view('admin/berita/prestasii', [
            'title'    => 'Edit Prestasi',
            'item'     => $item,
            'kategori' => 'prestasi',
            'errors'   => session()->getFlashdata('errors') ?? [],
        ]);
    }

    public function updatePrestasi(int $id)
    {
        $item = $this->beritaModel->find($id);
        if (!$item || $item['kategori'] !== 'prestasi') {
            throw PageNotFoundException::forPageNotFound('Prestasi tidak ditemukan.');
        }

        $file = $this->request->getFile('gambar');
        $namaFile = $item['gambar'] ?? null;

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $allowed = ['image/jpg', 'image/jpeg', 'image/png', 'image/webp'];
            if (!in_array($file->getMimeType(), $allowed, true)) {
                return redirect()->back()->withInput()->with('errors', ['gambar' => 'File harus berupa gambar (jpg/jpeg/png/webp).']);
            }

            $namaBaru = $file->getRandomName();
            $file->move(ROOTPATH . 'public/uploads/berita', $namaBaru);

            if (!empty($item['gambar']) && is_file(ROOTPATH . 'public/uploads/berita/' . $item['gambar'])) {
                @unlink(ROOTPATH . 'public/uploads/berita/' . $item['gambar']);
            }

            $namaFile = $namaBaru;
        }

        // slug unik saat update
        $slugInput = trim((string)$this->request->getPost('slug'));
        $baseSlug  = $slugInput !== '' ? $slugInput : (string)$this->request->getPost('judul');
        $slug      = $this->makeUniqueSlug($baseSlug, $id);

        $payload = [
            'id'              => $id,
            'judul'           => trim((string)$this->request->getPost('judul')),
            'slug'            => $slug,
            'kategori'        => 'prestasi',
            'ringkasan'       => $this->request->getPost('ringkasan'),
            'konten'          => $this->request->getPost('konten'),
            'gambar'          => $namaFile,
            'penulis'         => $this->request->getPost('penulis'),
            'is_published'    => (int)($this->request->getPost('is_published') ?? 0),
            'tanggal_publish' => $this->request->getPost('tanggal_publish') ?: null,
        ];

        if (!$this->beritaModel->update($id, $payload)) {
            return redirect()->back()->withInput()->with('errors', $this->beritaModel->errors());
        }

        return redirect()->to('/admin/prestasi')->with('success', 'Prestasi berhasil diupdate.');
    }

    public function deletePrestasi(int $id)
    {
        $item = $this->beritaModel->find($id);
        if (!$item || $item['kategori'] !== 'prestasi') {
            throw PageNotFoundException::forPageNotFound('Prestasi tidak ditemukan.');
        }

        if (!empty($item['gambar']) && is_file(ROOTPATH . 'public/uploads/berita/' . $item['gambar'])) {
            @unlink(ROOTPATH . 'public/uploads/berita/' . $item['gambar']);
        }

        $this->beritaModel->delete($id);
        return redirect()->to('/admin/prestasi')->with('success', 'Prestasi berhasil dihapus.');
    }
}
