<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use Dompdf\Dompdf;
use Dompdf\Options;

class Formulir extends BaseController
{
    protected $modelPengajuanCuti;

    public function __construct()
    {
        $this->modelPengajuanCuti = new \App\Models\ModelPengajuanCuti();
    }

    public function cetak($id)
    {
        $data = $this->modelPengajuanCuti->getDataByIdCetak($id);

        if (!$data) {
            return redirect()->back()->with('error', 'Data tidak ditemukan.');
        }

        // Cek status
        if ($data['status_supervisor'] !== 'disetujui' || $data['status_manager'] !== 'disetujui') {
            return redirect()->back()->with('error', 'Maaf, pengajuan cuti belum disetujui oleh supervisor dan manager.');
        }

        // Update status_admin jika masih pending
        if ($data['status_admin'] === 'pending') {
            $this->modelPengajuanCuti->update($id, ['status_admin' => 'dicetak']);
        }

        // Ambil settings instansi
        $settingModel = new \App\Models\SettingsModel();
        $settings = $settingModel->first(); // Ambil data settings, asumsinya hanya 1 baris

        $userModel = new \App\Models\ModelUser();

        // Ambil user (pengaju cuti)
        $user = $userModel->find($data['id_user']);

        // Ambil supervisor dan manager
        $supervisor = $user && !empty($user['id_atasan']) ? $userModel->find($user['id_atasan']) : null;
        $manager = $supervisor && !empty($supervisor['id_atasan']) ? $userModel->find($supervisor['id_atasan']) : null;

        // Ambil histori cuti user
        $historiCuti = $this->modelPengajuanCuti
            ->where('id_user', $data['id_user'])
            ->where('id !=', $id) // agar pengajuan yang sedang dicetak tidak ikut
            ->orderBy('tanggal_mulai', 'DESC')
            ->findAll();

        // Siapkan dompdf dengan opsi remote image
        $options = new Options();
        $options->set('isRemoteEnabled', true); // WAJIB agar logo dari base_url bisa dimuat
        $dompdf = new Dompdf($options);

        // Load view untuk cetak
        $html = view('formulir/cetak', [
            'data' => $data,
            'settings' => $settings,
            'supervisor' => $supervisor,
            'manager'    => $manager,
            'historiCuti' => $historiCuti,

        ]);

        $dompdf->loadHtml($html);
        // $dompdf->setPaper('F4', 'portrait');
        $customPaper = [0, 0, 595.276, 935.433]; // 210mm × 330mm
        $dompdf->setPaper($customPaper, 'portrait');
        $dompdf->render();

        // Penting: tidak boleh ada echo / spasi / HTML sebelum ini
        $dompdf->stream('formulir_cuti_' . $data['nama'] . '.pdf', ['Attachment' => false]);
        exit(); // paksa keluar supaya tidak ada output tambahan
    }

    public function cekStatus($id)
    {
        $data = $this->modelPengajuanCuti->getDataByIdCetak($id);

        if (!$data) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Data tidak ditemukan.']);
        }

