<?php
namespace App\Controllers\Setup;

use CodeIgniter\Controller;
use Config\Database;

class PaymentTypeController extends Controller
{
    public function index()
    {
        $db = Database::connect();
        $items = [];
        try { $items = $db->table('payment_types')->orderBy('id', 'desc')->get()->getResultArray(); } catch (\Throwable $e) { $items = []; }
        return view('setup/payment_types', [ 'title' => 'Payment Types Setup', 'items' => $items ]);
    }

    public function store()
    {
        $req = $this->request;
        $db = Database::connect();
        $data = [
            'description_en' => $req->getPost('description_en') ?? '',
            'description_ar' => $req->getPost('description_ar') ?? '',
            'amount' => (float) ($req->getPost('amount') ?? 0),
            'option' => $req->getPost('option') ?? 'Fixed',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if (! $data['description_en']) {
            return redirect()->back()->with('error', 'Description (EN) is required.');
        }
        try { $db->table('payment_types')->insert($data); return redirect()->back()->with('success', 'Payment Type added.'); }
        catch (\Throwable $e) { return redirect()->back()->with('error', 'Failed to add payment type: ' . $e->getMessage()); }
    }
}
