<?php

namespace Models;

class DocumentModel
{
    private \PDO $pdo;

    public function __construct()
    {
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
            $this->pdo = $GLOBALS['pdo'];
            return;
        }
    }

    public function create(int $userId, string $documentType, string $documentPath): array
    {
        $stmt = $this->pdo->prepare(
            'INSERT INTO "document" (user_id, document_type, document_path)
             VALUES (:user_id, :document_type, :document_path)
             RETURNING document_id'
        );

        $stmt->execute([
            'user_id' => $userId,
            'document_type' => $documentType,
            'document_path' => $documentPath,
        ]);

        $documentId = (int)$stmt->fetchColumn();

        return [
            'document_id' => $documentId,
            'user_id' => $userId,
            'document_type' => $documentType,
            'document_path' => $documentPath,
        ];
    }

    public function listByUserId(int $userId): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT document_id, user_id, document_type, document_path
             FROM "document"
             WHERE user_id = :user_id
             ORDER BY document_id DESC'
        );
        $stmt->execute(['user_id' => $userId]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function findLatestByUserIdAndType(int $userId, string $documentType): ?array
    {
        $stmt = $this->pdo->prepare(
            'SELECT document_id, user_id, document_type, document_path
             FROM "document"
             WHERE user_id = :user_id AND document_type = :document_type
             ORDER BY document_id DESC
             LIMIT 1'
        );
        $stmt->execute([
            'user_id' => $userId,
            'document_type' => $documentType,
        ]);

        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        return $row ?: null;
    }
}
