<?php

namespace App\Http\Controllers\Instansi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Karyawan;
use App\Models\Jabatan;
use App\Models\JamKerja;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class KaryawanController extends Controller
{
    // ── INDEX ──────────────────────────────────────────────────────────────
    public function index()
    {
        $instansiId = Auth::user()->instansi_id;

        $karyawan = Karyawan::with(['user', 'jabatan', 'jamKerja'])
            ->where('instansi_id', $instansiId)->get();
        $jabatan  = Jabatan::where('instansi_id', $instansiId)->get();
        $jamKerja = JamKerja::where('instansi_id', $instansiId)->get();

        return view('instansi.karyawan.index', compact('karyawan', 'jabatan', 'jamKerja'));
    }

    // ── CREATE (halaman form, jika masih dipakai) ──────────────────────────
    public function create()
    {
        $instansiId = Auth::user()->instansi_id;

        $jabatans  = Jabatan::where('instansi_id', $instansiId)->get();
        $jamKerjas = JamKerja::where('instansi_id', $instansiId)->get();

        return view('instansi.karyawan.create', compact('jabatans', 'jamKerjas'));
    }

    // ── STORE ──────────────────────────────────────────────────────────────
    public function store(Request $request)
    {
        $request->validate([
            'nip'          => 'required|string|max:50',
            'nama'         => 'required|string|max:100',
            'email'        => 'required|email|unique:users,email',
            'password'     => 'required|min:6',
            'jabatan_id'   => 'required|exists:jabatans,id',
            'jam_kerja_id' => 'required|exists:jam_kerjas,id',
            'no_hp'        => 'required|string|max:20',
            'alamat'       => 'required|string',
        ]);

        $instansiId = Auth::user()->instansi_id;

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

        Karyawan::create([
            'user_id'      => $user->id,
            'instansi_id'  => $instansiId,
            'jabatan_id'   => $request->jabatan_id,
            'jam_kerja_id' => $request->jam_kerja_id,
            'nip'          => $request->nip,
            'nama'         => $request->nama,
            'no_hp'        => $request->no_hp,
            'alamat'       => $request->alamat,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Karyawan berhasil ditambahkan',
        ]);
    }

    // ── EDIT DATA (AJAX — dipanggil dari modal edit di index) ──────────────
    // Route: GET /instansi/karyawan/{id}/edit-data
    public function editData($id)
    {
        $instansiId = Auth::user()->instansi_id;

        $karyawan = Karyawan::with('user')
            ->where('instansi_id', $instansiId)
            ->findOrFail($id);

        return response()->json([
            'success'  => true,
            'karyawan' => [
                'id'           => $karyawan->id,
                'nama'         => $karyawan->nama,
                'nip'          => $karyawan->nip,
                'no_hp'        => $karyawan->no_hp,
                'alamat'       => $karyawan->alamat,
                'jabatan_id'   => $karyawan->jabatan_id,
                'jam_kerja_id' => $karyawan->jam_kerja_id,
                'email'        => $karyawan->user->email ?? '',
            ],
        ]);
    }

    // ── EDIT (halaman terpisah, fallback jika JS gagal) ────────────────────
    public function edit($id)
    {
        $instansiId = Auth::user()->instansi_id;

        $karyawan  = Karyawan::with('user')
            ->where('instansi_id', $instansiId)
            ->findOrFail($id);
        $jabatans  = Jabatan::where('instansi_id', $instansiId)->get();
        $jamKerjas = JamKerja::where('instansi_id', $instansiId)->get();

        // Kalau request AJAX (dari modal JS), return JSON
        if (request()->expectsJson() || request()->ajax()) {
            return response()->json([
                'success'  => true,
                'karyawan' => [
                    'id'           => $karyawan->id,
                    'nama'         => $karyawan->nama,
                    'nip'          => $karyawan->nip,
                    'no_hp'        => $karyawan->no_hp,
                    'alamat'       => $karyawan->alamat,
                    'jabatan_id'   => $karyawan->jabatan_id,
                    'jam_kerja_id' => $karyawan->jam_kerja_id,
                    'email'        => $karyawan->user->email ?? '',
                ],
            ]);
        }

        return view('instansi.karyawan.edit', compact('karyawan', 'jabatans', 'jamKerjas'));
    }

    // ── UPDATE ─────────────────────────────────────────────────────────────
    public function update(Request $request, $id)
    {
        $instansiId = Auth::user()->instansi_id;

        $karyawan = Karyawan::where('instansi_id', $instansiId)->findOrFail($id);

        $request->validate([
            'nip'          => 'required|string|max:50',
            'nama'         => 'required|string|max:100',
            'email'        => 'required|email|unique:users,email,' . $karyawan->user_id,
            'password'     => 'nullable|min:6',
            'jabatan_id'   => 'required|exists:jabatans,id',
            'jam_kerja_id' => 'required|exists:jam_kerjas,id',
            'no_hp'        => 'required|string|max:20',
            'alamat'       => 'required|string',
        ]);

        // Update data karyawan
        $karyawan->update([
            'jabatan_id'   => $request->jabatan_id,
            'jam_kerja_id' => $request->jam_kerja_id,
            'nip'          => $request->nip,
            'nama'         => $request->nama,
            'no_hp'        => $request->no_hp,
            'alamat'       => $request->alamat,
        ]);

        // Update user (email & password)
        $userData = [
            'name'  => $request->nama,
            'email' => $request->email,
        ];
        if ($request->filled('password')) {
            $userData['password'] = Hash::make($request->password);
        }
        $karyawan->user->update($userData);

        return response()->json([
            'success' => true,
            'message' => 'Data karyawan berhasil diperbarui',
        ]);
    }

    // ── SHOW ───────────────────────────────────────────────────────────────
    public function show($id)
    {
        $instansiId = Auth::user()->instansi_id;

        $karyawan = Karyawan::with(['user', 'jabatan', 'jamKerja'])
            ->where('instansi_id', $instansiId)
            ->findOrFail($id);

        // Riwayat absensi 30 hari terakhir
        $absensi = \App\Models\Absensi::where('karyawan_id', $karyawan->id)
            ->orderByDesc('tanggal')
            ->limit(30)
            ->get();

        // Statistik bulan ini
        $bulanIni    = now()->month;
        $tahunIni    = now()->year;
        $totalHadir  = \App\Models\Absensi::where('karyawan_id', $karyawan->id)
                        ->whereMonth('tanggal', $bulanIni)->whereYear('tanggal', $tahunIni)
                        ->whereNotNull('jam_masuk')->count();
        $totalTerlambat = \App\Models\Absensi::where('karyawan_id', $karyawan->id)
                        ->whereMonth('tanggal', $bulanIni)->whereYear('tanggal', $tahunIni)
                        ->where('status_waktu', 'terlambat')->count();

        return view('instansi.karyawan.show', compact('karyawan', 'absensi', 'totalHadir', 'totalTerlambat'));
    }

    // ── DESTROY ────────────────────────────────────────────────────────────
    public function destroy($id)
    {
        $instansiId = Auth::user()->instansi_id;

        $karyawan = Karyawan::where('instansi_id', $instansiId)->findOrFail($id);

        // Hapus user terkait (cascade)
        $karyawan->user?->delete();
        $karyawan->delete();

        return response()->json([
            'success' => true,
            'message' => 'Karyawan berhasil dihapus',
        ]);
    }
}