<?php

namespace Modules\Ticket\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Permission slug: manage_global_cancellation_policy
 * Assign via Role → permissions (not for company roles). Company users (role 7) are blocked in code.
 */
class AddManageGlobalCancellationPolicyMenu extends Migration
{
    public function up()
    {
        $db = $this->db;
        if ($db->table('menus')->where('menu_title', 'manage_global_cancellation_policy')->where('deleted_at', null)->countAllResults() > 0) {
            return;
        }

        $parent = $db->table('menus')
            ->select('id')
            ->where('menu_title', 'role')
            ->where('deleted_at', null)
            ->get()
            ->getRow();
        if (! $parent) {
            return;
        }

        $db->table('menus')->insert([
            'menu_title'      => 'manage_global_cancellation_policy',
            'page_url'        => 'cancellation/cancellation/globalpolicy',
            'module_name'     => 'Cancellation',
            'parent_menu_id'  => (string) $parent->id,
            'have_chield'     => null,
            'created_by'      => '1',
            'created_at'      => date('Y-m-d H:i:s'),
            'updated_at'      => date('Y-m-d H:i:s'),
            'deleted_at'      => null,
        ]);
        $menuId = $db->insertID();

        if ($db->table('permissions')->where('menu_id', $menuId)->where('role_id', 1)->where('deleted_at', null)->countAllResults() > 0) {
            return;
        }

        $db->table('permissions')->insert([
            'role_id'    => 1,
            'user_id'    => 1,
            'menu_id'    => $menuId,
            'menu_title' => 'manage_global_cancellation_policy',
            'create'     => '1',
            'read'       => '1',
            'edit'       => '1',
            'delete'     => '0',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'deleted_at' => null,
        ]);
    }

    public function down()
    {
        $row = $this->db->table('menus')->where('menu_title', 'manage_global_cancellation_policy')->get()->getRow();
        if ($row) {
            $this->db->table('permissions')->where('menu_id', $row->id)->delete();
            $this->db->table('menus')->where('id', $row->id)->delete();
        }
    }
}
