<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddBelowSixtyNavItem 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');

        $communication = $navBuilder
            ->select('id')
            ->where('label', 'Communication')
            ->where($parentColumn, null)
            ->get()
            ->getRowArray();

        if ($communication) {
            $communicationId = (int) $communication['id'];
        } else {
            $navBuilder->insert([
                $parentColumn => null,
                'label'        => 'Communication',
                'url'          => null,
                'sort_order'   => 80,
                'is_enabled'   => 1,
                'created_at'   => $now,
                'updated_at'   => $now,
            ]);
            $communicationId = (int) $db->insertID();
        }

        $belowSixtyUrl = 'grading/below-60';
        $existing = $navBuilder->select('id')
            ->where('url', $belowSixtyUrl)
            ->get()
            ->getRowArray();

        if (!$existing) {
            $navBuilder->insert([
                $parentColumn => $communicationId ?: null,
                'label'        => 'Below 60 Summary',
                'url'          => $belowSixtyUrl,
                'sort_order'   => 4,
                'is_enabled'   => 1,
                'created_at'   => $now,
                'updated_at'   => $now,
            ]);
            $belowSixtyId = (int) $db->insertID();
        } else {
            $belowSixtyId = (int) $existing['id'];
        }

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

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

        $roleRows = $db->table('roles')
            ->select('id, name')
            ->whereIn('name', ['administrator', 'principal', 'vice_principal', 'admin'])
            ->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', $belowSixtyId)
                ->get()
                ->getRowArray();

            if ($exists) {
                continue;
            }

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

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

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

        $belowSixtyUrl = 'grading/below-60';
        $row = $db->table('nav_items')
            ->select('id')
            ->where('url', $belowSixtyUrl)
            ->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', $belowSixtyUrl)
            ->delete();
    }
}
