<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Models\PaymentModel;
use Exception;

class PaymentController extends Controller
{
    private PaymentModel $paymentModel;

    public function __construct()
    {
        $this->paymentModel = new PaymentModel();
    }

    public function index(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $filters = $_GET;
        $page = (int) ($_GET['page'] ?? 1);
        $perPage = (int) ($_GET['per_page'] ?? 20);

        $payments = $this->paymentModel->getAll($tenantId, $filters, $page, $perPage);
        Response::success($payments);
    }

    public function show(string $id): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $payment = $this->paymentModel->getById((int)$id, $tenantId);

        if (!$payment) {
            Response::error('Payment not found', [], 404);
        }

        Response::success($payment);
    }

    public function store(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $userId = (int) $_REQUEST['user']['sub'];
        $data = $this->getJsonBody();

        $this->validate($data, [
            'amount' => 'required|numeric'
        ]);

        try {
            $result = $this->paymentModel->createPayment($tenantId, $data, $userId);
            Response::success($result, 'Payment recorded successfully', 201);
        } catch (Exception $e) {
            Response::error($e->getMessage());
        }
    }
}
