<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\EmployeeDetails;
use App\Models\EmployeeSalaryStructure;
use Illuminate\Support\Facades\DB;

class SuperAdminSalaryStructureController extends Controller
{
    /**
     * Display the master salary structure page.
     */
    public function index()
    {
        $employees = EmployeeDetails::select('id', 'employee_id', 'name', 'designation', 'department')
            ->where('status', 'active') // Assuming 'active' status exists, logical guess
            ->get();

        $structures = EmployeeSalaryStructure::with('employee')->get();
        // Map structure by employee_id for easy checking in view if needed, 
        // or just pass structures to show list.
        
        return view('superadmin.employee.salary_structure', compact('employees', 'structures'));
    }

    /**
     * Store or Update Salary Structure.
     */
    public function store(Request $request)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'basic_da' => 'nullable|numeric|min:0',
            'hra' => 'nullable|numeric|min:0',
            'conveyance' => 'nullable|numeric|min:0',
            'washing_allowance' => 'nullable|numeric|min:0',
            'fixed_salary' => 'nullable|numeric|min:0',
            'pf_percentage' => 'nullable|numeric|between:0,100',
            'esi_percentage' => 'nullable|numeric|between:0,100',
        ]);

        // Calculate fixed salary if not provided or just trust user input?
        // User requirement: "Default fields Basic & DA ,HRA ,Conveyance, Washing Allowance, Fixed Salary..."
        // Usually Fixed Salary = Sum(Components). Let's trust input but maybe validate sum? 
        // For now, simple updateOrCreate.

        EmployeeSalaryStructure::updateOrCreate(
            ['employee_id' => $request->employee_id],
            [
                'basic_da' => $request->basic_da ?? 0,
                'hra' => $request->hra ?? 0,
                'conveyance' => $request->conveyance ?? 0,
                'washing_allowance' => $request->washing_allowance ?? 0,
                'fixed_salary' => $request->fixed_salary ?? 0,
                'pf_percentage' => $request->pf_percentage,
                'esi_percentage' => $request->esi_percentage,
            ]
        );

        return response()->json(['success' => true, 'message' => 'Salary Structure updated successfully.']);
    }

    /**
     * Fetch structure for a specific employee (AJAX).
     */
    public function getStructure($employeeId)
    {
        $structure = EmployeeSalaryStructure::where('employee_id', $employeeId)->first();
        
        if (!$structure) {
            return response()->json(['success' => false, 'message' => 'No structure found']);
        }

        return response()->json(['success' => true, 'data' => $structure]);
    }
}
