<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Instansi;
use App\Models\User;
use App\Models\Absensi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class InstansiController extends Controller
{
    public function index()
    {
        $instansis = Instansi::withCount('karyawans')->get();
        return view('admin.instansi.index', compact('instansis'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'nama_instansi' => 'required|unique:instansis,nama_instansi',
            'alamat'        => 'nullable|string|max:500',
            'email'         => 'required|email|unique:users,email',
            'password'      => 'required|min:6',
            'latitude'      => 'required|numeric',
            'longitude'     => 'required|numeric',
            'radius_meter'  => 'required|numeric|min:10',
        ]);

        DB::transaction(function () use ($request) {
            $instansi = Instansi::create([
                'nama_instansi' => $request->nama_instansi,
                'alamat'        => $request->alamat,
                'latitude'      => $request->latitude,
                'longitude'     => $request->longitude,
                'radius_meter'  => $request->radius_meter,
            ]);

            User::create([
                'name'        => $request->nama_instansi,
                'email'       => $request->email,
                'password'    => Hash::make($request->password),
                'role'        => 'instansi',
                'instansi_id' => $instansi->id,
            ]);
        });

        if ($request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Instansi berhasil dibuat.']);
        }

        return redirect()->route('admin.instansi.index')
            ->with('success', 'Instansi berhasil dibuat.');
    }

    public function update(Request $request, Instansi $instansi)
    {
        $request->validate([
            'nama_instansi' => 'required|unique:instansis,nama_instansi,' . $instansi->id,
            'alamat'        => 'nullable|string|max:500',
            'latitude'      => 'required|numeric',
            'longitude'     => 'required|numeric',
            'radius_meter'  => 'required|numeric|min:10',
            'email'         => 'nullable|email|unique:users,email,' . optional($instansi->users->first())->id,
            'password'      => 'nullable|min:6',
        ]);

        $instansi->update([
            'nama_instansi' => $request->nama_instansi,
            'alamat'        => $request->alamat,
            'latitude'      => $request->latitude,
            'longitude'     => $request->longitude,
            'radius_meter'  => $request->radius_meter,
        ]);

        // Update user jika email/password diisi
        $user = $instansi->users()->first();
        if ($user) {
            $userData = [];
            if ($request->filled('email'))    $userData['email']    = $request->email;
            if ($request->filled('password')) $userData['password'] = Hash::make($request->password);
            if ($userData) $user->update($userData);
        }

        if ($request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Instansi berhasil diperbarui.']);
        }

        return redirect()->route('admin.instansi.index')
            ->with('success', 'Instansi berhasil diperbarui.');
    }

    public function destroy(Instansi $instansi, Request $request)
    {
        $instansi->delete();

        if ($request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Instansi berhasil dihapus.']);
        }

        return redirect()->route('admin.instansi.index')
            ->with('success', 'Instansi berhasil dihapus.');
    }

public function show(Instansi $instansi)
{
    $instansi->loadCount('karyawans')->load('karyawans.jabatan', 'users');
    return view('admin.instansi.show', compact('instansi'));
}
} 