<?php

namespace App\Http\Controllers\Admin;

use App\Enums\UserType;
use App\Http\Controllers\Controller;
use App\Models\EmployeeTaxAssignment;
use App\Models\Tax;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;

class EmployeeTaxAssignmentController extends Controller
{
    public function index(Request $request)
    {
        $taxes = Tax::where('status', 'active')->get();

        $employees = User::where('type', UserType::EMPLOYEE)
            ->where('status', 'active')
            ->with(['employeeProfile.departmentRel', 'employeeProfile.designationRel'])
            ->with(['taxAssignments' => function ($query) {
                $query->where('status', 'active')->with('tax');
            }])
            ->get()
            ->map(function ($employee) {
                $activeAssignment = $employee->taxAssignments->first();

                return [
                    'id' => $employee->id,
                    'name' => $employee->name,
                    'email' => $employee->email,
                    'department' => $employee->employeeProfile?->departmentRel?->name ?? '-',
                    'designation' => $employee->employeeProfile?->designationRel?->name ?? '-',
                    'assignment' => $activeAssignment ? [
                        'id' => $activeAssignment->id,
                        'tax_id' => $activeAssignment->tax_id,
                        'tax_name' => $activeAssignment->tax->name,
                        'tax_type' => $activeAssignment->tax->type,
                        'fixed_amount' => $activeAssignment->fixed_amount,
                        'fixed_amount_type' => $activeAssignment->tax->fixed_amount_type,
                        'effective_from' => $activeAssignment->effective_from->format('Y-m-d'),
                    ] : null,
                ];
            });

        return Inertia::render('Admin/Tax/Assignments', [
            'employees' => $employees,
            'taxes' => $taxes,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'employee_id' => 'required|exists:users,id',
            'tax_id' => 'required|exists:taxes,id',
            'fixed_amount' => [
                'nullable',
                'numeric',
                'min:0',
                Rule::requiredIf(fn () => Tax::find($request->tax_id)?->type === 'fixed'),
            ],
            'effective_from' => 'required|date',
        ]);

        // Deactivate existing active assignments for this employee
        EmployeeTaxAssignment::where('employee_id', $request->employee_id)
            ->where('status', 'active')
            ->update(['status' => 'inactive']);

        EmployeeTaxAssignment::create([
            'employee_id' => $request->employee_id,
            'tax_id' => $request->tax_id,
            'fixed_amount' => cloneAmount($request->fixed_amount),
            'effective_from' => $request->effective_from,
            'status' => 'active',
        ]);

        return back()->with('success', 'Tax assigned successfully.');
    }

    public function bulkAssign(Request $request)
    {
        $request->validate([
            'employee_ids' => 'required|array',
            'employee_ids.*' => 'exists:users,id',
            'tax_id' => 'required|exists:taxes,id',
            'fixed_amount' => [
                'nullable',
                'numeric',
                'min:0',
                Rule::requiredIf(fn () => Tax::find($request->tax_id)?->type === 'fixed'),
            ],
            'effective_from' => 'required|date',
        ]);

        // Deactivate existing assignments for all selected employees
        EmployeeTaxAssignment::whereIn('employee_id', $request->employee_ids)
            ->where('status', 'active')
            ->update(['status' => 'inactive']);

        $records = [];
        $now = now();

        $amount = $request->fixed_amount ? (float) $request->fixed_amount : null;

        foreach ($request->employee_ids as $employeeId) {
            $records[] = [
                'employee_id' => $employeeId,
                'tax_id' => $request->tax_id,
                'fixed_amount' => $amount,
                'effective_from' => $request->effective_from,
                'status' => 'active',
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        EmployeeTaxAssignment::insert($records);

        return back()->with('success', count($records).' employees assigned to tax policy successfully.');
    }

    public function destroy(EmployeeTaxAssignment $employeeTax)
    {
        $employeeTax->update(['status' => 'inactive']);

        return back()->with('success', 'Tax assignment removed.');
    }
}

function cloneAmount($amount)
{
    return $amount !== null ? (float) $amount : null;
}
