<?php

namespace App\Controllers\Api\Admin;

use App\Models\RewarderPaymentModel;
use CodeIgniter\HTTP\ResponseInterface;

class Payments extends BaseAdminApiController
{
    public function index(): ResponseInterface
    {
        if ($resp = $this->requirePermission('shop_orders_manage')) {
            return $resp;
        }

        $q = db_connect()->table('rewarder_payments p')
            ->select('p.*, sh.name as shop_name, u.name as customer_name, l.points_delta AS reward_points')
            ->join('rewarder_shops sh', 'sh.id = p.shop_id', 'left')
            ->join('users u', 'u.id = p.user_id', 'left')
            ->join('rewarder_ledger l', "l.user_id = p.user_id AND l.created_at = p.created_at AND l.points_delta > 0 AND l.description LIKE 'Points earned%'", 'left')
            ->orderBy('p.id', 'desc');

        $shopId = $this->isShopkeeper() ? $this->shopkeeperShopId() : null;
        if ($shopId) {
            $q->where('p.shop_id', (int) $shopId);
        } else {
            $filterShopId = $this->request->getGet('shop_id');
            if ($filterShopId !== null && $filterShopId !== '') {
                $q->where('p.shop_id', (int) $filterShopId);
            }
        }

        $filterUserId = $this->request->getGet('user_id');
        if ($filterUserId !== null && $filterUserId !== '') {
            $q->where('p.user_id', (int) $filterUserId);
        }

        $filterStatus = $this->request->getGet('status');
        if ($filterStatus !== null && $filterStatus !== '') {
            $q->where('p.status', (string) $filterStatus);
        }

        $rows = $q->get()->getResult();
        return $this->ok($rows);
    }

    public function show(int $id): ResponseInterface
    {
        if ($resp = $this->requirePermission('shop_orders_manage')) {
            return $resp;
        }

        $q = db_connect()->table('rewarder_payments p')
            ->select('p.*, sh.name as shop_name, u.name as customer_name, u.email as customer_email, u.username as customer_username')
            ->join('rewarder_shops sh', 'sh.id = p.shop_id', 'left')
            ->join('users u', 'u.id = p.user_id', 'left')
            ->where('p.id', $id);

        $shopId = $this->isShopkeeper() ? $this->shopkeeperShopId() : null;
        if ($shopId) {
            $q->where('p.shop_id', (int) $shopId);
        }

        $row = $q->get()->getRow();
        if (!$row) {
            return $this->fail('Not found', 404);
        }

        return $this->ok($row);
    }

    public function update(int $id): ResponseInterface
    {
        if ($resp = $this->requirePermission('shop_orders_manage')) {
            return $resp;
        }

        $m = new RewarderPaymentModel();
        $payment = $m->getById($id);
        if (!$payment) {
            return $this->fail('Not found', 404);
        }

        if ($this->isShopkeeper()) {
            $shopId = $this->shopkeeperShopId();
            if (!$shopId || (int) $payment->shop_id !== (int) $shopId) {
                return $this->fail('Not found', 404);
            }
        }

        $status = trim((string) $this->input('status', ''));
        if ($status === '') {
            return $this->fail('Validation failed', 422, ['status' => 'Status is required']);
        }

        $m->update($id, ['status' => $status]);
        return $this->ok($m->getById($id));
    }
}

