<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\EmployeeLoan;
use App\Models\Employee;
use App\Services\AccountingService;
use Carbon\Carbon;

class EmployeeLoanController extends Controller
{
    /**
     * Tampilkan semua daftar Kasbon Karyawan
     */
    public function index(Request $request)
    {
        try {
            $query = EmployeeLoan::with(['employee.branch', 'employee.position']);

            // Isolasi berdasarkan cabang
            if ($request->has('branch_id') && !empty($request->branch_id)) {
                $query->whereHas('employee', function($q) use ($request) {
                    $q->where('branch_id', $request->branch_id);
                });
            }

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

    /**
     * Buat Kasbon Baru (Pencairan)
     */
    public function store(Request $request)
    {
        $request->validate([
            'employee_id'        => 'required|exists:employees,id',
            'loan_amount'        => 'required|numeric|min:1',
            'installment_amount' => 'required|numeric|min:1',
            'loan_date'          => 'required|date',
            'notes'              => 'nullable|string'
        ]);

        DB::beginTransaction();
        try {
            $employee = Employee::findOrFail($request->employee_id);
            $user = $request->user();

            // Generate Nomor Referensi Kasbon
            $tahunBulan = Carbon::parse($request->loan_date)->format('Ym');
            $count = EmployeeLoan::whereYear('loan_date', Carbon::parse($request->loan_date)->year)
                                 ->whereMonth('loan_date', Carbon::parse($request->loan_date)->month)
                                 ->count() + 1;
            $loanNumber = 'KSB-' . $tahunBulan . '-' . str_pad($count, 4, '0', STR_PAD_LEFT);

            // Simpan Master Kasbon
            $loan = EmployeeLoan::create([
                'employee_id'        => $employee->id,
                'loan_number'        => $loanNumber,
                'loan_amount'        => $request->loan_amount,
                'installment_amount' => $request->installment_amount,
                'remaining_balance'  => $request->loan_amount, // Saldo awal = total pinjaman
                'loan_date'          => $request->loan_date,
                'notes'              => $request->notes,
                'status'             => 'active',
                'created_by'         => $user->id ?? 1
            ]);

            // =================================================================
            // INTEGRASI AKUNTANSI: Jurnal Pengeluaran Kas untuk Kasbon
            // =================================================================
            $akunPiutangKasbon = AccountingService::getAccountId('employee_receivable_account') ?? DB::table('accounts')->where('name', 'like', '%Piutang Karyawan%')->value('id');
            $akunKasKeluar = AccountingService::getAccountId('cash_disbursement_account') ?? DB::table('accounts')->where('name', 'like', '%Kas Kecil%')->value('id');

            if ($akunPiutangKasbon && $akunKasKeluar) {
                AccountingService::log([
                    'branch_id'   => $employee->branch_id,
                    'entry_date'  => $request->loan_date,
                    'description' => "Pencairan Kasbon Karyawan: " . $employee->name,
                    'reference'   => $loanNumber,
                    'source_type' => 'EMPLOYEE_LOAN',
                    'user_id'     => $user->id ?? 1,
                    'items'       => [
                        ['account_id' => $akunPiutangKasbon, 'debit' => $request->loan_amount, 'credit' => 0], // DEBIT: Piutang Karyawan Bertambah
                        ['account_id' => $akunKasKeluar, 'debit' => 0, 'credit' => $request->loan_amount]      // KREDIT: Kas / Bank Berkurang
                    ]
                ]);
            }

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Kasbon berhasil dicatat dan Kas telah dikeluarkan.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Hapus/Batalkan Kasbon (Hanya jika belum pernah dicicil)
     */
    public function destroy($id)
    {
        try {
            $loan = EmployeeLoan::findOrFail($id);

            if ($loan->remaining_balance < $loan->loan_amount) {
                return response()->json(['success' => false, 'message' => 'Kasbon tidak dapat dibatalkan karena sudah mulai dicicil melalui Payroll.'], 400);
            }

            // TODO: Reverse Jurnal Akuntansi jika diperlukan
            $loan->delete();

            return response()->json(['success' => true, 'message' => 'Data Kasbon berhasil dibatalkan.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}