<?php

namespace Modules\Ticket\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Permission: cancel online (passenger / website-app) tickets from the ticket list.
 * Separate from manage_online_cancellations (online cancel list + money sent).
 */
class AddCancelOnlineTicketPermission extends Migration
{
    public function up()
    {
        $db = $this->db;
        $exists = $db->table('menus')
            ->where('menu_title', 'cancel_online_ticket')
            ->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'      => 'cancel_online_ticket',
            'page_url'        => 'ticket/booking/cancel-online-ticket',
            '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' => 'cancel_online_ticket',
            'create'     => '1',
            'read'       => '1',
            'edit'       => '0',
            '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', 'cancel_online_ticket')
            ->get()
            ->getRow();
        if ($row) {
            $this->db->table('permissions')->where('menu_id', $row->id)->delete();
            $this->db->table('menus')->where('id', $row->id)->delete();
        }
    }
}
