<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;

class AddPrPermissions extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Main feature permissions
        Permission::findOrCreate('purchase_requisition.access_module', 'web');
        Permission::findOrCreate('purchase_requisition.create', 'web');
        Permission::findOrCreate('purchase_requisition.view_all', 'web');
        Permission::findOrCreate('purchase_requisition.view_own', 'web');
        Permission::findOrCreate('purchase_requisition.edit', 'web');
        Permission::findOrCreate('purchase_requisition.delete', 'web');
        Permission::findOrCreate('purchase_requisition.approve', 'web');
        Permission::findOrCreate('purchase_requisition.share_with_suppliers', 'web');
        Permission::findOrCreate('purchase_requisition.make_purchase', 'web');
        Permission::findOrCreate('purchase_requisition.access_settings', 'web');

        // Location-based permissions for generation page
        $statuses = ['generate', 'index', 'approve'];
        $directions = ['from', 'to'];
        $types = ['all', 'his', 'selected'];

        foreach ($statuses as $status) {
            foreach ($directions as $direction) {
                foreach ($types as $type) {
                    $permissionName = "purchase_requisition.location_access_{$status}_{$direction}_{$type}_locations";
                    Permission::findOrCreate($permissionName, 'web');
                }
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Delete main permissions
        $mainPermissions = [
            'purchase_requisition.access_module',
            'purchase_requisition.create',
            'purchase_requisition.view_all',
            'purchase_requisition.view_own',
            'purchase_requisition.edit',
            'purchase_requisition.delete',
            'purchase_requisition.approve',
            'purchase_requisition.share_with_suppliers',
            'purchase_requisition.make_purchase',
            'purchase_requisition.access_settings',
        ];

        foreach ($mainPermissions as $permission) {
            Permission::where('name', $permission)->delete();
        }

        // Delete location-based permissions
        Permission::where('name', 'LIKE', 'purchase_requisition.location_access_%')->delete();
    }
}
