<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AccountController extends Controller
{
    public function index()
    {
        // Fetch all users including admins
        $accounts = User::all();
        
        // Fetch all branches
        $allBranches = \App\Models\Branch::all();
        
        // Get names of branches that already have an account
        $usedBranchNames = User::whereNotNull('branch')->pluck('branch')->toArray();
        
        return view('manajemen_akun', compact('accounts', 'allBranches', 'usedBranchNames'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255', 'regex:/^[a-zA-Z0-9\s]+$/'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users', 'regex:/^[a-z0-9._%+-]+@gmail\.com$/'],
            'password' => 'required|string|min:8|max:12',
            'branch' => 'required|string|unique:users,branch',
        ], [
            'name.regex' => 'Nama lengkap hanya boleh berisi huruf, angka, dan spasi.',
            'email.regex' => 'Email harus menggunakan huruf kecil dan diakhiri dengan @gmail.com',
            'password.min' => 'Password minimal 8 karakter.',
            'password.max' => 'Password maksimal 12 karakter.',
            'branch.unique' => 'Cabang ini sudah memiliki akun terdaftar.',
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 'karyawan',
            'branch' => $request->branch,
        ]);

        return back()->with('success', 'Akun karyawan berhasil ditambahkan!');
    }

    public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $request->validate([
            'name' => ['required', 'string', 'max:255', 'regex:/^[a-zA-Z0-9\s]+$/'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$id, 'regex:/^[a-z0-9._%+-]+@gmail\.com$/'],
            'branch' => 'required|string|unique:users,branch,'.$id,
        ], [
            'name.regex' => 'Nama lengkap hanya boleh berisi huruf, angka, dan spasi.',
            'email.regex' => 'Email harus menggunakan huruf kecil dan diakhiri dengan @gmail.com',
            'branch.unique' => 'Cabang ini sudah memiliki akun terdaftar.',
        ]);

        $data = [
            'name' => $request->name,
            'email' => strtolower($request->email),
            'branch' => $request->branch,
        ];

        if ($request->filled('password')) {
            $request->validate([
                'password' => 'string|min:8|max:12'
            ], [
                'password.min' => 'Password minimal 8 karakter.',
                'password.max' => 'Password maksimal 12 karakter.',
            ]);
            $data['password'] = Hash::make($request->password);
        }

        $user->update($data);

        return back()->with('success', 'Akun karyawan berhasil diperbarui!');
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        
        // Prevent deleting the main admin if accidentally reached
        if ($user->role === 'admin') {
            return back()->with('error', 'Tidak dapat menghapus akun admin!');
        }

        $user->delete();
        return back()->with('success', 'Akun karyawan berhasil dihapus!');
    }
}
