<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeLeave;
use App\Models\EmployeeLeaveCredits;
use App\Models\EmployeeSchedule;
use App\Models\Holiday;
use App\Models\LeaveType;
use App\Models\User;
use App\Notifications\Leave;
use DateInterval;
use DatePeriod;
use DateTime;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class RoleMigrationController extends Controller
{

    public function index(Request $request)
    {
    $id = (int) $request->id;

    try {
        DB::beginTransaction();

        // Fetch roles, permissions, and company access
        $roles = \App\Models\Role::where('id', $id)->get();
        $rolesPermissions = DB::table('role_permissions')->where('role_id', $id)->get();
        $roleCompanyAccess = DB::table('role_company_access')->where('role_id', $id)->get();

        if ($roles->isEmpty() || $rolesPermissions->isEmpty() || $roleCompanyAccess->isEmpty()) {
            return response()->json([
                'message' => 'No roles, permissions, or company access found for the specified role ID.',
                'status' => 'error',
            ], 404);
        }

        $insertDataPermissions = [];
        $insertDataCompanyAccess = [];

        foreach ($roles as $role) {
            $dealers = \App\Models\Dealership::whereNotIn('id', [35])->get();

            foreach ($dealers as $dealer) {
                $roleName = match ($id) {
                    79 => 'CRM ' . trim($dealer->code) . ' - Manager',
                    85 => 'CRM ' . trim($dealer->code) . ' - SUPERVISOR',
                    84 => 'CRM ' . trim($dealer->code) . ' - ASSISTANT',
                    default => 'CRM ' . trim($dealer->code),
                };

                $roleInsert = \App\Models\Role::create([
                    'name' => $roleName,
                    'group_id' => $role->group_id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                foreach ($rolesPermissions as $rolePermission) {
                    $insertDataPermissions[] = [
                        'role_id' => $roleInsert->id,
                        'company_id' => $dealer->company_id,
                        'dealership_id' => $dealer->id,
                        'module_id' => $rolePermission->module_id,
                        'permission_id' => $rolePermission->permission_id,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }

                foreach ($roleCompanyAccess as $roleComAccess) {
                    $insertDataCompanyAccess[] = [
                        'role_id' => $roleInsert->id,
                        'company_id' => $dealer->company_id,
                        'dealership_id' => $dealer->id,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }
            }
        }

        // Chunk and insert permissions
        collect($insertDataPermissions)->chunk(500)->each(function ($chunk) {
            DB::table('role_permissions')->insert($chunk->toArray());
        });

        // Chunk and insert company access
        collect($insertDataCompanyAccess)->chunk(500)->each(function ($chunk) {
            DB::table('role_company_access')->insert($chunk->toArray());
        });

        DB::commit();

        return response()->json([
            'message' => 'Record successfully added!',
            'status' => 'success',
        ], 201);
    } catch (Exception $e) {
        DB::rollBack();
   

        return response()->json([
            'status' => false,
            'message' => 'Unable to process request. Please try again.',
            'error' => $e->getMessage(),
        ], 500);
    }
}

    // public function rolePermissions(Request $request)
    // {
    //     $id = $request->id;
    
    //     try {
    //         DB::beginTransaction();
    
    //         // Fetch all role permissions for the given role ID
    //         $rolesPermissions = DB::table('role_permissions')->where('role_id', $id)->get();
    
    //         if ($rolesPermissions->isEmpty()) {
    //             return response()->json([
    //                 'message' => 'No permissions found for the specified role.',
    //                 'status' => 'error',
    //             ], 404);
    //         }
    
    //         $dealers = \App\Models\Dealership::whereNotIn('id', [35])->get();

    //         $insertData = [];
    
    //         // Loop through each role permission and dealership to prepare the insert data
    //         foreach ($rolesPermissions as $rolePermission) {
    //             foreach ($dealers as $dealer) {
    //                 $roleDealer = \App\Models\Role::where()
    //                 $insertData[] = [
    //                     'role_id' => $id,
    //                     'company_id' => $dealer->company_id,
    //                     'dealership_id' => $dealer->id,
    //                     'module_id' => $rolePermission->module_id,
    //                     'permission_id' => $rolePermission->permission_id,
    //                     'created_at' => now(),
    //                     'updated_at' => now(),
    //                 ];
    //             }
    //         }
    
    //         // Batch insert to minimize database interactions
    //         DB::table('role_permissions')->insert($insertData);
    //         DB::commit();
    //         return response()->json([
    //             'message' => 'Record successfully added!',
    //             'status' => 'success',
    //         ], 201);
    //     } catch (Exception $e) {
    //         DB::rollBack();
    
    //         return response()->json([
    //             'status' => 'error',
    //             'message' => 'Unable to process request. Please try again.',
    //             'error' => $e->getMessage(),
    //         ], 500);
    //     }
    // }

}
