<?php
// app/Http/Controllers/Payroll/LoanController.php
namespace App\Modules\HR\Payroll\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\PLATFORM\Settings\Models\Branch;
use App\Modules\HR\Payroll\Models\Loan;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Yajra\DataTables\Facades\DataTables;

class LoanController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            return DataTables::of(Loan::query()->orderBy('sort_order'))
                ->addIndexColumn()
                ->editColumn('status', fn($r) =>
                    $r->status
                        ? '<span class="badge bg-success">Active</span>'
                        : '<span class="badge bg-danger">Inactive</span>'
                )
                ->addColumn('action', fn($row) =>
                    view('payroll::loans/partials/actions', compact('row'))->render()
                )
                ->rawColumns(['status','action'])
                ->make(true);
        }

        return view('payroll::loans/index');
    }

    public function create()
    {
        return view('payroll::loans/create', [
            'branches' => Branch::where('status', true)->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'branch_id' => 'nullable|exists:branches,id',
            'code' => ['required', 'max:50', Rule::unique('loans')->where(function ($query) use ($request) {
                return $request->branch_id
                    ? $query->where('branch_id', $request->branch_id)
                    : $query->whereNull('branch_id');
            })],
            'name' => 'required|max:150',
            'description' => 'nullable|string',

            'min_amount' => 'nullable|numeric|min:0',
            'max_amount' => 'nullable|numeric|gte:min_amount',

            'min_installments' => 'nullable|integer|min:1',
            'max_installments' => 'nullable|integer|gte:min_installments',

            'interest_type' => 'required|in:NONE,FIXED,REDUCING',
            'interest_rate' => 'nullable|numeric|min:0',

            'recovery_start' => 'required|in:IMMEDIATE,NEXT_MONTH',
            'recovery_frequency' => 'required|in:MONTHLY,BIWEEKLY',
            'allow_partial_recovery' => 'boolean',

            'deduction_code' => 'nullable|string|max:50',

            'requires_approval' => 'boolean',
            'approval_levels' => 'nullable|integer|min:1',

            'sort_order' => 'nullable|integer|min:0',
            'effective_from' => 'nullable|date',
            'effective_to' => 'nullable|date|after_or_equal:effective_from',
        ]);

        if (! $request->boolean('requires_approval')) {
            $data['approval_levels'] = null;
        }

        $data['status'] = $request->boolean('status');
        $data['allow_partial_recovery'] = $request->boolean('allow_partial_recovery');
        $data['is_salary_advance'] = $request->boolean('is_salary_advance');
        $data['requires_approval'] = $request->boolean('requires_approval');

        Loan::create($data);

        return response()->json(['status'=>true,'message'=>'Loan created successfully']);
    }

    public function edit(Loan $loan)
    {
        return view('payroll::loans/edit', [
            'loan'   => $loan,
            'branches' => Branch::where('status', true)->orderBy('name')->get(),
        ]);
    }

    public function update(Request $request, Loan $loan)
    {
        $data = $request->validate([
            'branch_id' => 'nullable|exists:branches,id',
            'code' => ['required', 'max:50', Rule::unique('loans')->where(function ($query) use ($loan) {
                return $loan->branch_id
                    ? $query->where('branch_id', $loan->branch_id)
                    : $query->whereNull('branch_id');
            })->ignore($loan->id)],
            'name' => 'required|max:150',
            'description' => 'nullable|string',

            'min_amount' => 'nullable|numeric|min:0',
            'max_amount' => 'nullable|numeric|gte:min_amount',

            'min_installments' => 'nullable|integer|min:1',
            'max_installments' => 'nullable|integer|gte:min_installments',

            'interest_type' => 'required|in:NONE,FIXED,REDUCING',
            'interest_rate' => 'nullable|numeric|min:0',

            'recovery_start' => 'required|in:IMMEDIATE,NEXT_MONTH',
            'recovery_frequency' => 'required|in:MONTHLY,BIWEEKLY',
            'allow_partial_recovery' => 'boolean',

            'deduction_code' => 'nullable|string|max:50',

            'requires_approval' => 'boolean',
            'approval_levels' => 'nullable|integer|min:1',

            'sort_order' => 'nullable|integer|min:0',
            'effective_from' => 'nullable|date',
            'effective_to' => 'nullable|date|after_or_equal:effective_from',
        ]);

        if (! $request->boolean('requires_approval')) {
            $data['approval_levels'] = null;
        }

        $data['status'] = $request->boolean('status');
        $data['allow_partial_recovery'] = $request->boolean('allow_partial_recovery');
        $data['is_salary_advance'] = $request->boolean('is_salary_advance');
        $data['requires_approval'] = $request->boolean('requires_approval');

        $loan->update($data);

        return response()->json(['status'=>true,'message'=>'Loan updated successfully']);
    }

    public function destroy(Loan $loan)
    {
        $loan->delete();
        return response()->json(['status'=>true,'message'=>'Loan deleted successfully']);
    }

    public function status(Loan $loan)
    {
        $loan->update(['status'=>!$loan->status]);
        return response()->json(['status'=>true,'message'=>'Status updated']);
    }
}
