<?php
declare(strict_types=1);

namespace App\Modules\Settings;

use App\Core\Http\ToggleableRepositoryTrait;
use PDO;
use Throwable;

final class ReceiptConfigRepository
{
    use ToggleableRepositoryTrait;
    public function __construct(
        private readonly PDO $pdo
    ) {
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function listAll(): array
    {
        $statement = $this->pdo->prepare('SELECT * FROM receipt_configs ORDER BY created_at DESC');
        $statement->execute();
        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

        return is_array($rows) ? $rows : [];
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findById(int $id): ?array
    {
        $statement = $this->pdo->prepare('SELECT * FROM receipt_configs WHERE id = :id LIMIT 1');
        $statement->execute(['id' => $id]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);

        return is_array($row) ? $row : null;
    }

    /**
     * @param array<string, mixed> $data
     */
    public function save(array $data): void
    {
        $id = isset($data['id']) && $data['id'] !== '' ? (int) $data['id'] : null;

        $params = [
            'name' => trim((string) ($data['name'] ?? '')),
            'is_active' => isset($data['is_active']) ? 1 : 0,
            'number_format' => trim((string) ($data['number_format'] ?? 'PAR/%N/%M/%Y')),
            'numbering_type' => in_array((string) ($data['numbering_type'] ?? ''), ['monthly', 'yearly'], true)
                ? (string) $data['numbering_type']
                : 'monthly',
            'is_named' => isset($data['is_named']) ? 1 : 0,
            'sale_date_source' => in_array((string) ($data['sale_date_source'] ?? ''), ['order_date', 'payment_date', 'issue_date'], true)
                ? (string) $data['sale_date_source']
                : 'issue_date',
            'order_reference' => in_array((string) ($data['order_reference'] ?? ''), ['none', 'orderpro', 'integration'], true)
                ? (string) $data['order_reference']
                : 'none',
        ];

        if ($id !== null) {
            $statement = $this->pdo->prepare(
                'UPDATE receipt_configs SET
                    name = :name,
                    is_active = :is_active,
                    number_format = :number_format,
                    numbering_type = :numbering_type,
                    is_named = :is_named,
                    sale_date_source = :sale_date_source,
                    order_reference = :order_reference
                WHERE id = :id'
            );
            $params['id'] = $id;
        } else {
            $statement = $this->pdo->prepare(
                'INSERT INTO receipt_configs (name, is_active, number_format, numbering_type, is_named, sale_date_source, order_reference)
                VALUES (:name, :is_active, :number_format, :numbering_type, :is_named, :sale_date_source, :order_reference)'
            );
        }

        $statement->execute($params);
    }

    public function toggleStatus(int $id): void
    {
        $this->toggleActive('receipt_configs', $id);
    }

    public function delete(int $id): void
    {
        $statement = $this->pdo->prepare('DELETE FROM receipt_configs WHERE id = :id');
        $statement->execute(['id' => $id]);
    }
}
