<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddSchoolYearsNavItem extends Migration
{
    private string $url = 'administrator/school-years';

    public function up(): void
    {
        if (! $this->db->tableExists('nav_items')) {
            return;
        }

        $parentColumn = $this->parentColumn();
        $existingQuery = $this->db->table('nav_items')
            ->where('url', $this->url)
            ->get();

        $existing = $existingQuery !== false ? $existingQuery->getRowArray() : null;

        if ($existing !== null) {
            return;
        }

        $parentBuilder = $this->db->table('nav_items')
            ->where('label', 'Configuration');

        if ($parentColumn !== null) {
            $parentBuilder->where($parentColumn, null);
        }

        $parentQuery = $parentBuilder->get();
        $parent = $parentQuery !== false ? $parentQuery->getRowArray() : null;

        $insert = [
            'label' => 'School Years',
            'url' => $this->url,
            'sort_order' => 2,
            'is_enabled' => 1,
            'created_at' => date('Y-m-d H:i:s'),
        ];

        if ($parentColumn !== null) {
            $insert[$parentColumn] = $parent['id'] ?? null;
        }

        $this->db->table('nav_items')->insert($insert);

        $navItemId = (int) $this->db->insertID();

        if (
            $navItemId <= 0
            || ! $this->db->tableExists('role_nav_items')
            || ! $this->db->fieldExists('role', 'role_nav_items')
            || ! $this->db->fieldExists('nav_item_id', 'role_nav_items')
        ) {
            return;
        }

        foreach (['administrator', 'principal', 'vice_principal'] as $role) {
            $this->db->table('role_nav_items')->insert([
                'role' => $role,
                'nav_item_id' => $navItemId,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public function down(): void
    {
        if (! $this->db->tableExists('nav_items')) {
            return;
        }

        $query = $this->db->table('nav_items')
            ->where('url', $this->url)
            ->get();

        $row = $query !== false ? $query->getRowArray() : null;

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

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

        $this->db->table('nav_items')
            ->where('id', (int) $row['id'])
            ->delete();
    }

    private function parentColumn(): ?string
    {
        if ($this->db->fieldExists('parent_id', 'nav_items')) {
            return 'parent_id';
        }

        if ($this->db->fieldExists('menu_parent_id', 'nav_items')) {
            return 'menu_parent_id';
        }

        return null;
    }
}
