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

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM payment_methods");
        $rows  = $db->fetchAll("SELECT * FROM payment_methods ORDER BY sort_order");

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

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

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

        $validator = new Validator($request->all(), [
            'method_code' => 'required|string|max:20|unique:payment_methods,method_code',
            'name_en'     => 'required|string|max:100',
            'name_ar'     => 'required|string|max:100',
            'method_type' => 'required|in:cash,check,bank_transfer,credit_card,debit_card,online,wallet,other',
        ]);

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

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

        $id = $this->db()->insert('payment_methods', $data);
        AuditLog::log('create', 'finance', 'payment_method', $id, "Created payment method: {$data['method_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' => 'CSRF'], 403); return; }

        $id = (int)$request->routeParam('id');
        $validator = new Validator($request->all(), [
            'name_en'     => 'required|string|max:100',
            'name_ar'     => 'required|string|max:100',
            'method_type' => 'required|in:cash,check,bank_transfer,credit_card,debit_card,online,wallet,other',
        ]);

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

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

        $this->db()->update('payment_methods', $data, 'id = ?', [$id]);
        AuditLog::log('update', 'finance', 'payment_method', $id, "Updated payment method");
        $this->json(['success' => true, 'message' => lang('common.success')]);
    }
}