<?php

namespace App\Http\Controllers;

use App\Models\Role;
use Illuminate\Http\Request;

class AdminRoleController extends Controller
{
    /**
     * Display a listing of roles.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $roles = Role::latest('id');
        
        // Add search functionality if search parameter is provided
        if ($request->filled('search')) {
            $search = $request->input('search');
            $roles->where(function($query) use ($search) {
                $query->where('title', 'like', '%' . $search . '%')
                      ->orWhere('code', 'like', '%' . $search . '%');
            });
        }
        
        return $this->withCount($roles, "Roles retrieved successfully.");
    }

    /**
     * Store a newly created role in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = $this->roleValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }

        $validatedData = $validator->validated();
        
        // Normalize code to uppercase
        if (isset($validatedData['code'])) {
            $validatedData['code'] = strtoupper($validatedData['code']);
        }
        
        // Check if role with same code already exists
        $existingRole = Role::where('code', $validatedData['code'])
            ->where('del', '0')
            ->first();
            
        if ($existingRole) {
            return $this->error('Role with this code already exists', 422);
        }

        // Set default del value if not provided
        if (!isset($validatedData['del'])) {
            $validatedData['del'] = '0';
        }

        // Mark as admin-created (editable) role
        $validatedData['is_seeded'] = 0;

        $role = Role::create($validatedData);

        return $this->success($role, 'Role created successfully', 201);
    }

    /**
     * Display the specified role.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $role = Role::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$role) {
            return $this->notFound('Role not found', 404);
        }

        return $this->success($role, 'Role retrieved successfully');
    }

    /**
     * Update the specified role in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $validator = $this->roleValidationRequest($request, true);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }

        $validatedData = $validator->validated();
        $id = $request->input('id');

        if (!$id) {
            return $this->error('Role ID is required', 422);
        }

        $role = Role::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$role) {
            return $this->notFound('Role not found', 404);
        }

        // Check if role is seeded (non-editable)
        if ($role->is_seeded == 1) {
            return $this->error('Cannot edit this role. This role is system-defined and cannot be modified.', 403);
        }

        // Normalize code to uppercase if provided
        if (isset($validatedData['code'])) {
            $validatedData['code'] = strtoupper($validatedData['code']);
        }

        // Check if another role with same code already exists (excluding current one)
        if (isset($validatedData['code'])) {
            $existingRole = Role::where('code', $validatedData['code'])
                ->where('id', '!=', $id)
                ->where('del', '0')
                ->first();
                
            if ($existingRole) {
                return $this->error('Role with this code already exists', 422);
            }
        }

        // Remove is_seeded from update data (cannot be changed)
        unset($validatedData['is_seeded']);

        $role->update($validatedData);

        return $this->success($role->fresh(), 'Role updated successfully');
    }

    /**
     * Remove the specified role from storage (soft delete).
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Role::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$role) {
            return $this->notFound('Role not found', 404);
        }

        // Check if role is seeded (non-editable)
        if ($role->is_seeded == 1) {
            return $this->error('Cannot delete seeded role. Seeded roles are system-defined and cannot be deleted.', 403);
        }

        // Check if role is being used by any employees
        $employeesUsingRole = \App\Models\EmpCompanyDetails::where('access_role', $role->code)
            ->where('del', '0')
            ->count();
            
        if ($employeesUsingRole > 0) {
            return $this->error('Cannot delete role. It is being used by ' . $employeesUsingRole . ' employee(s).', 422);
        }

        // Soft delete by setting del to '1'
        $role->update(['del' => '1']);

        return $this->message('Role deleted successfully', 200);
    }
}

