<?php

declare(strict_types=1);

namespace App\Repositories;

use App\Models\DemoData;

final class ReportRepository extends BaseRepository
{
    public function latest(int $limit = 6): array
    {
        if (!$this->pdo) {
            return array_slice(DemoData::reports(), 0, $limit);
        }

        $statement = $this->pdo->prepare(
            'SELECT r.*, i.name AS institution
             FROM reports r
             LEFT JOIN institutions i ON i.id = r.institution_id
             ORDER BY r.created_at DESC
             LIMIT :limit'
        );
        $statement->bindValue(':limit', $limit, \PDO::PARAM_INT);
        $statement->execute();

        return $statement->fetchAll();
    }

    public function create(array $data): array
    {
        $trackingNumber = 'CG-' . date('Y') . '-' . random_int(2000, 9999);

        if (!$this->pdo) {
            return [
                'id' => random_int(2000, 9999),
                'tracking_number' => $trackingNumber,
                'status' => 'in_progress',
                ...$data,
            ];
        }

        $statement = $this->pdo->prepare(
            'INSERT INTO reports
                (user_id, category, title, description, address, municipality, institution_id, status, tracking_number, submitted_at, deadline_at, created_at)
             VALUES
                (:user_id, :category, :title, :description, :address, :municipality, :institution_id, :status, :tracking_number, NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY), NOW())'
        );
        $statement->execute([
            'user_id' => $data['user_id'] ?? null,
            'category' => $data['category'],
            'title' => $data['title'],
            'description' => $data['description'],
            'address' => $data['address'],
            'municipality' => $data['municipality'],
            'institution_id' => $data['institution_id'] ?? null,
            'status' => 'in_progress',
            'tracking_number' => $trackingNumber,
        ]);

        return [
            'id' => (int) $this->pdo->lastInsertId(),
            'tracking_number' => $trackingNumber,
            'status' => 'in_progress',
            ...$data,
        ];
    }

    public function findByTracking(string $trackingNumber): ?array
    {
        if (!$this->pdo) {
            foreach (DemoData::reports() as $report) {
                if ($report['tracking_number'] === $trackingNumber || (string) $report['id'] === $trackingNumber) {
                    return $report;
                }
            }

            return DemoData::reports()[0];
        }

        $statement = $this->pdo->prepare(
            'SELECT r.*, i.name AS institution
             FROM reports r
             LEFT JOIN institutions i ON i.id = r.institution_id
             WHERE r.tracking_number = :tracking OR r.id = :numeric_id
             LIMIT 1'
        );
        $statement->execute([
            'tracking' => $trackingNumber,
            'numeric_id' => ctype_digit($trackingNumber) ? (int) $trackingNumber : 0,
        ]);

        $report = $statement->fetch();

        return $report ?: null;
    }
}
