<?php
declare(strict_types=1);

namespace App\Modules\Cashier\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Cashier\Services\PaymentRequestService;

class CashierController extends Controller
{
    public function queue(Request $request): Response
    {
        $this->authorize('cashier.view_queue');
        $branch = App::getInstance()->currentBranch();
        $branchId = $branch ? (int) $branch['id'] : null;

        $filters = [
            'status'       => trim((string) $request->get('status', '')),
            'payment_type' => trim((string) $request->get('payment_type', '')),
            'search'       => trim((string) $request->get('search', '')),
        ];

        $requests = PaymentRequestService::getPendingQueue($branchId, $filters);

        return $this->view('Cashier.Views.queue', [
            'requests' => $requests,
            'filters'  => $filters,
        ]);
    }

    public function process(Request $request, string $id): Response
    {
        $this->authorize('cashier.process_payment');
        $db = App::getInstance()->db();

        $pr = $db->selectOne(
            "SELECT pr.*, m.full_name_ar as member_name, m.form_number, m.membership_number, m.phone_mobile,
                    e.full_name_ar as requested_by_name
             FROM payment_requests pr
             LEFT JOIN members m ON m.id = pr.member_id
             LEFT JOIN employees e ON e.id = pr.requested_by
             WHERE pr.id = ? AND pr.is_voided = 0",
            [(int) $id]
        );

        if (!$pr) {
            return $this->redirect('/cashier')->withError('طلب الدفع غير موجود');
        }
        if ($pr['status'] === 'completed') {
            return $this->redirect('/cashier')->withError('طلب الدفع مكتمل بالفعل');
        }

        return $this->view('Cashier.Views.process', [
            'pr' => $pr,
        ]);
    }

    public function complete(Request $request, string $id): Response
    {
        $this->authorize('cashier.process_payment');

        $paymentMethod = trim((string) $request->post('payment_method', 'cash'));
        if ($paymentMethod === '') {
            return $this->redirect('/cashier/' . $id)->withError('طريقة الدفع مطلوبة');
        }

        $result = PaymentRequestService::processRequest((int) $id, $paymentMethod);

        if (!$result['success']) {
            return $this->redirect('/cashier/' . $id)->withError($result['error']);
        }

        $receiptId = $result['receipt_id'] ?? null;
        $printParam = $receiptId ? '?print_receipt=' . $receiptId : '';

        return $this->redirect('/cashier' . $printParam)->withSuccess(
            'تم تحصيل الدفعة — إيصال: ' . ($result['receipt_number'] ?? '')
        );
    }

    public function cancel(Request $request, string $id): Response
    {
        $this->authorize('cashier.cancel_request');

        $reason = trim((string) $request->post('reason', ''));
        $result = PaymentRequestService::cancelRequest((int) $id, $reason);

        if (!$result['success']) {
            return $this->redirect('/cashier/' . $id)->withError($result['error']);
        }

        return $this->redirect('/cashier')->withSuccess('تم إلغاء طلب الدفع');
    }
}
