<?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;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

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',
            'incentive_per_hour' => 'nullable|numeric|min:0',
            'fixed_salary' => 'nullable|numeric|min:0',
            'pf_percentage' => 'nullable|numeric|between:0,100',
            'esi_percentage' => 'nullable|numeric|between:0,100',
            'pt_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,
                'incentive_per_hour' => $request->incentive_per_hour ?? 0,
                'fixed_salary' => $request->fixed_salary ?? 0,
                'pf_percentage' => $request->pf_percentage,
                'esi_percentage' => $request->esi_percentage,
                'pt_percentage' => $request->pt_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]);
    }

    /**
     * Import salary structures from Excel file.
     */
    public function import(Request $request)
    {
        if (!$request->hasFile('import_file')) {
            return back()->with('error', 'No file uploaded.');
        }

        $file = $request->file('import_file');

        try {
            $spreadsheet = IOFactory::load($file->getPathname());
            $sheet = $spreadsheet->getActiveSheet();
            $rows = $sheet->toArray();

            $imported = 0;
            $skipped = 0;
            $errors = [];

            foreach ($rows as $index => $row) {
                // Skip header row
                if ($index === 0) continue;

                // Skip empty rows
                if (empty($row[0])) continue;

                $employeeId = trim($row[0]);

                // Find employee by employee_id field
                $employee = EmployeeDetails::where('employee_id', $employeeId)->first();

                if (!$employee) {
                    $skipped++;
                    $errors[] = "Row " . ($index + 1) . ": Employee ID '$employeeId' not found";
                    continue;
                }

                // Parse values with defaults
                $basicDa = is_numeric($row[1] ?? '') ? floatval($row[1]) : 0;
                $hra = is_numeric($row[2] ?? '') ? floatval($row[2]) : 0;
                $conveyance = is_numeric($row[3] ?? '') ? floatval($row[3]) : 0;
                $washingAllowance = is_numeric($row[4] ?? '') ? floatval($row[4]) : 0;
                $incentivePerHour = is_numeric($row[5] ?? '') ? floatval($row[5]) : 0;
                $fixedSalary = is_numeric($row[6] ?? '') ? floatval($row[6]) : 0;
                $pfPercentage = is_numeric($row[7] ?? '') ? floatval($row[7]) : null;
                $esiPercentage = is_numeric($row[8] ?? '') ? floatval($row[8]) : null;
                $ptPercentage = is_numeric($row[9] ?? '') ? floatval($row[9]) : null;

                // Auto-calculate fixed salary if not provided
                if ($fixedSalary == 0) {
                    $fixedSalary = $basicDa + $hra + $conveyance + $washingAllowance;
                }

                EmployeeSalaryStructure::updateOrCreate(
                    ['employee_id' => $employee->id],
                    [
                        'basic_da' => $basicDa,
                        'hra' => $hra,
                        'conveyance' => $conveyance,
                        'washing_allowance' => $washingAllowance,
                        'incentive_per_hour' => $incentivePerHour,
                        'fixed_salary' => $fixedSalary,
                        'pf_percentage' => $pfPercentage,
                        'esi_percentage' => $esiPercentage,
                        'pt_percentage' => $ptPercentage,
                    ]
                );

                $imported++;
            }

            $message = "Successfully imported $imported salary structure(s).";
            if ($skipped > 0) {
                $message .= " Skipped $skipped row(s).";
            }

            if (!empty($errors)) {
                Log::warning('Salary structure import errors:', $errors);
            }

            return back()->with('success', $message);

        } catch (\Exception $e) {
            Log::error('Salary structure import error: ' . $e->getMessage());
            return back()->with('error', 'Failed to import file: ' . $e->getMessage());
        }
    }

    /**
     * Download sample Excel file for salary structure import.
     */
    public function downloadSample()
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Salary Structure');

        // Set headers
        $headers = [
            'Employee ID',
            'Basic & DA',
            'HRA',
            'Conveyance',
            'Washing Allowance',
            'Incentive per Hour',
            'Fixed Salary',
            'PF %',
            'ESI %',
            'PT %'
        ];

        $sheet->fromArray($headers, null, 'A1');

        // Style header row
        $headerStyle = [
            'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => '4472C4']
            ],
            'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER]
        ];
        $sheet->getStyle('A1:J1')->applyFromArray($headerStyle);

        // Add sample data rows
        $sampleData = [
            ['1001', 15000, 5000, 2000, 500, 50, 22500, 12, 0.75, 2.5],
            ['1002', 18000, 6000, 2500, 600, 60, 27100, 12, 0.75, 2.5],
            ['1003', 20000, 7000, 3000, 700, 75, 30700, 12, 0.75, 2.5],
        ];

        $sheet->fromArray($sampleData, null, 'A2');

        // Auto-size columns
        foreach (range('A', 'J') as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }

        // Add instructions sheet
        $instructionSheet = $spreadsheet->createSheet();
        $instructionSheet->setTitle('Instructions');

        $instructions = [
            ['Salary Structure Import Instructions'],
            [''],
            ['Column', 'Description', 'Required', 'Example'],
            ['Employee ID', 'Must match existing Employee ID in system', 'Yes', '1001'],
            ['Basic & DA', 'Basic salary + DA amount', 'No', '15000'],
            ['HRA', 'House Rent Allowance', 'No', '5000'],
            ['Conveyance', 'Conveyance Allowance', 'No', '2000'],
            ['Washing Allowance', 'Washing Allowance', 'No', '500'],
            ['Incentive per Hour', 'Hourly incentive rate', 'No', '50'],
            ['Fixed Salary', 'Total fixed salary (auto-calculated if empty)', 'No', '22500'],
            ['PF %', 'Provident Fund percentage (0-100)', 'No', '12'],
            ['ESI %', 'ESI percentage (0-100)', 'No', '0.75'],
            ['PT %', 'Professional Tax percentage (0-100)', 'No', '2.5'],
            [''],
            ['Notes:'],
            ['1. First row is header - do not modify'],
            ['2. Employee ID must exist in the system'],
            ['3. If Fixed Salary is empty/0, it will be auto-calculated as sum of Basic+HRA+Conv+Wash'],
            ['4. Existing salary structures will be updated if Employee ID already exists'],
        ];

        $instructionSheet->fromArray($instructions, null, 'A1');
        $instructionSheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
        $instructionSheet->getStyle('A3:D3')->getFont()->setBold(true);

        foreach (range('A', 'D') as $col) {
            $instructionSheet->getColumnDimension($col)->setAutoSize(true);
        }

        // Set active sheet back to data sheet
        $spreadsheet->setActiveSheetIndex(0);

        // Create response
        $fileName = 'salary_structure_sample.xlsx';
        $writer = new Xlsx($spreadsheet);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $writer->save('php://output');
        exit;
    }
}
