<?php

namespace App\Http\Controllers;

use App\Models\Salary;
use App\Models\Employee;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;

class SalaryController extends Controller
{
    public function index()
    {
        return view('salaries.index');
    }

    public function report()
    {
        return view('salaries.report');
    }

    public function reportData(Request $request)
    {
        $query = Salary::with('employee');

        if ($request->start_date) {
            $query->whereDate('payment_date', '>=', $request->start_date);
        }
        if ($request->end_date) {
            $query->whereDate('payment_date', '<=', $request->end_date);
        }
        if ($request->month) {
            $query->where('month', $request->month);
        }
        if ($request->year) {
            $query->where('year', $request->year);
        }

        return DataTables::of($query)
            ->addColumn('employee', function ($salary) {
                return $salary->employee->name;
            })
            ->addColumn('employee_email', function ($salary) {
                return $salary->employee->email;
            })
            ->addColumn('employee_designation', function ($salary) {
                return $salary->designation ?? ($salary->employee->designation ?? 'Staff');
            })
            ->addColumn('employee_department', function ($salary) {
                return $salary->department ?? ($salary->employee->department ?? 'GSS - Operations');
            })
            ->addColumn('employee_code', function ($salary) {
                return $salary->employee_code ?? "ICA00{$salary->employee_id}";
            })
            ->editColumn('month', function ($salary) {
                return date("F", mktime(0, 0, 0, $salary->month, 10)) . ' ' . $salary->year;
            })
            ->make(true);
    }

    public function create()
    {
        return view('salaries.create');
    }

    public function getData(Request $request)
    {
        $query = Salary::with('employee');

        // Advanced Filters
        $query->when($request->month, function ($q) use ($request) {
            return $q->where('month', $request->month);
        })
        ->when($request->year, function ($q) use ($request) {
            return $q->where('year', $request->year);
        })
        ->when($request->employee_id, function ($q) use ($request) {
            return $q->where('employee_id', $request->employee_id);
        });

        // Clone query for totals to avoid pagination interference
        $totalsQuery = clone $query;
        $aggregates = [
            'total_net_pay' => $totalsQuery->sum('net_pay'),
            'total_gross_earnings' => $totalsQuery->sum('gross_earnings'),
            'total_gross_deductions' => $totalsQuery->sum('gross_deductions'),
            'total_count' => $totalsQuery->count()
        ];

        return DataTables::of($query)
            ->addColumn('employee', function ($salary) {
                return $salary->employee->name;
            })
            ->editColumn('month', function ($salary) {
                return date("F", mktime(0, 0, 0, $salary->month, 10)) . ' ' . $salary->year;
            })
            ->addColumn('month_raw', function ($salary) {
                return $salary->month;
            })

            ->addColumn('action', function ($salary) {
                $btn = '<div class="d-flex gap-1 justify-content-center">';
                
                if (auth()->user()->canAccess('payroll.view')) {
                    $btn .= '<a href="' . route('payslips.show', $salary->id) . '" target="_blank" class="btn-crm-view" title="View Payslip"><i class="fas fa-eye"></i></a>';
                }
                
                if (auth()->user()->canAccess('payroll.process')) {
                     $btn .= '<button class="btn-crm-edit edit-salary" data-id="' . $salary->id . '" title="Edit Salary"><i class="fas fa-edit"></i></button>';
                }

                if (auth()->user()->canAccess('payroll.process')) {
                    $btn .= '<button class="btn-crm-delete delete-salary" data-id="' . $salary->id . '" title="Delete Salary"><i class="fas fa-trash"></i></button>';
                }

                $btn .= '</div>';
                return $btn;
            })
            ->with('aggregates', $aggregates)
            ->make(true);
    }

    public function store(Request $request)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'month' => 'required|integer|min:1|max:12',
            'year' => 'required|integer',
            'working_days' => 'required|integer',
            'lop_days' => 'required|integer',
            
            // Earnings
            'base_salary' => 'required|numeric',
            'hra' => 'nullable|numeric',
            'special_allowance' => 'nullable|numeric',
            'conveyance' => 'nullable|numeric',
            'medical' => 'nullable|numeric',
            'lta' => 'nullable|numeric',
            'gross_earnings' => 'required|numeric',
            
            // Deductions
            'esic_employee' => 'nullable|numeric',
            'esic_employer' => 'nullable|numeric',
            'gratuity' => 'nullable|numeric',
            'prof_tax' => 'nullable|numeric',
            'income_tax' => 'nullable|numeric',
            'gross_deductions' => 'required|numeric',
            
