<?php

namespace App\Http\Controllers;
use App\Models\ProjectCode;
use App\Models\TimeSheet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TimeSheetController extends Controller
{
    public function index()
    {
        // Get all timesheets for the authenticated user
        $timesheets = Timesheet::where('user_id', auth()->id())
                        ->orderBy('date', 'desc')
                        ->get();

        // Calculate totals safely
        $totalRegularHours = 0;
        $totalOvertimeWeekdays = 0;
        $totalOvertimeWeekend = 0;
        $totalAllHours = 0;

        foreach ($timesheets as $timesheet) {
            // Calculate regular hours for each timesheet
            $start = \Carbon\Carbon::parse($timesheet->start_time);
            $end = \Carbon\Carbon::parse($timesheet->end_time);
            $regularHours = round($end->diffInMinutes($start) / 60, 2);
            
            $totalRegularHours -= $regularHours;
            $totalOvertimeWeekdays += $timesheet->overtime_weekdays ?? 0;
            $totalOvertimeWeekend += $timesheet->overtime_weekend ?? 0;
        }

        $totalAllHours = $totalRegularHours + $totalOvertimeWeekdays + $totalOvertimeWeekend;

        return view('time-sheets.index', compact(
            'timesheets',
            'totalRegularHours',
            'totalOvertimeWeekdays',
            'totalOvertimeWeekend',
            'totalAllHours'
        ));
    }

    public function create()
    {
        $projectCodes = ProjectCode::all();
        
        return view('time-sheets.create', compact('projectCodes'));
        //return view('time-sheets.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
            'start_time' => 'required',
            'end_time' => 'required|after:start_time',
            'project_code' => 'required|string|max:50',
            'overtime_weekdays' => 'nullable|numeric|min:0',
            'overtime_weekend' => 'nullable|numeric|min:0',
            'description' => 'nullable|string|max:500',
        ]);

        TimeSheet::create([
            'date' => $request->date,
            'start_time' => $request->start_time,
            'end_time' => $request->end_time,
            'project_code' => $request->project_code,
            'overtime_weekdays' => $request->overtime_weekdays ?? 0,
            'overtime_weekend' => $request->overtime_weekend ?? 0,
            'description' => $request->description,
            'user_id' => Auth::id(),

        ]);

        return redirect()->route('time-sheets.index')
            ->with('success', 'Time sheet entry created successfully!');
    }

    public function show(TimeSheet $timeSheet)
    {
        // Check if user owns this timesheet
        if ($timeSheet->user_id !== Auth::id()) {
            abort(403);
        }

        return view('time-sheets.show', compact('timeSheet'));
    }

    public function edit(TimeSheet $timeSheet)
    {
        // Check if user owns this timesheet
        if ($timeSheet->user_id !== Auth::id()) {
            abort(403);
        }

        return view('time-sheets.edit', compact('timeSheet'));
    }

    public function update(Request $request, TimeSheet $timeSheet)
    {
        // Check if user owns this timesheet
        if ($timeSheet->user_id !== Auth::id()) {
            abort(403);
        }

        $request->validate([
            'date' => 'required|date',
            'start_time' => 'required',
            'end_time' => 'required|after:start_time',
            'project_code' => 'required|string|max:50',
            'overtime_weekdays' => 'nullable|numeric|min:0',
            'overtime_weekend' => 'nullable|numeric|min:0',
            'description' => 'nullable|string|max:500',
        ]);

        $timeSheet->update([
            'date' => $request->date,
            'start_time' => $request->start_time,
            'end_time' => $request->end_time,
            'project_code' => $request->project_code,
            'overtime_weekdays' => $request->overtime_weekdays ?? 0,
            'overtime_weekend' => $request->overtime_weekend ?? 0,
            'description' => $request->description,
        ]);

        return redirect()->route('time-sheets.index')
            ->with('success', 'Time sheet entry updated successfully!');
    }

    public function destroy(TimeSheet $timeSheet)
    {
        // Check if user owns this timesheet
        if ($timeSheet->user_id !== Auth::id()) {
            abort(403);
        }

        $timeSheet->delete();

        return redirect()->route('time-sheets.index')
            ->with('success', 'Time sheet entry deleted successfully!');
    }
}