<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class ConvertAcademyToSwimming extends Migration
{
    public function up(): void
    {
        $now = date('Y-m-d H:i:s');

        $this->db->table('settings')
            ->where('key', 'academy_name')
            ->update([
                'value' => 'Splash Academy',
                'updated_at' => $now,
            ]);

        $this->db->table('roles')
            ->where('slug', 'coach')
            ->update([
                'name' => 'Trainer',
                'description' => 'Acces la copii, evaluari si prezenta pentru grupele proprii de inot.',
                'updated_at' => $now,
            ]);

        $levelRows = $this->db->table('academy_levels')
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->get()
            ->getResultArray();

        if (count($levelRows) >= 4) {
            $targetLevels = [
                [
                    'name' => 'Delfinaș (Inițiere)',
                    'slug' => 'delfinas-initiere',
                    'sort_order' => 1,
                    'color_hex' => '#0ea5e9',
                    'internal_description' => 'Nivel intern pentru cursurile de inot: Delfinaș (Inițiere).',
                    'parent_description' => 'Nivelul Delfinaș (Inițiere) marcheaza acomodarea copilului cu apa si bazele tehnice.',
                ],
                [
                    'name' => 'Rechin (Avansat)',
                    'slug' => 'rechin-avansat',
                    'sort_order' => 2,
                    'color_hex' => '#0284c7',
                    'internal_description' => 'Nivel intern pentru cursurile de inot: Rechin (Avansat).',
                    'parent_description' => 'Nivelul Rechin (Avansat) marcheaza progresul copilului in tehnica de inot.',
                ],
                [
                    'name' => 'Pre-Performanță',
                    'slug' => 'pre-performanta',
                    'sort_order' => 3,
                    'color_hex' => '#14b8a6',
                    'internal_description' => 'Nivel intern pentru cursurile de inot: Pre-Performanță.',
                    'parent_description' => 'Nivelul Pre-Performanță pregateste copilul pentru volum si obiective sportive.',
                ],
                [
                    'name' => 'Sportiv de Performanță',
                    'slug' => 'sportiv-de-performanta',
                    'sort_order' => 4,
                    'color_hex' => '#f59e0b',
                    'internal_description' => 'Nivel intern pentru cursurile de inot: Sportiv de Performanță.',
                    'parent_description' => 'Nivelul Sportiv de Performanță marcheaza integrarea in pregatirea competitiva.',
                ],
            ];

            foreach ($targetLevels as $index => $level) {
                $this->db->table('academy_levels')
                    ->where('id', (int) $levelRows[$index]['id'])
                    ->update($level + [
                        'benchmark_minimum' => 3.0,
                        'benchmark_target' => 4.0,
                        'promotion_rules' => 'Necesita evaluare full cu status READY si criterii critice peste prag.',
                        'updated_at' => $now,
                    ]);
            }

            $sportPerformanceId = (int) $levelRows[3]['id'];
            $oldLevelIds = array_map(static fn (array $row): int => (int) $row['id'], array_slice($levelRows, 4));

            if ($oldLevelIds !== []) {
                foreach (['children' => 'academy_level_id', 'academy_groups' => 'academy_level_id', 'evaluations' => 'level_at_time_id'] as $table => $column) {
                    $this->db->table($table)
                        ->whereIn($column, $oldLevelIds)
                        ->update([$column => $sportPerformanceId, 'updated_at' => $now]);
                }

                $this->db->table('academy_levels')->whereIn('id', $oldLevelIds)->delete();
            }
        }

        $criteriaMap = [
            'footwork' => ['Water Confidence', 'water-confidence'],
            'rally-consistency' => ['Breathing Control', 'breathing-control'],
            'technique' => ['Stroke Technique', 'stroke-technique'],
            'serve-basics' => ['Start & Turn Basics', 'start-turn-basics'],
            'tactical-awareness' => ['Race Awareness', 'race-awareness'],
        ];

        foreach ($criteriaMap as $oldSlug => [$name, $slug]) {
            $this->db->table('evaluation_criteria')
                ->where('slug', $oldSlug)
                ->update([
                    'name' => $name,
                    'slug' => $slug,
                    'description' => $name . ' in contextul evaluarii academiei de inot.',
                    'updated_at' => $now,
                ]);
        }

        $this->db->table('academy_groups')
            ->where('code', 'RSP')
            ->update(['name' => 'Delfinas Initiere', 'code' => 'DFN', 'updated_at' => $now]);
        $this->db->table('academy_groups')
            ->where('code', 'OAC')
            ->update(['name' => 'Rechin Avansat', 'code' => 'RCH', 'updated_at' => $now]);
        $this->db->table('academy_groups')
            ->where('code', 'GSM')
            ->update(['name' => 'Performanta Bazin', 'code' => 'PRF', 'updated_at' => $now]);

        $this->db->table('coaches')
            ->where('display_role', 'Head Coach')
            ->update(['display_role' => 'Head Trainer', 'updated_at' => $now]);
        $this->db->table('coaches')
            ->where('display_role', 'Coach')
            ->update(['display_role' => 'Trainer', 'updated_at' => $now]);
        $this->db->table('coaches')
            ->where('display_role', 'Assistant Coach')
            ->update(['display_role' => 'Assistant Trainer', 'updated_at' => $now]);
    }

    public function down(): void
    {
        $now = date('Y-m-d H:i:s');

        $this->db->table('settings')
            ->where('key', 'academy_name')
            ->update(['value' => 'Academia Tennis', 'updated_at' => $now]);

        $this->db->table('roles')
            ->where('slug', 'coach')
            ->update([
                'name' => 'Coach',
                'description' => 'Acces la copii, evaluari si prezenta pentru grupele proprii.',
                'updated_at' => $now,
            ]);
    }
}
