<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\TransactionModel;
use App\Models\ParticipantModel;
use App\Models\EventPackageModel;
use App\Models\EventModel;
use App\Models\ChurchModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use App\Libraries\PdfService;

class ParticipantReportController extends BaseController
{
    public function index()
    {
        $participantModel = new ParticipantModel();

        // Ambil semua input filter dari URL query string
        $filters = [
            'name'           => $this->request->getGet('name'),
            'phone'          => $this->request->getGet('phone'),
            'email'          => $this->request->getGet('email'),
            'church'         => $this->request->getGet('church'),
            'kta_number'     => $this->request->getGet('kta_number'),
            'birth_date'     => $this->request->getGet('birth_date'),
            'event_id'       => $this->request->getGet('event_id'),
            'payment_status' => $this->request->getGet('payment_status'),
            'start_date'     => $this->request->getGet('start_date'),
            'end_date'       => $this->request->getGet('end_date'),
            'qr_number'      => $this->request->getGet('qr_number'),
            'invoice_number' => $this->request->getGet('invoice_number'),
        ];

        $adminChurchIds = getAdminChurchIds(session()->get('user_id'));
        if ($adminChurchIds !== null) {
            $filters['admin_church_ids'] = $adminChurchIds;
        }
        $data['participants'] = $participantModel->search($filters);

        $churchQuery = new ChurchModel();
        if ($adminChurchIds !== null) {
            $churchQuery->whereIn('id', $adminChurchIds);
        }
        $data['churches'] = $churchQuery->findAll();

        $eventQuery = new EventModel(); // Inisialisasi model
        if ($adminChurchIds !== null) {
            $eventQuery->groupStart()
                       ->whereIn('church_id', $adminChurchIds)
                       ->orWhere('church_id IS NULL')
                       ->groupEnd();
        }
        $data['events'] = $eventQuery->findAll();
        $data['payment_status'] = get_database_enum_values('transactions','payment_status');

        $data['pager'] = $participantModel->pager;
        $data['filters'] = $filters;
        $data['pageTitle'] = lang('Admin/ParticipantReport.pageTitle');

        return view('backend/reports/participants/index', $data);
    }


    public function downloadTicket($participantId = null)
    {
        $participant = (new ParticipantModel())->find($participantId);
        if (!$participant) { return redirect()->back()->with('error', 'Participant not found.'); }

        $transaction = (new TransactionModel())->find($participant->transaction_id);
        if ($transaction->payment_status !== 'paid') {
            return redirect()->back()->with('error', 'Ticket can only be downloaded for paid transactions.');
        }

        // Kumpulkan data untuk view PDF
        $data = [
            'participant' => $participant,
            'event' => (new EventModel())->find($transaction->event_id),
            'package' => (new EventPackageModel())->find($participant->event_package_id),
        ];

        $pdfService = new PdfService();
        // Buat metode baru di PdfService untuk menangani ini
        return $pdfService->streamSingleTicket($data);
    }

    public function exportExcel()
    {
        $participantModel = new ParticipantModel();
        // Ambil SEMUA data yang cocok dengan filter, bukan hanya 1 halaman
        $filters = $this->request->getGet(); // Ambil semua parameter GET
        $participants = $participantModel->search($filters, 0); // 0 berarti tidak ada paginasi

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Tulis Header
        $sheet->setCellValue('A1', 'Name');
        $sheet->setCellValue('B1', 'Email');
        $sheet->setCellValue('C1', 'Phone');
        $sheet->setCellValue('D1', 'Event');
        $sheet->setCellValue('E1', 'Package');
        $sheet->setCellValue('F1', 'Church');
        $sheet->setCellValue('G1', 'KTA');
        $sheet->setCellValue('H1', 'Birth Date');
        $sheet->setCellValue('I1', 'QR Code');
        $sheet->setCellValue('J1', 'Status');
        
        // Tulis Data
        $row = 2;
        foreach ($participants as $p) {
            $sheet->setCellValue('A' . $row, $p->name);
            $sheet->setCellValue('B' . $row, $p->email);
            $sheet->setCellValue('C' . $row, $p->phone_number);
            $sheet->setCellValue('D' . $row, $p->event_name);
            $sheet->setCellValue('E' . $row, $p->package_name);
            $sheet->setCellValue('F' . $row, $p->church_db_name ?: $p->church_name);
            $sheet->setCellValue('G' . $row, $p->kta_number);
            $sheet->setCellValue('H' . $row, $p->birth_date);
            $sheet->setCellValue('I' . $row, $p->qr_number);
            $sheet->setCellValue('J' . $row, ucfirst($p->payment_status));
            $row++;
        }

        $writer = new Xlsx($spreadsheet);
        $timestamp = date('Ymd-His');
        $filename = 'participant_report_' . $timestamp . '.xlsx';

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $writer->save('php://output');
        exit();
    }

}