<?php

namespace App\Http\Controllers\AdminKcd;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeAssignment;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class PengawasController extends Controller
{
    /**
     * Display a listing of pengawas (employees assigned to this KCD).
     */
    public function index()
    {
        // Get current admin KCD's kcd_id
        $kcdId = Auth::user()->kcd_id;
        
        if (!$kcdId) {
            return view('admin-kcd.pengawas', ['pengawas' => collect()]);
        }
        
        // Get employees assigned to this KCD
        $pengawas = Employee::whereHas('assignments', function ($query) use ($kcdId) {
                $query->where('kcd_id', $kcdId)
                      ->where('is_active', true);
            })
            ->with(['assignments' => function ($query) use ($kcdId) {
                $query->where('kcd_id', $kcdId);
            }, 'user'])
            ->where('is_active', true)
            ->latest()
            ->get();
        
        return view('admin-kcd.pengawas', compact('pengawas'));
    }

    /**
     * Reset password for the specified pengawas (employee's user account).
     */
    public function resetPassword(Employee $employee)
    {
        // Verify employee has user account
        $user = User::where('employee_id', $employee->id)->first();
        
        if (!$user) {
            return redirect()->route('admin-kcd.pengawas')
                ->with('error', 'Pegawai belum memiliki akun user!');
        }

        // Verify employee is assigned to same KCD
        $kcdId = Auth::user()->kcd_id;
        $hasAssignment = EmployeeAssignment::where('employee_id', $employee->id)
            ->where('kcd_id', $kcdId)
            ->where('is_active', true)
            ->exists();
            
        if (!$hasAssignment) {
            return redirect()->route('admin-kcd.pengawas')
                ->with('error', 'Anda tidak memiliki akses untuk pegawai ini!');
        }

        // 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('admin-kcd.pengawas')
            ->with('success', "Password untuk pengawas <strong>{$employee->name}</strong> berhasil direset!<br>Password baru: <strong class='text-danger'>{$newPassword}</strong><br><small class='text-muted'>Salin dan berikan kepada pengawas.</small>");
    }
}
