<?php
// app/Controllers/Berita.php  (BUKAN di app/Controllers/Admin/)

namespace App\Controllers;

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

class Berita extends BaseController
{
    public function detailById(int $id)
    {
        $model = new BeritaModel();
        $row = $model->find($id);

        if (!$row) {
            throw PageNotFoundException::forPageNotFound('Berita tidak ditemukan');
        }

        return view('berita_detail', ['row' => $row]);
    }

    public function detail(string $slug)
    {
        $model = new BeritaModel();
        $row = $model->where('slug', $slug)->first();

        if (!$row) {
            throw PageNotFoundException::forPageNotFound('Berita tidak ditemukan');
        }

        return view('berita_detail', ['row' => $row]);
    }
    public function download(string $slug)
    {
        $model = new BeritaModel();
        $row = $model->where('slug', $slug)->first();

        if (!$row || empty($row['gambar'])) {
            throw PageNotFoundException::forPageNotFound('File tidak ditemukan');
        }

        $path = ROOTPATH . 'public/uploads/berita/' . $row['gambar'];

        if (!is_file($path)) {
            throw PageNotFoundException::forPageNotFound('File tidak ditemukan');
        }

        // force download
        return $this->response->download($path, null);
    }

    public function downloadById(int $id)
    {
        $model = new BeritaModel();
        $row = $model->find($id);

        if (!$row || empty($row['gambar'])) {
            throw PageNotFoundException::forPageNotFound('File tidak ditemukan');
        }

        $path = ROOTPATH . 'public/uploads/berita/' . $row['gambar'];

        if (!is_file($path)) {
            throw PageNotFoundException::forPageNotFound('File tidak ditemukan');
        }

        return $this->response->download($path, null);
    }
}
