<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddCompetitionNavItems extends Migration
{
    public function up()
    {
        $db = \Config\Database::connect();

        if (!$db->tableExists('nav_items')) {
            return;
        }

        $parentColumn = null;
        if ($db->fieldExists('menu_parent_id', 'nav_items')) {
            $parentColumn = 'menu_parent_id';
        } elseif ($db->fieldExists('parent_id', 'nav_items')) {
            $parentColumn = 'parent_id';
        }

        if ($parentColumn === null) {
            return;
        }

        $navBuilder = $db->table('nav_items');
        $now = date('Y-m-d H:i:s');

        $eventRow = $navBuilder
            ->select('id')
            ->where('label', 'Event Management')
            ->where($parentColumn, null)
            ->get()
            ->getRowArray();

        if ($eventRow) {
            $eventId = (int) $eventRow['id'];
        } else {
            $navBuilder->insert([
                $parentColumn => null,
                'label'        => 'Event Management',
                'url'          => null,
                'sort_order'   => 110,
                'is_enabled'   => 1,
                'created_at'   => $now,
                'updated_at'   => $now,
            ]);
            $eventId = (int) $db->insertID();
        }

        $competitionUrl = 'admin/competition-winners';
        $existing = $navBuilder->select('id')
            ->where('url', $competitionUrl)
            ->get()
            ->getRowArray();

        if (!$existing) {
            $navBuilder->insert([
                $parentColumn => $eventId ?: null,
                'label'        => 'Competition Winners',
                'url'          => $competitionUrl,
                'sort_order'   => 3,
                'is_enabled'   => 1,
                'created_at'   => $now,
                'updated_at'   => $now,
            ]);
            $competitionId = (int) $db->insertID();
        } else {
            $competitionId = (int) $existing['id'];
        }

        if (!$db->tableExists('role_nav_items') || !$db->tableExists('roles')) {
            return;
        }

        if ($competitionId <= 0) {
            return;
        }

        $roleRows = $db->table('roles')
            ->select('id, name')
            ->whereIn('name', ['administrator', 'principal', 'vice_principal'])
            ->get()
            ->getResultArray();

        $roleMap = $db->table('role_nav_items');
        foreach ($roleRows as $role) {
            $roleId = (int) ($role['id'] ?? 0);
            if ($roleId <= 0) {
                continue;
            }

            $exists = $roleMap
                ->where('role_id', $roleId)
                ->where('nav_item_id', $competitionId)
                ->get()
                ->getRowArray();

            if ($exists) {
                continue;
            }

            $roleMap->insert([
                'role_id'     => $roleId,
                'nav_item_id' => $competitionId,
                'created_at'  => $now,
                'updated_at'  => $now,
            ]);
        }
    }

    public function down()
    {
        $db = \Config\Database::connect();

        if (!$db->tableExists('nav_items')) {
            return;
        }

        $competitionUrl = 'admin/competition-winners';
        $row = $db->table('nav_items')
            ->select('id')
            ->where('url', $competitionUrl)
            ->get()
            ->getRowArray();

        if ($row && $db->tableExists('role_nav_items')) {
            $db->table('role_nav_items')
                ->where('nav_item_id', (int) $row['id'])
                ->delete();
        }

        $db->table('nav_items')
            ->where('url', $competitionUrl)
            ->delete();
    }
}
