<?php

class PaymentController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('payments', 'view');

        $methodId = $this->input('method', 'ALL');
        $search = trim($this->input('search', ''));
        $dateFrom = $this->input('date_from', '');
        $dateTo = $this->input('date_to', '');

        $paymentModel = new Payment();
        $methodModel = new PaymentMethod();
        $db = Database::getConnection();

        $this->view('payments.index', [
            'pageTitle'  => 'Payments',
            'payments'   => $paymentModel->listAll($methodId, $search, $dateFrom, $dateTo),
            'stats'      => $paymentModel->stats(),
            'breakdown'  => $paymentModel->methodBreakdownToday(),
            'unpaidCount'=> $paymentModel->unpaidOrdersCount(),
            'oldestUnpaidHours' => $paymentModel->oldestUnpaidHours(),
            'trend'      => $paymentModel->collectionTrend(7),
            'methods'    => $methodModel->allWithAccount(),
            'financeAccounts' => $db->query("SELECT * FROM finance_accounts WHERE is_active = 1")->fetchAll(),
            'activeMethod' => $methodId,
            'search'     => $search,
            'dateFrom'   => $dateFrom,
            'dateTo'     => $dateTo,
            'csrf'       => $this->csrfField(),
        ]);
    }

    // --- Payment Methods management ---

    public function storeMethod(): void
    {
        Auth::requirePermission('payments', 'add');
        $this->verifyCsrf();

        $name = trim($this->input('method_name', ''));
        if ($name === '') {
            $this->redirect('payments');
            return;
        }

        $methodModel = new PaymentMethod();
        $methodModel->insert([
            'method_name'        => strtoupper(str_replace(' ', '_', $name)),
            'finance_account_id' => (int) $this->input('finance_account_id', 0) ?: null,
            'fee_percentage'     => (float) $this->input('fee_percentage', 0),
            'is_active'          => 1,
        ]);

        AuditLogger::log(Auth::id(), 'PAYMENT_METHOD_CREATE', 'payments', "Added payment method: {$name}");
        $this->redirect('payments');
    }

    public function updateMethod(): void
    {
        Auth::requirePermission('payments', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $methodModel = new PaymentMethod();
        $existing = $methodModel->find($id);
        if (!$existing) {
            $this->redirect('payments');
            return;
        }

        $methodModel->update($id, [
            'finance_account_id' => (int) $this->input('finance_account_id', 0) ?: null,
            'fee_percentage'     => (float) $this->input('fee_percentage', $existing['fee_percentage']),
        ]);

        AuditLogger::log(Auth::id(), 'PAYMENT_METHOD_UPDATE', 'payments', "Updated payment method #{$id}");
        $this->redirect('payments');
    }

    public function toggleMethod(): void
    {
        Auth::requirePermission('payments', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $methodModel = new PaymentMethod();
        $method = $methodModel->find($id);
        if ($method) {
            $methodModel->update($id, ['is_active' => $method['is_active'] ? 0 : 1]);
            AuditLogger::log(Auth::id(), 'PAYMENT_METHOD_TOGGLE', 'payments', "Method #{$id} active -> " . ($method['is_active'] ? '0' : '1'));
        }
        $this->redirect('payments');
    }
}