            // Final
            'expense_reimbursements' => 'nullable|numeric',
            'net_pay' => 'required|numeric',
        ]);

        $salary = Salary::create([
            'employee_id' => $request->employee_id,
            'month' => $request->month,
            'year' => $request->year,
            'working_days' => $request->working_days,
            'lop_days' => $request->lop_days,
            
            'base_salary' => $request->base_salary,
            'hra' => $request->hra ?? 0,
            'special_allowance' => $request->special_allowance ?? 0,
            'conveyance' => $request->conveyance ?? 0,
            'medical' => $request->medical ?? 0,
            'lta' => $request->lta ?? 0,
            'gross_earnings' => $request->gross_earnings,
            
            'esic_employee' => $request->esic_employee ?? 0,
            'esic_employer' => $request->esic_employer ?? 0,
            'gratuity' => $request->gratuity ?? 0,
            'prof_tax' => $request->prof_tax ?? 0,
            'income_tax' => $request->income_tax ?? 0,
            'gross_deductions' => $request->gross_deductions,
            
            'expense_reimbursements' => $request->expense_reimbursements ?? 0,
            'net_pay' => $request->net_pay,
            
            // Mapping for legacy fields
            'bonus' => $request->expense_reimbursements ?? 0,
            'deductions' => $request->gross_deductions,
            'net_salary' => $request->net_pay,
            'status' => 'paid',
            'payment_date' => now(),
        ]);

        if ($request->ajax()) {
            return response()->json(['success' => 'Salary record generated successfully.']);
        }

        return redirect()->route('salaries.index')->with('success', 'Salary record generated successfully.');
    }

    public function destroy(Salary $salary)
    {
        $salary->delete();
        return response()->json(['success' => 'Salary record deleted successfully.']);
    }

    public function exportExcel(Request $request)
    {
        $query = Salary::with('employee', 'salaryDeductions.deductionType');

        // Apply filters
        if ($request->month) {
            $query->where('month', $request->month);
        }
        if ($request->year) {
            $query->where('year', $request->year);
        }
        if ($request->employee_id) {
            $query->where('employee_id', $request->employee_id);
        }

        $salaries = $query->get();

        // Create CSV content
        $filename = 'payslips_' . date('Y-m-d_His') . '.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function() use ($salaries) {
            $file = fopen('php://output', 'w');
            
            // Header exactly like the User Template (sharedStrings.xml)
            fputcsv($file, [
                'Email',
                'Emp Code',
                'Employee Name',
                'Designation',
                'Department',
                'Working Days',
                'LOP',
                'Basic',
                'HRA',
                'Special allowance',
                'Conveyance',
                'Medical',
                'LTA',
                'Gross Earnings',
                'ESIC',
                'Employer ESIC',
                'Gratuity',
                'Professional Tax',
                'Income Tax',
                'Gross Deduction',
                'Net Salary',
                'Expense Reimbursements',
                'Net Pay'
            ]);

            foreach ($salaries as $salary) {
                fputcsv($file, [
                    $salary->employee->email,
                    $salary->employee->id, // Or custom emp code if available
                    $salary->employee->name,
                    $salary->employee->designation,
                    'GSS', // Default or fetch from dept if exists
                    $salary->working_days,
                    $salary->lop_days,
                    number_format($salary->base_salary, 2, '.', ''),
                    number_format($salary->hra, 2, '.', ''),
                    number_format($salary->special_allowance, 2, '.', ''),
                    number_format($salary->conveyance, 2, '.', ''),
                    number_format($salary->medical, 2, '.', ''),
                    number_format($salary->lta, 2, '.', ''),
                    number_format($salary->gross_earnings, 2, '.', ''),
                    number_format($salary->esic_employee, 2, '.', ''),
                    number_format($salary->esic_employer, 2, '.', ''),
                    number_format($salary->gratuity, 2, '.', ''),
                    number_format($salary->prof_tax, 2, '.', ''),
                    number_format($salary->income_tax, 2, '.', ''),
                    number_format($salary->gross_deductions, 2, '.', ''),
                    number_format($salary->net_pay, 2, '.', ''), // Net Salary column in Excel often means pre-reimb
                    number_format($salary->expense_reimbursements, 2, '.', ''),
                    number_format($salary->net_pay, 2, '.', '')
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    public function exportCSV(Request $request)
    {
        // Same as exportExcel for now, can be customized differently
        return $this->exportExcel($request);
    }
}
