<?php
class FeeTypeController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('fee-types/index', [
            'title' => lang('finance.fee_types'),
            'breadcrumbs' => [
                ['label' => lang('finance.title'), 'url' => '/finance/invoices'],
                ['label' => lang('finance.fee_types')],
            ],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw   = (int)$request->get('draw', 1);
        $start  = (int)$request->get('start', 0);
        $length = (int)$request->get('length', 25);

        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM fee_types");
        $rows  = $db->fetchAll("SELECT * FROM fee_types ORDER BY sort_order LIMIT {$length} OFFSET {$start}");

        $data = [];
        foreach ($rows as $row) {
            $data[] = [
                'id'           => $row['id'],
                'fee_code'     => e($row['fee_code']),
                'name_en'      => e($row['name_en']),
                'name_ar'      => e($row['name_ar']),
                'category'     => e(ucfirst(str_replace('_', ' ', $row['category']))),
                'is_recurring' => $row['is_recurring'] ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>',
                'is_active'    => $row['is_active'] ? status_badge('active') : status_badge('inactive'),
                'actions'      => '<button class="btn btn-sm btn-outline-primary btn-edit-fee" data-id="'.$row['id'].'" data-fee=\''.e(json_encode($row)).'\'><i class="fas fa-edit"></i></button>',
            ];
        }

        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $total, 'data' => $data]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid security token'], 403);
            return;
        }

        $validator = new Validator($request->all(), [
            'fee_code' => 'required|string|max:30|unique:fee_types,fee_code',
            'name_en'  => 'required|string|max:200',
            'name_ar'  => 'required|string|max:200',
            'category' => 'required|in:registration,subscription,annual,transfer,freeze,card,carnet,penalty,sport,facility,guest,other',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['is_recurring']   = (int)$request->post('is_recurring', 0);
        $data['is_refundable']  = (int)$request->post('is_refundable', 0);
        $data['tax_applicable'] = (int)$request->post('tax_applicable', 0);
        $data['is_active']      = (int)$request->post('is_active', 1);
        $data['sort_order']     = (int)$request->post('sort_order', 0);

        $id = $this->db()->insert('fee_types', $data);
        AuditLog::log('create', 'finance', 'fee_type', $id, "Created fee type: {$data['fee_code']}");
        $this->json(['success' => true, 'message' => lang('common.success')]);
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid security token'], 403);
            return;
        }

        $id = (int)$request->routeParam('id');

        $validator = new Validator($request->all(), [
            'name_en'  => 'required|string|max:200',
            'name_ar'  => 'required|string|max:200',
            'category' => 'required|in:registration,subscription,annual,transfer,freeze,card,carnet,penalty,sport,facility,guest,other',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['is_recurring']   = (int)$request->post('is_recurring', 0);
        $data['is_refundable']  = (int)$request->post('is_refundable', 0);
        $data['tax_applicable'] = (int)$request->post('tax_applicable', 0);
        $data['is_active']      = (int)$request->post('is_active', 1);
        $data['sort_order']     = (int)$request->post('sort_order', 0);

        $this->db()->update('fee_types', $data, 'id = ?', [$id]);
        AuditLog::log('update', 'finance', 'fee_type', $id, "Updated fee type");
        $this->json(['success' => true, 'message' => lang('common.success')]);
    }

    public function listActive(Request $request): void
    {
        $feeTypes = $this->db()->fetchAll("SELECT id, fee_code, name_en, name_ar, category FROM fee_types WHERE is_active=1 ORDER BY sort_order");
        $this->json(['success' => true, 'data' => $feeTypes]);
    }
}