<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\PayPalPaymentModel;
use App\Models\PaymentModel;
use App\Models\UserModel;
use App\Models\ConfigurationModel;
use App\Models\InvoiceModel;

class PaypalTransactionsController extends BaseController
{
    public function index()
    {
        $model = new PayPalPaymentModel();

        $keyword = $this->request->getGet('q');
        $perPage = 10;

        if ($keyword) {
            $transactions = $model
                ->groupStart()
                    ->like('transaction_id', $keyword)
                    ->orLike('payer_email', $keyword)
                    ->orLike('event_type', $keyword)
                    ->orLike('order_id', $keyword)
                    ->orLike('parent_school_id', $keyword)
                ->groupEnd()
                ->orderBy('created_at', 'DESC')
                ->paginate($perPage);
        } else {
            $transactions = $model
                ->orderBy('created_at', 'DESC')
                ->paginate($perPage);
        }

        return view('administrator/paypal_transactions', [
            'transactions' => $transactions,
            'pager' => $model->pager,
            'keyword' => $keyword
        ]);
    }

    public function exportCsv()
    {
        $model = new PayPalPaymentModel();
        $keyword = $this->request->getGet('q');

        if ($keyword) {
            $transactions = $model
                ->groupStart()
                    ->like('transaction_id', $keyword)
                    ->orLike('payer_email', $keyword)
                    ->orLike('event_type', $keyword)
                    ->orLike('order_id', $keyword)
                    ->orLike('parent_school_id', $keyword)
                ->groupEnd()
                ->orderBy('created_at', 'DESC')
                ->findAll();
        } else {
            $transactions = $model->orderBy('created_at', 'DESC')->findAll();
        }

        $filename = 'paypal_transactions_' . date('Ymd_His') . '.csv';

        header('Content-Type: text/csv');
        header("Content-Disposition: attachment; filename=\"$filename\"");

        $output = fopen('php://output', 'w');

        // CSV headers
        fputcsv($output, [
            'ID', 'Transaction ID', 'Order ID', 'Parent School ID',
            'Email', 'Amount', 'Net Amount', 'Currency',
            'Status', 'Event Type', 'Created At'
        ]);

        foreach ($transactions as $t) {
            fputcsv($output, [
                $t['id'],
                $t['transaction_id'],
                $t['order_id'],
                $t['parent_school_id'],
                $t['payer_email'],
                $t['amount'],
                $t['net_amount'],
                $t['currency'],
                $t['status'],
                $t['event_type'],
                $t['created_at'],
            ]);
        }

        fclose($output);
        exit;
    }

}
