<?php

namespace App\Http\Controllers\Manager;
use App\Http\Controllers\Controller;

use App\Models\Department;
use App\Models\Employee;
use App\Models\Attendance;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\Holiday;
use App\Models\Setting;
use App\Models\Payroll;



class PayrollController extends Controller
{


    public function index()
    {
        $departments = Department::all();
        $employees = Employee::all();
        $settings = Setting::first();
        return view('manager/payroll/index', compact('departments', 'employees' ,'settings'));
    }


    public function addpage()
    {
        $departments = Department::all();
        $employees = Employee::all();
        $settings = Setting::first();

        return view('manager/payroll/add', compact('departments', 'employees' , 'settings'));
    }

     
    public function generateReportUpdate(Request $request)
    {
        try {
            // Retrieve selected values from the request
            $employeeId = $request->input('employee');
            $year = $request->input('year');
            $month = $request->input('month');
    
            // Query payroll records based on selected employee, year, and month
            $payroll = Payroll::where('employee_id', $employeeId)
                              ->where('year', $year)
                              ->where('month', $month)
                              ->first();
    
            if (!$payroll) {
                return redirect()->back()->withErrors('Payroll record not found for the selected employee, year, and month.');
            }
    
            // Fetch employee details based on employee ID
            $employee = Employee::findOrFail($employeeId);
    
            // Fetch other necessary data for payroll calculation if needed
    
            // Return the view with the payroll data and employee details
            $departments = Department::all();
            $employees = Employee::all();
            $settings = Setting::first();
            $employeesignle = Employee::findOrFail($employeeId);
    
            return view('manager.payroll.index', compact('payroll', 'departments', 'employees', 'employee', 'settings', 'employeesignle'));
        } catch (\Exception $e) {
            // Handle any exceptions that occur
            return redirect()->back()->withErrors('An error occurred while generating the report: ' . $e->getMessage());
        }
    }
    
    

 

    public function generateReport(Request $request)
    {
        try {
            // Retrieve selected values from the request
            $employeeId = $request->input('employee');
            $year = $request->input('year');
            $month = $request->input('month');
    
            // Check if a payroll record already exists for the given employee, year, and month
            $existingPayroll = Payroll::where('employee_id', $employeeId)
                                      ->where('year', $year)
                                      ->where('month', $month)
                                      ->first();
    
            if ($existingPayroll) {
                return redirect()->back()->withErrors('Payroll record already exists for the selected employee, year, and month.');
            }
    
            // Query attendance records based on selected employee, year, and month
            $attendances = Attendance::where('employee_id', $employeeId)
                                     ->whereYear('date', $year)
                                     ->whereMonth('date', $month)
                                     ->get();
    
            // Initialize count variables
            $presentCount = 0;
            $absentCount = 0;
            $lateCount = 0;
            $remoteCount = 0;
    
            // Calculate counts for different attendance statuses
            foreach ($attendances as $attendance) {
                if ($attendance->status === 'present') {
                    $presentCount++;
                } elseif ($attendance->status === 'absent') {
                    $absentCount++;
                } elseif ($attendance->status === 'late') {
                    $lateCount++;
                } elseif ($attendance->status === 'remote') {
                    $remoteCount++;
                }
            }
    
            // Calculate total days in the selected month
            $totalDaysInMonth = Carbon::create($year, $month)->daysInMonth();
    
            // Query holidays for the selected month and year
            $holidays = Holiday::whereYear('holiday_date', $year)
                               ->whereMonth('holiday_date', $month)
                               ->count();
    
            // Calculate total office days by subtracting holidays from total days in the month
            $totalOfficeDays = $totalDaysInMonth - $holidays;
    
            // Fetch employee details based on employee ID
            $employeesignle = Employee::findOrFail($employeeId);
    
            // Format the date in the desired format (e.g., YYYY-MM-DD)
            $attendances->transform(function ($attendance) {
                $attendance->date = Carbon::parse($attendance->date)->format('Y-m-d');
                return $attendance;
            });
    
            // Return the view with the attendance data, counts, total office days, and employee details
            $departments = Department::all();
            $employees = Employee::all();
            $settings = Setting::first();
    
            return view('manager.payroll.add', compact('attendances', 'departments', 'employees', 'presentCount', 'absentCount', 'lateCount', 'remoteCount', 'totalOfficeDays', 'employeesignle', 'settings'));
        } catch (\Exception $e) {
            // Handle any exceptions that occur
            return redirect()->back()->withErrors('An error occurred while generating the report: ' . $e->getMessage());
        }
    }
    
    
    
    public function getEmployeesByDepartment($departmentId)
    {
        // Fetch employees of the selected department
         $employees = Employee::where('department', $departmentId)->get();
      
        // Return the employees as JSON response
        return response()->json($employees);
    }

    public function store(Request $request)
    {
      
        // Validate the incoming request data
        $validatedData = $request->validate([
            'employee_id' => 'required|integer', // Assuming employee_id is required and integer
            'year' => 'required|integer', // Assuming year is required and integer
            'month' => 'required', // Assuming month is required and integer
            'total_office_date' => 'required|integer',
            'total_attend' => 'nullable|integer',
            'total_late' => 'nullable|string',
            'total_pay' => 'nullable|numeric',
        ]);
 
        // Create and save the payroll record
        $payroll = new Payroll();
        $payroll->employee_id = $validatedData['employee_id'];
        $payroll->year = $validatedData['year'];
        $payroll->month = $validatedData['month'];
        $payroll->total_office_date = $validatedData['total_office_date'];
        $payroll->total_attend = $validatedData['total_attend'];
        $payroll->total_late = $validatedData['total_late'];
        $payroll->this_month_pay = $validatedData['total_pay'];
 
        // Save the payroll record
        $payroll->save();
       
        
       return redirect()->route('payroll.add')->with('success', 'Payroll added successfully');
        
    }


    public function update_payroll(Request $request)
    {
        // Validate the incoming request data
        $validatedData = $request->validate([
            'employee_id' => 'required|integer',
            'year' => 'required|integer',
            'month' => 'required', 
            'pay_again' => 'required',
        ]);
        // Attempt to find an existing payroll record for the employee, year, and month
        $payroll = Payroll::where('employee_id', $validatedData['employee_id'])
                    ->where('year', $validatedData['year'])
                    ->where('month', $validatedData['month'])
                    ->first();
    
        // Update the payroll record with the validated data
        $payroll->again_pay = $validatedData['pay_again'];
        // $payroll->again_pay2 = Carbon::now();
        // Save the payroll record
        $payroll->save();
    
        // Redirect back or return a response as needed
        return redirect()->back()->with('success', 'Payroll updated successfully');
    }
    


    // Payroll Delete
    public function delete($id)
    {
        // Find the payroll entry
        $payroll = Payroll::find($id);
    
        // Check if the payroll entry exists
        if (!$payroll) {
            return redirect()->back()->with('error', 'Payroll not found.');
        }
    
        // Delete the payroll entry
        $payroll->delete();
    
        // Redirect back with a success message=
        return redirect()->route('all_payroll')->with('success', 'Payroll deleted successfully.');
    }

}
