<?php
namespace App\Repositories;

use App\Database\Connection;
use PDO;

class PaymentEventRepository
{
    private $db;

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

    public function recordEvent(
        int $paymentRecordId,
        string $eventType,
        array $oldSnapshot = [],
        array $newSnapshot = [],
        array $metadata = [],
        int $actorUserId = 0,
        string $actorDidarId = ''
    ): int {
        if ($paymentRecordId <= 0 || trim($eventType) === '') {
            return 0;
        }
        $stmt = $this->db->getPdo()->prepare("
            INSERT INTO payment_events
                (payment_record_id, event_type, actor_user_id, actor_didar_id, old_snapshot_json, new_snapshot_json, metadata_json)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $paymentRecordId,
            trim($eventType),
            $actorUserId > 0 ? $actorUserId : null,
            trim($actorDidarId) !== '' ? trim($actorDidarId) : null,
            $this->jsonOrNull($oldSnapshot),
            $this->jsonOrNull($newSnapshot),
            $this->jsonOrNull($metadata),
        ]);
        return (int)$this->db->getPdo()->lastInsertId();
    }

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

    private function jsonOrNull(array $value): ?string
    {
        if (empty($value)) {
            return null;
        }
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}
