<?php

namespace Modules\Ticket\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Role permission slug: manage_online_refunds (online refund list — UI to be built later).
 */
class AddManageOnlineRefundsPermission extends Migration
{
    public function up()
    {
        $db = $this->db;
        $exists = $db->table('menus')
            ->where('menu_title', 'manage_online_refunds')
            ->where('deleted_at', null)
            ->countAllResults();
        if ($exists > 0) {
            return;
        }

        $parent = $db->table('menus')
            ->select('id')
            ->where('menu_title', 'ticket_booking')
            ->where('deleted_at', null)
            ->get()
            ->getRow();

        if (! $parent) {
            return;
        }

        $db->table('menus')->insert([
            'menu_title'      => 'manage_online_refunds',
            'page_url'        => 'ticket/booking/onlinerefunds',
            'module_name'     => 'Ticket',
            '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();

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

        $db->table('permissions')->insert([
            'role_id'    => 1,
            'user_id'    => 1,
            'menu_id'    => $menuId,
            'menu_title' => 'manage_online_refunds',
            '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_online_refunds')
            ->get()
            ->getRow();
        if ($row) {
            $this->db->table('permissions')->where('menu_id', $row->id)->delete();
            $this->db->table('menus')->where('id', $row->id)->delete();
        }
    }
}
