<?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\Addition;
use App\Modules\HR\Payroll\Models\Deduction;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Yajra\DataTables\Facades\DataTables;

class DeductionController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            return DataTables::of(Deduction::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($r) =>
                    view('payroll::deductions/partials/actions', compact('r'))->render()
                )
                ->rawColumns(['status','action'])
                ->make(true);
        }

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

    public function create()
    {
        return view('payroll::deductions/create', [
            'branches' => Branch::where('status', true)->orderBy('name')->get(),
            'additionCodes' => Addition::where('status', true)->orderBy('code')->pluck('code'),
            'deductionCodes' => Deduction::where('status', true)->orderBy('code')->pluck('code'),
        ]);
    }

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

            'calculation_type' => 'required|in:FIXED,FORMULA,BOTH',
            'fixed_amount' => 'nullable|numeric|min:0',
            'formula_expression' => 'nullable|string',

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

        if ($data['calculation_type'] === 'FIXED') {
            $data['formula_expression'] = null;
        }
        if ($data['calculation_type'] === 'FORMULA') {
            $data['fixed_amount'] = null;
        }

        $data['status'] = $request->status;
        $data['is_epf_applicable'] = $request->is_epf_applicable;
        $data['is_etf_applicable'] = $request->is_etf_applicable;
        $data['is_gross_applicable'] = $request->is_gross_applicable;
        $data['is_net_applicable'] = $request->is_net_applicable;

        Deduction::create($data);

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

    public function edit(Deduction $deduction)
    {
        return view('payroll::deductions/edit', [
            'deduction'   => $deduction,
            'branches' => Branch::where('status', true)->orderBy('name')->get(),
            'additionCodes' => Addition::where('status', true)->orderBy('code')->pluck('code'),
            'deductionCodes' => Deduction::where('status', true)->orderBy('code')->pluck('code'),
        ]);
    }

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

            'calculation_type' => 'required|in:FIXED,FORMULA,BOTH',
            'fixed_amount' => 'nullable|numeric|min:0',
            'formula_expression' => 'nullable|string',

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

        if ($data['calculation_type'] === 'FIXED') {
            $data['formula_expression'] = null;
        }
        if ($data['calculation_type'] === 'FORMULA') {
            $data['fixed_amount'] = null;
        }

        $data['status'] = $request->status;
        $data['is_epf_applicable'] = $request->is_epf_applicable;
        $data['is_etf_applicable'] = $request->is_etf_applicable;
        $data['is_gross_applicable'] = $request->is_gross_applicable;
        $data['is_net_applicable'] = $request->is_net_applicable;
        $deduction->update($data);

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

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

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