<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function index()
    {
        $users = User::orderBy('name')->paginate(20);
        return view('admin.users.index', compact('users'));
    }

    public function create()
    {
        return view('admin.users.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'          => 'required',
            'email'         => 'required|email|unique:users',
            'password'      => 'required|min:8|confirmed',
            'role'          => 'required|in:admin,cs,technician',
            'division'      => 'required|in:JPN,FixLab,Havva',
            'phone'         => 'nullable|string',
            'is_active'     => 'boolean',
            'whatsapp_number'  => 'nullable|string',
            'telegram_chat_id' => 'nullable|string',
            'permissions'   => ['nullable','array'],
            'permissions.*' => ['string', Rule::in(array_keys(User::permissionMap()))],
        ]);
        if (!$request->has('permissions')) {
            $data['permissions'] = null;
        }
        $data['password'] = Hash::make($data['password']);
        User::create($data);
        return redirect()->route('admin.users.index')->with('success','User dibuat.');
    }

    public function show(User $user)
    {
        return view('admin.users.show', compact('user'));
    }

    public function edit(User $user)
    {
        return view('admin.users.edit', compact('user'));
    }

    public function update(Request $request, User $user)
    {
        $data = $request->validate([
            'name'             => 'required',
            'email'            => "required|email|unique:users,email,{$user->id}",
            'role'             => 'required|in:admin,cs,technician',
            'division'         => 'required|in:JPN,FixLab,Havva',
            'phone'            => 'nullable|string',
            'is_active'        => 'boolean',
            'whatsapp_number'  => 'nullable|string',
            'telegram_chat_id' => 'nullable|string',
            'permissions'      => ['nullable','array'],
            'permissions.*'    => ['string', Rule::in(array_keys(User::permissionMap()))],
        ]);
        if (!$request->has('permissions')) {
            $data['permissions'] = null;
        }
        if ($request->filled('password')) {
            $request->validate(['password' => 'min:8|confirmed']);
            $data['password'] = Hash::make($request->password);
        }
        $user->update($data);
        return redirect()->route('admin.users.index')->with('success','User diperbarui.');
    }

    public function testTelegram(Request $request)
    {
        $data = $request->validate([
            'telegram_chat_id' => 'required|string',
        ]);

        $sent = app(NotificationService::class)->sendTelegram(
            $data['telegram_chat_id'], 
            "Tes Telegram dari sistem JPN Helpdesk. Jika Anda menerima pesan ini, berarti chat ID/username sudah benar."
        );

        return response()->json([
            'success' => $sent,
            'message' => $sent
                ? 'Pesan uji Telegram berhasil dikirim. Pastikan penerima sudah membuka bot Telegram Anda.'
                : 'Gagal mengirim pesan Telegram. Periksa ID/username dan pastikan bot sudah dibuka oleh penerima.',
        ], $sent ? 200 : 422);
    }

    public function testWhatsapp(Request $request)
    {
        $data = $request->validate([
            'whatsapp_number' => 'required|string',
        ]);

        $sent = app(NotificationService::class)->sendWhatsapp(
            $data['whatsapp_number'], 
            "Tes WhatsApp dari sistem JPN Helpdesk. Jika Anda menerima pesan ini, berarti nomor WhatsApp sudah benar."
        );

        return response()->json([
            'success' => $sent,
            'message' => $sent
                ? 'Pesan uji WhatsApp berhasil dikirim.'
                : 'Gagal mengirim pesan WhatsApp. Periksa nomor dan konfigurasi provider WA.',
        ], $sent ? 200 : 422);
    }

    public function reset2fa(User $user)
    {
        $user->update(['google2fa_secret'=>null,'two_factor_enabled'=>false]);
        return back()->with('success','2FA direset.');
    }

    public function destroy(User $user)
    {
        if ($user->id === auth()->id()) return back()->withErrors(['user'=>'Tidak bisa hapus akun sendiri.']);
        $user->delete();
        return redirect()->route('admin.users.index')->with('success','User dihapus.');
    }
}
