<?php

namespace Modules\Role\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddJourneyListBackdatedPermission extends Migration
{
    /** Roles that had backdated journey list before permission-based control. */
    private const DEFAULT_BACKDATE_ROLE_IDS = [1, 7];

    public function up()
    {
        $menuExists = $this->db->table('menus')
            ->where('menu_title', 'journey_list_backdated')
            ->countAllResults();

        if ($menuExists > 0) {
            return;
        }

        $parent = $this->db->table('menus')
            ->where('menu_title', 'ticket_booking')
            ->get()
            ->getRow();

        $parentId = $parent ? (int) $parent->id : null;
        $now = date('Y-m-d H:i:s');

        $this->db->table('menus')->insert([
            'menu_title'     => 'journey_list_backdated',
            'page_url'       => 'ticket/booking/journeylist',
            'module_name'    => 'Ticket',
            'parent_menu_id' => $parentId,
            'have_chield'    => null,
            'created_by'     => 1,
            'created_at'     => $now,
            'updated_at'     => $now,
        ]);

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

        $roleIds = $this->db->table('roles')->select('id')->get()->getResultArray();
        foreach ($roleIds as $row) {
            $roleId = (int) ($row['id'] ?? 0);
            if ($roleId < 1) {
                continue;
            }

            $permExists = $this->db->table('permissions')
                ->where('role_id', $roleId)
                ->where('menu_title', 'journey_list_backdated')
                ->countAllResults();

            if ($permExists > 0) {
                continue;
            }

            $grantRead = in_array($roleId, self::DEFAULT_BACKDATE_ROLE_IDS, true) ? 1 : 0;

            $this->db->table('permissions')->insert([
                'role_id'    => $roleId,
                'user_id'    => 1,
                'menu_id'    => $menuId,
                'menu_title' => 'journey_list_backdated',
                'create'     => 0,
                'read'       => $grantRead,
                'edit'       => 0,
                'delete'     => 0,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }
    }

    public function down()
    {
        $menu = $this->db->table('menus')
            ->where('menu_title', 'journey_list_backdated')
            ->get()
            ->getRow();

        if ($menu) {
            $this->db->table('permissions')->where('menu_id', (int) $menu->id)->delete();
            $this->db->table('permissions')->where('menu_title', 'journey_list_backdated')->delete();
            $this->db->table('menus')->where('id', (int) $menu->id)->delete();
        }
    }
}
