<?php

namespace App\Http\Controllers;

use App\EmployeeAttendance;
use App\EmployeePayroll;
use App\Employees;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PayrollController extends Controller
{
    protected string $module = 'Employee Payrolls';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
    }
    public function index(Request $request)
    {
        $month = $request->get('month', Carbon::now()->month);
        $year = $request->get('year', Carbon::now()->year);

        $payrolls = EmployeePayroll::with('employee')
            ->where('month', $month)
            ->where('year', $year)
            ->get();

        return view('employee_payrolls.index', compact('payrolls', 'month', 'year'));
    }

    /**
     * Generate payroll for all employees
     */
 public function generate(Request $request)
{
    $request->validate([
        'month_year' => 'required|date_format:Y-m',
    ]);

    $monthYear = $request->month_year;
    $year = Carbon::createFromFormat('Y-m', $monthYear)->year;
    $month = Carbon::createFromFormat('Y-m', $monthYear)->month;

    $daysInMonth = Carbon::create($year, $month, 1)->daysInMonth;

    $employees = Employees::all();

    DB::transaction(function () use ($employees, $month, $year, $daysInMonth) {
        foreach ($employees as $employee) {


            $exists = EmployeePayroll::where('employee_id', $employee->id)
                ->where('month', $month)
                ->where('year', $year)
                ->exists();
            if ($exists) continue;


            $attendances = EmployeeAttendance::where('employee_id', $employee->id)
                ->whereYear('date', $year)
                ->whereMonth('date', $month)
                ->get();


            $presentDays = $attendances->where('status', 'present')->count();
            $lateDays = $attendances->where('status', 'late')->count();
            $absentDays = $attendances->where('status', 'absent')->count();
            $halfDays = $attendances->where('status', 'half-day')->count();
            $onLeaveDays = $attendances->where('status', 'on_leave')->count();


            $dailySalary = $employee->basic_salary / $daysInMonth;


            $deductions = 0;


            $deductions += $lateDays * ($dailySalary * 0.5);
            $deductions += $halfDays * ($dailySalary * 0.5);


            $deductions += $absentDays * $dailySalary;



            $netSalary = $employee->basic_salary - $deductions;


            EmployeePayroll::create([
                'employee_id' => $employee->id,
                'year' => $year,
                'month' => $month,
                'gross_salary' => $employee->basic_salary,
                'deductions' => $deductions,
                'net_salary' => $netSalary,
                'status' => 'unpaid',
            ]);
        }
    });

    return redirect()->back()->with('success', 'Payroll generated successfully for ' . Carbon::create($year, $month, 1)->format('F, Y'));
}



    public function pay(Request $request, $id)
    {
        $payroll = EmployeePayroll::findOrFail($id);

        if ($payroll->status === 'paid') {
            return redirect()->back()->with('error', 'Payroll already paid.');
        }

        $payroll->update([
            'status' => 'paid',
            'paid_at' => now(),
        ]);

        return redirect()->back()->with('success', 'Payroll paid successfully.');
    }


    public function payAll(Request $request)
    {
        $request->validate([
            'month_year' => 'required|date_format:Y-m',
        ]);

        $monthYear = $request->month_year;
        $year = Carbon::createFromFormat('Y-m', $monthYear)->year;
        $month = Carbon::createFromFormat('Y-m', $monthYear)->month;

        $payrolls = EmployeePayroll::where('year', $year)
            ->where('month', $month)
            ->where('status', 'unpaid')
            ->get();

        foreach ($payrolls as $payroll) {
            $payroll->update([
                'status' => 'paid',
                'paid_at' => now(),
            ]);
        }

        return redirect()->back()->with('success', 'All payrolls for ' . Carbon::create($year, $month, 1)->format('F, Y') . ' have been paid.');
    }
}
