<?php
namespace App\Controllers;

use App\Repositories\PaymentReviewRepository;
use App\Services\AuthService;
use App\Database\Connection;
use App\Utils\Sanitizer;
use App\Utils\Logger;

class PaymentController extends ApiController
{
    private $paymentRepo;
    private $authService;
    private $db;

    public function __construct(PaymentReviewRepository $paymentRepo, AuthService $authService, Connection $db)
    {
        $this->paymentRepo = $paymentRepo;
        $this->authService = $authService;
        $this->db = $db;
    }

    private function canRbac(string $cap): bool
    {
        global $app;
        if (isset($app->services->rbac) && $app->services->rbac) {
            return (bool)$app->services->rbac->can($cap);
        }
        return false;
    }

    private function requireCap(string $cap, string $msg): void
    {
        if (!$this->canRbac($cap)) {
            $this->errorResponse($msg, 403);
        }
    }

    private function currentUserDidarId(): string
    {
        return (string)($_SESSION['didar_id'] ?? $_SESSION['user_id'] ?? '');
    }

    public function list(): void
    {
        $this->requireCap('financial_payments.view', 'دسترسی محدود - شما مجاز به مشاهده پرداخت‌ها نیستید');
        $filters = [
            'sepidar_status' => Sanitizer::sanitize($_POST['sepidar_status'] ?? $_GET['sepidar_status'] ?? ''),
            'search' => Sanitizer::sanitize($_POST['search'] ?? $_GET['search'] ?? ''),
            'date_from' => Sanitizer::sanitize($_POST['date_from'] ?? $_GET['date_from'] ?? ''),
            'date_to' => Sanitizer::sanitize($_POST['date_to'] ?? $_GET['date_to'] ?? ''),
            'lead_owner_id' => Sanitizer::sanitize($_POST['lead_owner_id'] ?? $_GET['lead_owner_id'] ?? ''),
            'service' => Sanitizer::sanitize($_POST['service'] ?? $_GET['service'] ?? ''),
            'tafsili_status' => Sanitizer::sanitize($_POST['tafsili_status'] ?? $_GET['tafsili_status'] ?? ''),
            'image_status' => Sanitizer::sanitize($_POST['image_status'] ?? $_GET['image_status'] ?? ''),
            'limit' => (int)($_POST['limit'] ?? $_GET['limit'] ?? 50),
            'offset' => (int)($_POST['offset'] ?? $_GET['offset'] ?? 0),
        ];
        $filters['limit'] = max(1, min(200, (int)$filters['limit']));
        $filters['offset'] = max(0, (int)$filters['offset']);
        $rows = $this->paymentRepo->listPayments($filters);
        $total = $this->paymentRepo->countPayments($filters);
        $this->successResponse([
            'payments' => $rows,
            'count' => count($rows),
            'total' => $total,
            'limit' => $filters['limit'],
            'offset' => $filters['offset'],
            'page' => (int)floor($filters['offset'] / $filters['limit']) + 1,
        ]);
    }

    public function markSepidar(): void
    {
        $this->requireCap('financial_payments.sepidar', 'دسترسی محدود - شما مجاز به ثبت وضعیت سپیدار نیستید');
        $transactionId = (int)($_POST['transaction_id'] ?? 0);
        if ($transactionId <= 0) {
            $this->errorResponse('شناسه پرداخت نامعتبر است');
        }
        $txn = $this->paymentRepo->getPaymentTransaction($transactionId);
        if (!$txn) {
            $this->errorResponse('پرداخت یافت نشد');
        }
        $review = $this->paymentRepo->getReview($transactionId);
        if (!empty($review['sepidar_registered_at'])) {
            $this->successResponse(['review' => $review], 'این پرداخت قبلا در سپیدار ثبت شده است');
        }

        $review = $this->paymentRepo->markSepidarRegistered(
            $transactionId,
            (int)$txn['deal_id'],
            (float)$txn['amount'],
            $this->currentUserDidarId()
        );
        Logger::logInfo('PAYMENT_SEPIDAR_REGISTERED', ['transaction_id' => $transactionId, 'deal_id' => (int)$txn['deal_id']]);
        $this->successResponse(['review' => $review], 'ثبت سپیدار انجام شد');
    }
}
