<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\DocumentModel;
use App\Models\StudyProgramModel;
use App\Models\DocumentTypeModel;

class ReportController extends BaseController
{
    public function index()
    {
        $programs = model(StudyProgramModel::class)->orderBy('name')->findAll();
        $types    = model(DocumentTypeModel::class)->findAll();

        return view('admin/reports/index', [
            'title'    => 'Laporan & Ekspor',
            'programs' => $programs,
            'types'    => $types,
        ]);
    }

    public function export()
    {
        $program  = $this->request->getGet('program');
        $type     = $this->request->getGet('type');
        $year_from = $this->request->getGet('year_from');
        $year_to   = $this->request->getGet('year_to');
        $format    = $this->request->getGet('format') ?? 'csv';

        $builder = db_connect()->table('documents d')
            ->select('d.title, d.author_name, d.nim, sp.name AS study_program, dt.name AS document_type,
                      d.year, d.supervisor, d.keywords, d.citations_count, d.view_count, d.download_count,
                      d.published_at')
            ->join('document_types dt', 'dt.id = d.document_type_id')
            ->join('study_programs sp', 'sp.id = d.study_program_id', 'left')
            ->where('d.status', 'published');

        if ($program) $builder->where('d.study_program_id', $program);
        if ($type)    $builder->where('d.document_type_id', $type);
        if ($year_from) $builder->where('d.year >=', (int) $year_from);
        if ($year_to)   $builder->where('d.year <=', (int) $year_to);

        $rows = $builder->orderBy('d.year', 'DESC')->orderBy('d.title', 'ASC')->get()->getResultArray();

        $filename = 'repositori_stt_' . date('Ymd');

        $headers = ['Judul', 'Penulis', 'NIM', 'Program Studi', 'Jenis', 'Tahun',
                    'Pembimbing', 'Kata Kunci', 'Dikutip', 'Dilihat', 'Diunduh', 'Tanggal Terbit'];

        return $this->streamCsv($filename, $headers, $rows);
    }

    private function streamCsv(string $filename, array $headers, array $rows)
    {
        $output = fopen('php://temp', 'r+');

        // BOM for Excel UTF-8
        fputs($output, "\xEF\xBB\xBF");
        fputcsv($output, $headers);

        foreach ($rows as $row) {
            fputcsv($output, array_values($row));
        }

        rewind($output);
        $csv = stream_get_contents($output);
        fclose($output);

        return $this->response
            ->setHeader('Content-Type', 'text/csv; charset=UTF-8')
            ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '.csv"')
            ->setHeader('Cache-Control', 'no-store')
            ->setBody($csv);
    }
}
