<?php
namespace App\Repositories;

use App\Database\Connection;
use PDO;

class PaymentRefundRepository
{
    private $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    public function create(array $payload): int
    {
        $paymentRecordId = (int)($payload['payment_record_id'] ?? 0);
        $amount = (float)($payload['amount'] ?? 0);
        $refundDate = trim((string)($payload['refund_date'] ?? ''));
        if ($paymentRecordId <= 0 || $amount <= 0 || $refundDate === '') {
            throw new \InvalidArgumentException('payment_record_id, amount and refund_date are required');
        }

        $stmt = $this->db->getPdo()->prepare("
            INSERT INTO payment_refunds
                (payment_record_id, transaction_id, amount, refund_date, reason, status, affects_commission, clawback_status, created_by_user_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $paymentRecordId,
            isset($payload['transaction_id']) && $payload['transaction_id'] !== '' ? (int)$payload['transaction_id'] : null,
            $amount,
            $refundDate,
            $this->nullableString($payload['reason'] ?? null),
            strtoupper(trim((string)($payload['status'] ?? 'PENDING'))) ?: 'PENDING',
            !isset($payload['affects_commission']) || !empty($payload['affects_commission']) ? 1 : 0,
            strtoupper(trim((string)($payload['clawback_status'] ?? 'PENDING'))) ?: 'PENDING',
            isset($payload['created_by_user_id']) && $payload['created_by_user_id'] !== '' ? (int)$payload['created_by_user_id'] : null,
        ]);
        return (int)$this->db->getPdo()->lastInsertId();
    }

    public function updateStatus(int $id, string $status, string $clawbackStatus = ''): bool
    {
        if ($id <= 0 || trim($status) === '') {
            return false;
        }
        $set = ['status = ?'];
        $params = [strtoupper(trim($status))];
        if (trim($clawbackStatus) !== '') {
            $set[] = 'clawback_status = ?';
            $params[] = strtoupper(trim($clawbackStatus));
        }
        $params[] = $id;
        $stmt = $this->db->getPdo()->prepare('UPDATE payment_refunds SET ' . implode(', ', $set) . ' WHERE id = ?');
        return $stmt->execute($params);
    }

    public function listForPaymentRecord(int $paymentRecordId): array
    {
        if ($paymentRecordId <= 0) {
            return [];
        }
        $stmt = $this->db->getPdo()->prepare('SELECT * FROM payment_refunds WHERE payment_record_id = ? ORDER BY refund_date ASC, id ASC');
        $stmt->execute([$paymentRecordId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    private function nullableString($value): ?string
    {
        $value = trim((string)$value);
        return $value === '' ? null : $value;
    }
}
