<?php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Libraries\BulkRegistrationService;
use App\Models\BulkTransactionModel;
use App\Models\BulkTemporaryParticipantModel;
use App\Models\EventModel;
use App\Models\EventPackageModel;
use App\Models\UserModel;
use App\Models\ChurchModel;

class BulkTransactionsController extends BaseController
{
    /**
     * Menampilkan halaman daftar riwayat upload massal.
     */
    public function index()
    {
        $bulkModel = new BulkTransactionModel();
        
        $data = [
            'uploads' => $bulkModel->select('bulk_transactions.*, events.name as event_name, users.name as user_name')
                                   ->join('events', 'events.id = bulk_transactions.event_id', 'left')
                                   ->join('users', 'users.id = bulk_transactions.user_id', 'left')
                                   ->orderBy('bulk_transactions.created_at', 'DESC')
                                   ->paginate(10),
            'pager'     => $bulkModel->pager,
            'pageTitle' => lang('Admin/BulkTransactions.pageTitle'),
        ];

        return view('backend/bulk_transactions/index', $data);
    }
    
    /**
     * Menampilkan form untuk upload pendaftaran massal baru.
     */
    public function new()
    {
        $eventModel = new EventModel();
        $data = [
            'churches' => (new ChurchModel())->where('is_active', 1)->orderBy('sort_order', 'ASC')->findAll(),
            'events' => $eventModel->where('is_active', 1)->where('end_date >=', date('Y-m-d'))->findAll(),
            'pageTitle' => lang('Admin/BulkTransactions.formHeader'),
        ];
        return view('backend/bulk_transactions/new', $data);
    }

    /**
     * Memproses upload file dan menyimpan data header.
     */
    public function create()
    {
        if (!$this->validate($this->getFormRules())) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }
        
        $excelFile = $this->request->getFile('excel_file');
        if (!$excelFile->isValid() || $excelFile->hasMoved()) {
            return redirect()->back()->withInput()->with('error', 'Invalid file upload.');
        }
        
        $newName = $excelFile->getRandomName();
        $excelFile->move(WRITEPATH . 'uploads/bulk_excel', $newName);
        
        $db = \Config\Database::connect();
        $db->transStart();
        
        $eventId = $this->request->getPost('event_id');
        $invoice = $this->request->getPost('invoice_number');
        if (empty($invoice)) {
            $counter = (new BulkTransactionModel())->where('event_id', $eventId)->where('DATE(created_at)', date('Y-m-d'))->countAllResults() + 1;
            $invoice = 'INT\\' . $eventId . '\\' . date('dmy') . '\\' . str_pad($counter, 3, '0', STR_PAD_LEFT);
        }
        
        $bulkTrxModel = new BulkTransactionModel();
        $bulkTrxId = $bulkTrxModel->insert([
            'event_id'         => $eventId,
            'user_id'          => $this->request->getPost('user_id'),
            'church_id'        => $this->request->getPost('church_id'),
            'transaction_date' => $this->request->getPost('transaction_date'),
            'payment_type'     => $this->request->getPost('payment_type'),
            'event_package_id' => $this->request->getPost('event_package_id'),
            'invoice_number'   => $invoice,
            'description'      => $this->request->getPost('description'),
            'excel_path'       => $newName,
            'process_status'   => 'Processing', // Status awal yang benar
            'created_by'       => session()->get('user_id'),
        ]);

        // Panggil service untuk membaca Excel dan mengisi tabel temporer
        $processor = new BulkRegistrationService();
        $queuedCount = $processor->readAndQueueParticipants(
            WRITEPATH . 'uploads/bulk_excel/' . $newName, 
            $bulkTrxId, 
            (int)$this->request->getPost('church_id')
        );
        
        // Update total_quantity dengan jumlah baris yang berhasil dibaca
        $bulkTrxModel->update($bulkTrxId, ['total_quantity' => $queuedCount]);

        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->withInput()->with('error', lang('Admin/BulkTransactions.errorSave'));
        }
        
        return redirect()->to(route_to('admin.bulk.index'))->with('success', $queuedCount . ' participants have been queued for validation.');
    }
    
    // Anda akan memerlukan metode 'show' untuk menampilkan halaman hasil
    public function show($id = null)
    {
        $bulkTrxModel = new BulkTransactionModel();
        $bulkTrx = $bulkTrxModel->find($id);

        if (!$bulkTrx) {
            return redirect()->route('admin.bulk.index')->with('error', lang('Admin/BulkTransactions.errorNotFound'));
        }
        
        $tempParticipantsModel = new BulkTemporaryParticipantModel();
        $tempParticipants = $tempParticipantsModel->where('bulk_transaction_id', $id)->findAll();
        
        $decodedErrors = json_decode($bulkTrx->process_result, true);
        $errors = is_array($decodedErrors) ? $decodedErrors : [];
        
        // Tetap tampilkan halaman meskipun tidak ada peserta
        $totalRows = count($tempParticipants); 
        $validRows = (int) $bulkTrx->total_quantity;
        $invalidRows = count($errors);

        $data = [
            'bulkTransaction' => $bulkTrx,
            'event'        => (new EventModel())->find($bulkTrx->event_id),
            'package'      => (new EventPackageModel())->find($bulkTrx->event_package_id),
            'user'         => (new UserModel())->find($bulkTrx->user_id),
            'church'       => (new ChurchModel())->find($bulkTrx->church_id),
            'tempParticipants' => $tempParticipants,
            'totalRows'    => $totalRows,
            'validRows'    => $validRows,
            'invalidRows'  => $invalidRows,
            'errors'       => $errors,
            'pageTitle'    => lang('Admin/BulkTransactions.resultHeader', [esc($bulkTrx->excel_path)])
        ];

        return view('backend/bulk_transactions/show_result', $data);
    }

    private function getFormRules(): array
    {
        return [
            'event_id'         => 'required|is_natural_no_zero',
            'user_id'          => 'required|is_natural_no_zero',
            'church_id'        => 'required|is_natural_no_zero',
            'transaction_date' => 'required|valid_date',
            'payment_type'     => 'required|in_list[cash,transfer]',
            'event_package_id' => 'required|is_natural_no_zero',
            'excel_file'       => 'uploaded[excel_file]|max_size[excel_file,5120]|ext_in[excel_file,xlsx,xls]',
        ];
    }

    public function delete($id = null)
    {
        $bulkModel = new BulkTransactionModel();
        $bulkTrx = $bulkModel->find($id);

        if (!$bulkTrx) {
            return redirect()->route('admin.bulk.index')->with('error', 'Bulk transaction not found.');
        }

        // Update status dan lakukan soft delete
        $bulkModel->update($id, ['process_status' => 'Deleted']);
        $bulkModel->delete($id);

        return redirect()->to(route_to('admin.bulk.index'))->with('success', 'Bulk upload has been successfully canceled and moved to trash.');
    }

    public function process($id = null)
    {
        $service = new BulkRegistrationService();
        $result = $service->processValidatedParticipants((int)$id);

        if ($result['success']) {
            return redirect()->to(route_to('admin.bulk.show', $id))->with('success', $result['message']);
        }

        return redirect()->to(route_to('admin.bulk.show', $id))->with('error', $result['message']);
    }
}