<?php
namespace App\Controllers\PPDB;

use App\Controllers\BaseController;
use App\Models\PPDBPaymentModel;
use App\Models\PpdbModel;

class Payment extends BaseController
{
    protected $paymentModel;
    protected $studentModel;

    public function __construct()
    {
        $this->paymentModel = new PPDBPaymentModel();
        $this->studentModel = new PpdbModel();
    }

    public function index()
    {
        $payments = $this->paymentModel->orderBy('id', 'DESC')->findAll();

        // Gabungkan data siswa
        foreach ($payments as &$p) {
            $student = $this->studentModel->find($p['student_id']);
            $p['student_name'] = $student ? $student['name'] : '-';
            $p['reg_no'] = $student ? $student['reg_no'] : '-';
        }

        return view('ppdb/payment/index', ['payments' => $payments]);
    }

    public function detail($id)
    {
        $payment = $this->paymentModel->find($id);
        if (!$payment) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        return view('ppdb/payment/detail', ['payment' => $payment]);
    }

    public function addForm()
    {
        // Ambil siswa yang APPROVED untuk dropdown
        $students = $this->studentModel->where('status', 'APPROVED')->findAll();
        return view('ppdb/payment/add', ['students' => $students]);
    }

    public function add()
    {
        $request = service('request');

        // Ambil student_id dari form
        $studentId = $request->getPost('student_id');

        // Validasi: student_id harus ada
        if (!$studentId) {
            return redirect()->back()->withInput()->with('error', 'Siswa harus dipilih.');
        }

        // Validasi FK: student harus ada dan APPROVED
        $student = $this->studentModel
            ->where('id', $studentId)
            ->where('status', 'APPROVED')
            ->first();

        if (!$student) {
            return redirect()->back()->withInput()->with('error', 'Siswa tidak ditemukan atau belum APPROVED.');
        }

        // Handle file upload
        $file = $this->request->getFile('proof_file');

        $uploadPath = FCPATH . 'uploads/ppdb/payment/';
        if (!is_dir($uploadPath)) {
            mkdir($uploadPath, 0777, true);
        }

        $proofName = null;
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $proofName = time() . '_' . $file->getRandomName();
            $file->move($uploadPath, $proofName);
        }

        // Siapkan data insert
        $data = [
            'student_id' => $studentId,
            'amount' => $request->getPost('amount'),
            'method' => $request->getPost('method'),
            'status' => 'PAID',
            'payment_date' => date('Y-m-d H:i:s'),
            'proof_file' => $proofName
        ];

        // Debug log (optional)
        $logger = \Config\Services::logger();
        $logger->info('PPDB Payment data siap insert: ' . json_encode($data));

        // Insert ke DB dengan try-catch
        try {
            $insertId = $this->paymentModel->insert($data);
            if ($insertId === false) {
                $errors = $this->paymentModel->errors();
                return redirect()->back()->withInput()->with('error', 'Gagal menyimpan: ' . json_encode($errors));
            }
        } catch (\CodeIgniter\Database\Exceptions\DatabaseException $e) {
            return redirect()->back()->withInput()->with('error', 'Gagal menyimpan: ' . $e->getMessage());
        }

        return redirect()->to(site_url('ppdb/payment'))
            ->with('success', 'Pembayaran berhasil ditambahkan. ID: ' . $insertId);
    }

    
    public function data()
    {
        $data = $this->paymentModel
            ->select('
            ppdb_payment.id,
            ppdb_payment.amount,
            ppdb_payment.method,
            ppdb_payment.status,
            ppdb_payment.payment_date,
            ppdb_registrations.reg_no,
            ppdb_registrations.name AS student_name
        ')
            ->join(
                'ppdb_registrations',
                'ppdb_registrations.id = ppdb_payment.student_id',
                'left'
            )
            ->orderBy('ppdb_payment.id', 'DESC')
            ->findAll();

        return $this->response->setJSON([
            'data' => $data
        ]);
    }    

    
}
