<?php

namespace Modules\Role\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddBookingDiscountPermission extends Migration
{
    public function up()
    {
        $menuExists = $this->db->table('menus')
            ->where('menu_title', 'booking_discount')
            ->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'     => 'booking_discount',
            'page_url'       => 'ticket/booking/discount',
            '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', 'booking_discount')
                ->countAllResults();

            if ($permExists > 0) {
                continue;
            }

            $grantCreate = $roleId === 1 ? 1 : 0;

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

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

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