<?php

namespace App\Controllers;

use App\Models\DokumenModel;
use setasign\Fpdi\Fpdi;

class Arsip extends BaseController
{
    protected $dokumenModel;

    public function __construct()
    {
        $this->dokumenModel = new DokumenModel();
    }

    // --- FUNGSI GEMBOK LEVEL ---
    private function cekHakAkses()
    {
        if (session()->get('role') != 'Admin' && session()->get('role') != 'Kepala Seksi') {
            echo "<script>alert('Akses Ditolak! Level Anda tidak diizinkan mengubah arsip.'); window.location.href='".base_url('arsip')."';</script>";
            exit;
        }
    }

    public function index()
    {
        $data = [
            'title' => 'Arsip Dokumen - KPH III Asahan',
            'dokumen' => $this->dokumenModel->orderBy('id_dokumen', 'DESC')->findAll()
        ];
        return view('arsip', $data);
    }

    public function tambah()
    {
        $this->cekHakAkses(); // Pintu Terkunci
        $data = ['title' => 'Unggah Dokumen - KPH III Asahan'];
        return view('tambah_dokumen', $data);
    }

    public function simpan()
    {
        $this->cekHakAkses(); // Pintu Terkunci
        $fileDokumen = $this->request->getFile('file_dokumen');
        $namaFile = $fileDokumen->getRandomName();
        $fileDokumen->move('uploads/dokumen', $namaFile);

        $this->dokumenModel->save([
            'judul_dokumen'  => $this->request->getPost('judul_dokumen'),
            'kategori'       => $this->request->getPost('kategori'),
            'nama_file'      => $namaFile,
            'tanggal_upload' => date('Y-m-d')
        ]);
        return redirect()->to('/arsip');
    }

    public function edit($id_dokumen)
    {
        $this->cekHakAkses(); // Pintu Terkunci
        $data = [
            'title' => 'Edit Dokumen - KPH III Asahan',
            'dokumen_edit' => $this->dokumenModel->find($id_dokumen)
        ];
        return view('tambah_dokumen', $data);
    }

    public function update($id_dokumen)
    {
        $this->cekHakAkses(); // Pintu Terkunci
        $dokumenLama = $this->dokumenModel->find($id_dokumen);
        $fileDokumen = $this->request->getFile('file_dokumen');
        
        $namaFile = $dokumenLama['nama_file']; 

        if ($fileDokumen->isValid() && !$fileDokumen->hasMoved()) {
            $namaFile = $fileDokumen->getRandomName();
            $fileDokumen->move('uploads/dokumen', $namaFile);
            
            if (file_exists('uploads/dokumen/' . $dokumenLama['nama_file'])) {
                unlink('uploads/dokumen/' . $dokumenLama['nama_file']);
            }
        }

        $this->dokumenModel->update($id_dokumen, [
            'judul_dokumen'  => $this->request->getPost('judul_dokumen'),
            'kategori'       => $this->request->getPost('kategori'),
            'nama_file'      => $namaFile
        ]);
        return redirect()->to('/arsip');
    }

    public function hapus($id_dokumen)
    {
        $this->cekHakAkses(); // Pintu Terkunci
        $dokumen = $this->dokumenModel->find($id_dokumen);
        if ($dokumen) {
            $lokasi_file = 'uploads/dokumen/' . $dokumen['nama_file'];
            if (file_exists($lokasi_file)) {
                unlink($lokasi_file);
            }
            $this->dokumenModel->delete($id_dokumen);
        }
        return redirect()->to('/arsip');
    }

    // --- FUNGSI DOWNLOAD (SEMUA LEVEL BISA AKSES) ---
    public function download($id_dokumen)
    {
        $dokumen = $this->dokumenModel->find($id_dokumen);
        if ($dokumen) {
            $lokasi_file = 'uploads/dokumen/' . $dokumen['nama_file'];
            if (file_exists($lokasi_file)) {
                $ekstensi = strtolower(pathinfo($lokasi_file, PATHINFO_EXTENSION));

                if ($ekstensi == 'pdf') {
                    $nama_staf = session()->get('nama_lengkap');
                    $waktu_unduh = date('d/m/Y H:i');
                    $teks_watermark = 'DOKUMEN INTERNAL KPH III | DIUNDUH OLEH: ' . strtoupper($nama_staf) . ' (' . $waktu_unduh . ')';

                    $pdf = new Fpdi();
                    $jumlahHalaman = $pdf->setSourceFile($lokasi_file);

                    for ($halaman = 1; $halaman <= $jumlahHalaman; $halaman++) {
                        $templateId = $pdf->importPage($halaman);
                        $ukuran = $pdf->getTemplateSize($templateId);
                        
                        $orientasi = $ukuran['width'] > $ukuran['height'] ? 'L' : 'P';
                        $pdf->AddPage($orientasi, [$ukuran['width'], $ukuran['height']]);
                        $pdf->useTemplate($templateId);

                        $pdf->SetFont('Arial', 'B', 12);
                        $pdf->SetTextColor(255, 50, 50); 
                        
                        $pdf->SetXY(0, 10);
                        $pdf->Cell($ukuran['width'], 10, $teks_watermark, 0, 0, 'C');

                        $pdf->SetXY(0, $ukuran['height'] - 15);
                        $pdf->Cell($ukuran['width'], 10, $teks_watermark, 0, 0, 'C');
                    }

                    $nama_file_baru = 'Aman_' . $dokumen['judul_dokumen'] . '.pdf';
                    
                    header('Content-Type: application/pdf');
                    header('Content-Disposition: attachment; filename="'.$nama_file_baru.'"');
                    $pdf->Output('D', $nama_file_baru);
                    exit();
                } else {
                    return $this->response->download($lokasi_file, null)->setFileName($dokumen['judul_dokumen'] . '.' . $ekstensi);
                }
            } else {
                echo "<script>alert('Maaf, file fisik tidak ditemukan di server.'); window.location.href='".base_url('arsip')."';</script>";
            }
        }
    }
}