<?php

declare(strict_types=1);

namespace App\Modules\Settings;

use PDO;

final class ProjectMappingRepository
{
    public function __construct(
        private readonly PDO $pdo
    ) {
    }

    public function getAll(): array
    {
        $statement = $this->pdo->prepare(
            'SELECT * FROM project_mappings ORDER BY id DESC'
        );
        $statement->execute();

        return $statement->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    public function getById(int $id): ?array
    {
        $statement = $this->pdo->prepare(
            'SELECT * FROM project_mappings WHERE id = :id LIMIT 1'
        );
        $statement->execute([':id' => $id]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);

        return $row ?: null;
    }

    public function create(array $data): int
    {
        $statement = $this->pdo->prepare(
            'INSERT INTO project_mappings (product_name_pattern, script_name, output_dir, requires_photo, is_active)
             VALUES (:product_name_pattern, :script_name, :output_dir, :requires_photo, :is_active)'
        );
        $statement->execute([
            ':product_name_pattern' => $data['product_name_pattern'],
            ':script_name' => $data['script_name'],
            ':output_dir' => $data['output_dir'] ?? null,
            ':requires_photo' => (int) ($data['requires_photo'] ?? 0),
            ':is_active' => (int) ($data['is_active'] ?? 1),
        ]);

        return (int) $this->pdo->lastInsertId();
    }

    public function update(int $id, array $data): bool
    {
        $statement = $this->pdo->prepare(
            'UPDATE project_mappings
             SET product_name_pattern = :product_name_pattern,
                 script_name = :script_name,
                 output_dir = :output_dir,
                 requires_photo = :requires_photo
             WHERE id = :id'
        );

        return $statement->execute([
            ':product_name_pattern' => $data['product_name_pattern'],
            ':script_name' => $data['script_name'],
            ':output_dir' => $data['output_dir'] ?? null,
            ':requires_photo' => (int) ($data['requires_photo'] ?? 0),
            ':id' => $id,
        ]);
    }

    public function delete(int $id): bool
    {
        $statement = $this->pdo->prepare(
            'DELETE FROM project_mappings WHERE id = :id'
        );

        return $statement->execute([':id' => $id]);
    }

    public function toggleActive(int $id): bool
    {
        $statement = $this->pdo->prepare(
            'UPDATE project_mappings SET is_active = 1 - is_active WHERE id = :id'
        );

        return $statement->execute([':id' => $id]);
    }
}
