<?php

namespace App\Http\Controllers\Superadmin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Role;
use App\Models\School;
use App\Models\Kcd;
use App\Models\Employee;
use App\Models\SupervisorKcdAssignment;
use App\Models\SupervisorSchoolAssignment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    /**
     * Display a listing of users.
     */
    public function index()
    {
        $users = User::with('role', 'kcdAssignments.kcd', 'schoolAssignments.school')
            ->latest()
            ->get();
        return view('superadmin.users.index', compact('users'));
    }

    /**
     * Show the form for creating a new user.
     */
    public function create()
    {
        $roles = Role::all();
        $schools = School::where('is_active', true)->orderBy('name')->get();
        $kcds = Kcd::where('is_active', true)->orderBy('code')->get();
        $employees = Employee::where('is_active', true)->orderBy('name')->get();
        
        // Pass role constants to view
        $roleConstants = [
            'SLUG_PENGAWAS' => Role::SLUG_PENGAWAS,
            'SLUG_ADMIN_SEKOLAH' => Role::SLUG_ADMIN_SEKOLAH,
            'SLUG_ADMIN_KCD' => Role::SLUG_ADMIN_KCD,
            'SLUG_SUPERADMIN' => Role::SLUG_SUPERADMIN,
            'SLUG_ADMIN_DINAS' => Role::SLUG_ADMIN_DINAS,
        ];
        
        return view('superadmin.users.create', compact('roles', 'schools', 'kcds', 'employees', 'roleConstants'));
    }

    /**
     * Store a newly created user in storage.
     */
    public function store(Request $request)
    {
        // Check role slug
        $role = Role::find($request->role_id);
        $isAdminSekolah = $role && $role->slug === Role::SLUG_ADMIN_SEKOLAH;
        $isAdminKcd = $role && $role->slug === Role::SLUG_ADMIN_KCD;
        $isPengawas = $role && $role->slug === Role::SLUG_PENGAWAS;

        $validated = $request->validate([
            'role_id' => 'required|exists:roles,id',
            'kcd_id' => $isAdminKcd ? 'required|exists:kcds,id' : 'nullable|exists:kcds,id',
            'school_id' => $isAdminSekolah ? 'required|exists:schools,id' : 'nullable|exists:schools,id',
            'employee_id' => $isPengawas ? 'required|exists:employees,id' : 'nullable|exists:employees,id',
            'npsn' => $isAdminSekolah ? 'required|string|max:10|unique:users,npsn' : 'nullable|string|max:10|unique:users,npsn',
            'name' => 'required|string|max:255',
            'email' => $isAdminSekolah ? 'nullable|email|unique:users,email' : 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
            'nip' => $isAdminSekolah ? 'nullable|string|max:30|unique:users,nip' : 'required|string|max:30|unique:users,nip',
            'phone' => 'nullable|string|max:20',
            'pangkat_golongan' => $isAdminSekolah ? 'nullable|string|max:100' : 'required|string|max:100',
            'alamat' => 'nullable|string|max:255',
            'is_active' => 'boolean',
        ]);

        // Auto-fill name from employee for pengawas
        if ($isPengawas && !empty($validated['employee_id'])) {
            $employee = Employee::find($validated['employee_id']);
            if ($employee) {
                $validated['name'] = $employee->name;
                $validated['nip'] = $employee->nip;
                $validated['phone'] = $employee->phone ?? $validated['phone'];
                $validated['email'] = $employee->email ?? $validated['email'];
            }
        }

        // Auto-fill NPSN from school for admin sekolah
        if ($isAdminSekolah && !empty($validated['school_id'])) {
            $school = School::find($validated['school_id']);
            if ($school) {
                $validated['npsn'] = $school->npsn;
                // Auto-generate email if not provided
                if (empty($validated['email'])) {
                    $validated['email'] = $school->npsn . User::DEFAULT_SCHOOL_EMAIL_DOMAIN;
                }
            }
        }

        // Store plain password before hashing for display
        $plainPassword = $validated['password'];
        
        // Determine username (NPSN for admin sekolah, email for others)
        $username = $isAdminSekolah ? $validated['npsn'] : $validated['email'];
        
        $validated['password'] = Hash::make($validated['password']);
        $validated['is_active'] = $request->has('is_active');

        $user = User::create($validated);

        return redirect()->route('superadmin.users.index')
            ->with('success', "User <strong>{$user->name}</strong> berhasil ditambahkan!<br>Username: <strong class='text-primary'>{$username}</strong><br>Password: <strong class='text-danger'>{$plainPassword}</strong><br><small class='text-muted'>Salin dan berikan kepada user untuk login pertama kali.</small>");
    }

    /**
     * Show the form for editing the specified user.
     */
    public function edit(User $user)
    {
        $roles = Role::all();
        $schools = School::where('is_active', true)->orderBy('name')->get();
        $kcds = Kcd::where('is_active', true)->orderBy('code')->get();
        $employees = Employee::where('is_active', true)->orderBy('name')->get();
        $user->load('kcdAssignments', 'schoolAssignments', 'school', 'kcd', 'employee');
        
        // Pass role constants to view
        $roleConstants = [
            'SLUG_PENGAWAS' => Role::SLUG_PENGAWAS,
            'SLUG_ADMIN_SEKOLAH' => Role::SLUG_ADMIN_SEKOLAH,
            'SLUG_ADMIN_KCD' => Role::SLUG_ADMIN_KCD,
            'SLUG_SUPERADMIN' => Role::SLUG_SUPERADMIN,
            'SLUG_ADMIN_DINAS' => Role::SLUG_ADMIN_DINAS,
        ];
        
        return view('superadmin.users.edit', compact('user', 'roles', 'schools', 'kcds', 'employees', 'roleConstants'));
    }

    /**
     * Update the specified user in storage.
     */
    public function update(Request $request, User $user)
    {
        // Check role slug
        $role = Role::find($request->role_id);
        $isAdminSekolah = $role && $role->slug === Role::SLUG_ADMIN_SEKOLAH;
        $isAdminKcd = $role && $role->slug === Role::SLUG_ADMIN_KCD;
        $isPengawas = $role && $role->slug === Role::SLUG_PENGAWAS;

        $validated = $request->validate([
            'role_id' => 'required|exists:roles,id',
            'kcd_id' => $isAdminKcd ? 'required|exists:kcds,id' : 'nullable|exists:kcds,id',
            'school_id' => $isAdminSekolah ? 'required|exists:schools,id' : 'nullable|exists:schools,id',
            'employee_id' => $isPengawas ? 'required|exists:employees,id' : 'nullable|exists:employees,id',
            'npsn' => [
                $isAdminSekolah ? 'required' : 'nullable',
                'string',
                'max:10',
                Rule::unique('users')->ignore($user->id)
            ],
            'name' => 'required|string|max:255',
            'email' => [
                $isAdminSekolah ? 'nullable' : 'required',
                'email',
                Rule::unique('users')->ignore($user->id)
            ],
            'password' => 'nullable|string|min:8|confirmed',
            'nip' => [
                $isAdminSekolah ? 'nullable' : 'required',
                'string',
                'max:30',
                Rule::unique('users')->ignore($user->id)
            ],
            'phone' => 'nullable|string|max:20',
            'pangkat_golongan' => $isAdminSekolah ? 'nullable|string|max:100' : 'required|string|max:100',
            'alamat' => 'nullable|string|max:255',
            'is_active' => 'boolean',
            'kcd_ids' => 'nullable|array',
            'kcd_ids.*' => 'exists:kcds,id',
            'school_ids' => 'nullable|array',
            'school_ids.*' => 'exists:schools,npsn',
        ]);

        // Auto-fill NPSN from school for admin sekolah
        if ($isAdminSekolah && !empty($validated['school_id'])) {
            $school = School::find($validated['school_id']);
            if ($school) {
                $validated['npsn'] = $school->npsn;
                // Auto-generate email if not provided
                if (empty($validated['email'])) {
                    $validated['email'] = $school->npsn . User::DEFAULT_SCHOOL_EMAIL_DOMAIN;
                }
            }
        }

        if (!empty($validated['password'])) {
            $validated['password'] = Hash::make($validated['password']);
        } else {
            unset($validated['password']);
        }

        $validated['is_active'] = $request->has('is_active');

        $user->update($validated);

        // Update KCD assignments
        if ($request->has('kcd_ids')) {
            // Delete existing assignments
            SupervisorKcdAssignment::where('user_id', $user->id)->delete();
            
            // Create new assignments
            if (!empty($request->kcd_ids)) {
                foreach ($request->kcd_ids as $kcd_id) {
                    SupervisorKcdAssignment::create([
                        'user_id' => $user->id,
                        'kcd_id' => $kcd_id,
                        'assigned_by' => Auth::id(),
                        'assigned_date' => now(),
                        'is_active' => true,
                    ]);
                }
            }
        }

        // Update school assignments
        if ($request->has('school_ids')) {
            // Delete existing assignments
            SupervisorSchoolAssignment::where('user_id', $user->id)->delete();
            
            // Create new assignments
            if (!empty($request->school_ids)) {
                foreach ($request->school_ids as $npsn) {
                    $school = School::where('npsn', $npsn)->first();
                    if ($school) {
                        SupervisorSchoolAssignment::create([
                            'user_id' => $user->id,
                            'school_id' => $school->id,
                            'kcd_id' => $request->kcd_ids[0] ?? null,
                            'assigned_by' => Auth::id(),
                            'assigned_date' => now(),
                            'is_active' => true,
                        ]);
                    }
                }
            }
        }

        return redirect()->route('superadmin.users.index')
            ->with('success', 'User berhasil diperbarui!');
    }

    /**
     * Remove the specified user from storage.
     */
    public function destroy(User $user)
    {
        // Prevent deleting own account
        if ($user->id === auth()->id()) {
            return redirect()->route('superadmin.users.index')
                ->with('error', 'Anda tidak dapat menghapus akun sendiri!');
        }

        $user->delete();

        return redirect()->route('superadmin.users.index')
            ->with('success', 'User berhasil dihapus!');
    }

    /**
     * Reset password for the specified user.
     */
    public function resetPassword(User $user)
    {
        // Prevent resetting own password via this method
        if ($user->id === auth()->id()) {
            return redirect()->route('superadmin.users.index')
                ->with('error', 'Gunakan menu profil untuk mengubah password Anda sendiri!');
        }

        // Generate random 8-character password
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $newPassword = '';
        for ($i = 0; $i < 8; $i++) {
            $newPassword .= $characters[rand(0, strlen($characters) - 1)];
        }

        // Update user password
        $user->update([
            'password' => Hash::make($newPassword)
        ]);

        return redirect()->route('superadmin.users.index')
            ->with('success', "Password untuk user <strong>{$user->name}</strong> berhasil direset!<br>Password baru: <strong class='text-danger'>{$newPassword}</strong><br><small class='text-muted'>Salin dan berikan kepada user.</small>");
    }
}
