<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Models\Employee;
use App\Models\Position;
use App\Models\User;

class EmployeeController extends Controller
{
    /**
     * Menampilkan daftar karyawan beserta relasi jabatan dan user
     */
    public function index(Request $request)
    {
        try {
            $query = Employee::with(['branch', 'position', 'user', 'salary']);

            // Isolasi Cabang: Jika bukan Owner/SuperAdmin, filter berdasarkan cabang
            if ($request->has('branch_id') && !empty($request->branch_id)) {
                $query->where('branch_id', $request->branch_id);
            }

            $employees = $query->orderBy('employee_code', 'asc')->get();
            
            return response()->json([
                'success' => true, 
                'data' => $employees
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Menyimpan Karyawan Baru (Dengan Auto-Sync User Login)
     */
    public function store(Request $request)
    {
        $request->validate([
            'employee_code' => 'required|string|unique:employees,employee_code',
            'name'          => 'required|string|max:255',
            'position_id'   => 'required|exists:positions,id',
            'branch_id'     => 'required|exists:branches,id',
            'username'      => 'nullable|string|unique:users,username',
            'password'      => 'nullable|string|min:6'
        ]);

        DB::beginTransaction();
        try {
            $position = Position::findOrFail($request->position_id);
            $userId = null;

            // ==============================================================
            // LOGIKA SINKRONISASI: Bikin Akun Jika Jabatan Mengizinkan
            // ==============================================================
            if ($position->has_system_access) {
                if (empty($request->username) || empty($request->password)) {
                    throw new \Exception("Jabatan {$position->name} mewajibkan akses sistem. Username dan Password tidak boleh kosong.");
                }

                $user = User::create([
                    'name'      => $request->name,
                    'username'  => $request->username,
                    'password'  => Hash::make($request->password),
                    'role'      => $position->system_role ?? 'staff',
                    'branch_id' => $request->branch_id,
                    'whatsapp'  => $request->phone ?? null,
                    'is_active' => true,
                ]);

                // PENTING: Jika Anda pakai Spatie, assign role ke user baru
                if ($position->system_role) {
                    $user->assignRole($position->system_role);
                }

                $userId = $user->id;
            }

            // Simpan Data Master Karyawan
            Employee::create([
                'employee_code' => $request->employee_code,
                'name'          => $request->name,
                'position_id'   => $position->id,
                'branch_id'     => $request->branch_id,
                'user_id'       => $userId, // Terhubung dengan user ID jika ada
                'phone'         => $request->phone,
                'address'       => $request->address,
                'is_active'     => true,
            ]);

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data karyawan berhasil disimpan.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Memperbarui Data Karyawan (Termasuk Status Aktif/Non-Aktif User)
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'employee_code' => 'required|string|unique:employees,employee_code,' . $id,
            'name'          => 'required|string|max:255',
            'position_id'   => 'required|exists:positions,id',
            'branch_id'     => 'required|exists:branches,id',
            'is_active'     => 'required|boolean'
        ]);

        DB::beginTransaction();
        try {
            $employee = Employee::findOrFail($id);
            $position = Position::findOrFail($request->position_id);

            // Update Master Karyawan
            $employee->update([
                'employee_code' => $request->employee_code,
                'name'          => $request->name,
                'position_id'   => $position->id,
                'branch_id'     => $request->branch_id,
                'phone'         => $request->phone,
                'address'       => $request->address,
                'is_active'     => $request->is_active,
            ]);

            // ==============================================================
            // LOGIKA UPDATE SINKRONISASI USER (Termasuk Resign/Non-Aktif)
            // ==============================================================
            if ($employee->user_id) {
                $userUpdateData = [
                    'name'      => $request->name,
                    'branch_id' => $request->branch_id,
                    'is_active' => $request->is_active, // Sync status aktif / non-aktif
                ];

                if (!empty($request->password)) {
                    $userUpdateData['password'] = Hash::make($request->password);
                }

                if ($position->has_system_access && $position->system_role) {
                    $userUpdateData['role'] = $position->system_role;
                }

                $user = User::find($employee->user_id);
                if ($user) {
                    $user->update($userUpdateData);
                    
                    // Sync Spatie Role jika berubah
                    if ($position->has_system_access && $position->system_role) {
                        $user->syncRoles([$position->system_role]);
                    }
                }
            }

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data karyawan berhasil diperbarui.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Update Setup Gaji Pokok & BPJS
     */
    public function updateSalary(Request $request, $id)
    {
        $request->validate([
            'salary_type'                 => 'required|in:monthly,daily',
            'has_bpjs'                    => 'required|boolean', // TAMBAHAN BPJS
            'bpjs_kesehatan_number'       => 'nullable|string|max:50',
            'bpjs_ketenagakerjaan_number' => 'nullable|string|max:50',
            'base_salary'                 => 'required|numeric',
            'meal_allowance'              => 'nullable|numeric',
            'transport_allowance'         => 'nullable|numeric',
            'bank_name'                   => 'nullable|string|max:100',
            'bank_account_number'         => 'nullable|string|max:50',
            'bank_account_name'           => 'nullable|string|max:255',
        ]);

        try {
            $employee = Employee::findOrFail($id);
            
            \App\Models\EmployeeSalary::updateOrCreate(
                ['employee_id' => $employee->id],
                [
                    'salary_type'                 => $request->salary_type,
                    'has_bpjs'                    => $request->has_bpjs,
                    'bpjs_kesehatan_number'       => $request->bpjs_kesehatan_number,
                    'bpjs_ketenagakerjaan_number' => $request->bpjs_ketenagakerjaan_number,
                    'base_salary'                 => $request->base_salary,
                    'meal_allowance'              => $request->meal_allowance ?? 0,
                    'transport_allowance'         => $request->transport_allowance ?? 0,
                    'bank_name'                   => $request->bank_name,
                    'bank_account_number'         => $request->bank_account_number,
                    'bank_account_name'           => $request->bank_account_name,
                ]
            );

            return response()->json(['success' => true, 'message' => 'Setup Gaji & BPJS Karyawan berhasil diperbarui.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Hapus Karyawan
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $employee = Employee::findOrFail($id);
            
            // Opsional: Matikan akses user jika karyawan dihapus
            if ($employee->user_id) {
                User::where('id', $employee->user_id)->update(['is_active' => false]);
            }

            $employee->delete();
            
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data karyawan berhasil dihapus.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Karyawan tidak dapat dihapus karena sudah memiliki histori transaksi.'], 500);
        }
    }
}