        if ($data['status_supervisor'] === 'disetujui' && $data['status_manager'] === 'disetujui') {
            return $this->response->setJSON(['status' => 'ok']);
        } else {
            return $this->response->setJSON([
                'status' => 'pending',
                'message' => 'Pengajuan belum disetujui oleh Supervisor dan/atau Manager.'
            ]);
        }
    }

    public function download($id)
    {
        $data = $this->modelPengajuanCuti->getDataByIdCetak($id);

        if (!$data) {
            return redirect()->back()->with('error', 'Data tidak ditemukan.');
        }

        // Cek status
        if ($data['status_supervisor'] !== 'disetujui' || $data['status_manager'] !== 'disetujui') {
            return redirect()->back()->with('error', 'Maaf, pengajuan cuti belum disetujui oleh supervisor dan manager.');
        }

        // Update status_admin jika masih pending
        if ($data['status_admin'] === 'pending') {
            $this->modelPengajuanCuti->update($id, ['status_admin' => 'dicetak']);
        }

        // Ambil settings instansi
        $settingModel = new \App\Models\SettingsModel();
        $settings = $settingModel->first(); // Ambil data settings, asumsinya hanya 1 baris

        $userModel = new \App\Models\ModelUser();

        // Ambil user (pengaju cuti)
        $user = $userModel->find($data['id_user']);

        // Ambil supervisor dan manager
        $supervisor = $user && !empty($user['id_atasan']) ? $userModel->find($user['id_atasan']) : null;
        $manager = $supervisor && !empty($supervisor['id_atasan']) ? $userModel->find($supervisor['id_atasan']) : null;

        // Ambil histori cuti user
        $historiCuti = $this->modelPengajuanCuti
            ->where('id_user', $data['id_user'])
            ->where('id !=', $id) // agar pengajuan yang sedang dicetak tidak ikut
            ->orderBy('tanggal_mulai', 'DESC')
            ->findAll();

        // Siapkan dompdf dengan opsi remote image
        $options = new Options();
        $options->set('isRemoteEnabled', true); // WAJIB agar logo dari base_url bisa dimuat
        $dompdf = new Dompdf($options);

        // Load view untuk cetak
        $html = view('formulir/download', [
            'data' => $data,
            'settings' => $settings,
            'supervisor' => $supervisor,
            'manager'    => $manager,
            'historiCuti' => $historiCuti,

        ]);

        $dompdf->loadHtml($html);
        // $dompdf->setPaper('F4', 'portrait');
        $customPaper = [0, 0, 595.276, 935.433]; // 210mm × 330mm
        $dompdf->setPaper($customPaper, 'portrait');
        $dompdf->render();

        // Penting: tidak boleh ada echo / spasi / HTML sebelum ini
        $dompdf->stream('formulir_cuti_' . $data['nama'] . '.pdf', ['Attachment' => false]);
        exit(); // paksa keluar supaya tidak ada output tambahan
    }

    public function downloadWord($id)
    {
        $data = $this->modelPengajuanCuti->getDataByIdCetak($id);

        if (!$data) {
            return redirect()->back()->with('error', 'Data tidak ditemukan.');
        }

        // Cek status supervisor & manager
        if ($data['status_supervisor'] !== 'disetujui' || $data['status_manager'] !== 'disetujui') {
            return redirect()->back()->with('error', 'Maaf, pengajuan cuti belum disetujui oleh supervisor dan manager.');
        }

        // Update status_admin jika masih pending
        if ($data['status_admin'] === 'pending') {
            $this->modelPengajuanCuti->update($id, ['status_admin' => 'dicetak']);
        }

        // Ambil settings
        $settingModel = new \App\Models\SettingsModel();
        $settings = $settingModel->first();

        // Ambil data user, supervisor dan manager
        $userModel = new \App\Models\ModelUser();
        $user = $userModel->find($data['id_user']);
        $supervisor = $user && !empty($user['id_atasan']) ? $userModel->find($user['id_atasan']) : null;
        $manager = $supervisor && !empty($supervisor['id_atasan']) ? $userModel->find($supervisor['id_atasan']) : null;

        // Ambil histori cuti user
        $historiCuti = $this->modelPengajuanCuti
            ->where('id_user', $data['id_user'])
            ->where('id !=', $id) // agar pengajuan yang sedang dicetak tidak ikut
            ->orderBy('tanggal_mulai', 'DESC')
            ->findAll();

        // Render view ke HTML
        $html = view('formulir/download_word', [
            'data' => $data,
            'settings' => $settings,
            'supervisor' => $supervisor,
            'manager' => $manager,
            'historiCuti' => $historiCuti
        ]);

        // Buat header untuk Word document
        header("Content-type: application/vnd.ms-word");
        header("Content-Disposition: attachment;Filename=formulir_cuti_{$data['nama']}.doc");
        header("Pragma: no-cache");
        header("Expires: 0");

        echo $html;
        exit();
    }
}
