<?php

declare(strict_types=1);

class AlbumPerformer
{
    public static function find(int $id): ?array
    {
        return Database::fetchOne('SELECT * FROM album_performers WHERE id = ?', [$id]);
    }

    public static function findBySlug(string $slug): ?array
    {
        $vt = Video::activeType();
        $locale = Translator::locale();
        $defaultLang = Translator::getDefaultCode();

         
        if ($locale !== $defaultLang) {
            $q = 'SELECT ct.performer_id FROM album_performer_translations ct
                  JOIN album_performers c ON ct.performer_id = c.id
                  WHERE ct.slug = ? AND ct.lang_code = ?';
            $p = [$slug, $locale];
            if ($vt !== '') { $q .= ' AND c.video_type = ?'; $p[] = $vt; }
            $trans = Database::fetchOne($q, $p);
            if ($trans) {
                $performer = self::find((int) $trans['performer_id']);
                return $performer ? self::localize($performer) : null;
            }
        }

         
        $q = 'SELECT * FROM album_performers WHERE slug = ?';
        $p = [$slug];
        if ($vt !== '') { $q .= ' AND video_type = ?'; $p[] = $vt; }
        $performer = Database::fetchOne($q, $p);

         
        if (!$performer && $vt !== '') {
            $performer = Database::fetchOne('SELECT * FROM album_performers WHERE slug = ?', [$slug]);
        }

        return $performer ? self::localize($performer) : null;
    }

    public static function all(int $limit = 0, int $offset = 0, string $sort = 'alphabetical', string $videoType = '', bool $onlyPopulated = false): array
    {
        $orderBy = match ($sort) {
            'popularity' => 'c.total_views DESC, c.name ASC',
            default => 'c.name ASC',
        };

        $conds = [];
        $params = [];
        if ($videoType !== '') { $conds[] = 'c.video_type = ?'; $params[] = $videoType; }
         
        if ($onlyPopulated) { $conds[] = 'c.album_count > 0'; }
        $where = !empty($conds) ? ' WHERE ' . implode(' AND ', $conds) : '';

        $limitClause = $limit > 0 ? ' LIMIT ? OFFSET ?' : '';
        if ($limit > 0) {
            $params[] = $limit;
            $params[] = $offset;
        }

        $results = Database::fetchAll(
            "SELECT c.* FROM album_performers c{$where} ORDER BY {$orderBy}" . $limitClause,
            $params
        );
        return self::localizeResults($results);
    }

    public static function count(string $videoType = '', bool $onlyPopulated = false): int
    {
        $conds = []; $params = [];
        if ($videoType !== '') { $conds[] = 'video_type = ?'; $params[] = $videoType; }
        if ($onlyPopulated) { $conds[] = 'album_count > 0'; }
        if (!empty($conds)) {
            return Database::count('album_performers', implode(' AND ', $conds), $params);
        }
        return Database::count('album_performers');
    }

    public static function create(array $data): int
    {
        return Database::insert('album_performers', $data);
    }

    public static function update(int $id, array $data): void
    {
        Database::update('album_performers', $data, 'id = ?', [$id]);
    }

    public static function delete(int $id): void
    {
        Database::delete('album_performers', 'id = ?', [$id]);
    }

    

    public static function updateCounts(int $id): void
    {
        $row = Database::fetchOne(
            "SELECT COUNT(*) as cnt, COALESCE(SUM(a.views), 0) as tv
             FROM album_performer_map m
             JOIN albums a ON m.album_id = a.id
             WHERE m.performer_id = ? AND a.status = 'published'",
            [$id]
        );
        Database::update('album_performers', [
            'album_count' => (int) ($row['cnt'] ?? 0),
            'total_views' => (int) ($row['tv'] ?? 0),
        ], 'id = ?', [$id]);
    }

    

    public static function translations(int $performerId): array
    {
        $rows = Database::fetchAll(
            'SELECT lang_code, name, slug, bio FROM album_performer_translations WHERE performer_id = ? ORDER BY lang_code',
            [$performerId]
        );
        $result = [];
        foreach ($rows as $row) {
            $result[$row['lang_code']] = $row;
        }
        return $result;
    }

    

    public static function localize(?array $performer): ?array
    {
        if ($performer === null || Translator::locale() === Translator::getDefaultCode()) {
            return $performer;
        }

        $row = Database::fetchOne(
            'SELECT name, slug, bio FROM album_performer_translations WHERE performer_id = ? AND lang_code = ?',
            [(int) $performer['id'], Translator::locale()]
        );

        if ($row) {
            if ($row['name'] !== null && $row['name'] !== '') {
                $performer['name'] = $row['name'];
            }
            if ($row['slug'] !== null && $row['slug'] !== '') {
                $performer['slug'] = $row['slug'];
            }
            if ($row['bio'] !== null && $row['bio'] !== '') {
                $performer['bio'] = $row['bio'];
            }
        }

        return $performer;
    }

    

    public static function localizeResults(array $performers): array
    {
        if (empty($performers) || Translator::locale() === Translator::getDefaultCode()) {
            return $performers;
        }

        $ids = array_column($performers, 'id');
        if (empty($ids)) {
            return $performers;
        }

        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $params = array_merge([Translator::locale()], $ids);

        $rows = Database::fetchAll(
            "SELECT performer_id, name, slug, bio FROM album_performer_translations WHERE lang_code = ? AND performer_id IN ({$placeholders})",
            $params
        );

        $map = [];
        foreach ($rows as $row) {
            $map[(int) $row['performer_id']] = $row;
        }

        foreach ($performers as &$performer) {
            $pid = (int) $performer['id'];
            if (isset($map[$pid])) {
                $tr = $map[$pid];
                if ($tr['name'] !== null && $tr['name'] !== '') {
                    $performer['name'] = $tr['name'];
                }
                if ($tr['slug'] !== null && $tr['slug'] !== '') {
                    $performer['slug'] = $tr['slug'];
                }
                if (isset($tr['bio']) && $tr['bio'] !== null && $tr['bio'] !== '') {
                    $performer['bio'] = $tr['bio'];
                }
            }
        }
        unset($performer);

        return $performers;
    }
}
