// app/Http/Controllers/EmployeeDashboardController.php - Update this
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Visit;
use App\Models\Attendance;
use App\Models\LeaveRequest;
use Carbon\Carbon;

class EmployeeDashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $today = Carbon::today();
        
        $todayVisits = Visit::where('employee_id', $user->id)
            ->whereDate('scheduled_date', $today)
            ->with(['client', 'client.governorate', 'client.city'])
            ->orderBy('scheduled_time')
            ->get();
        
        $todayAttendance = Attendance::where('employee_id', $user->id)
            ->whereDate('date', $today)
            ->first();
        
        $stats = [
            'todayVisitsCount' => $todayVisits->count(),
            'completedVisitsCount' => Visit::where('employee_id', $user->id)
                ->where('status', 'completed')
                ->whereMonth('scheduled_date', $today->month)
                ->count(),
            'pendingVisitsCount' => Visit::where('employee_id', $user->id)
                ->where('status', 'scheduled')
                ->whereDate('scheduled_date', '>=', $today)
                ->count(),
            'leaveBalance' => $this->calculateLeaveBalance($user),
        ];
        
        return view('employee.dashboard', array_merge($stats, [
            'todayVisits' => $todayVisits,
            'todayAttendance' => $todayAttendance,
        ]));
    }
    
    private function calculateLeaveBalance($user)
    {
        // Default 21 days annual leave
        $annualLeave = 21;
        $usedLeave = LeaveRequest::where('employee_id', $user->id)
            ->where('status', 'approved')
            ->whereYear('created_at', Carbon::now()->year)
            ->sum('total_days');
            
        return max(0, $annualLeave - $usedLeave);
    }
    
    public function checkIn(Request $request)
    {
        $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
        ]);
        
        $user = Auth::user();
        $today = Carbon::today();
        
        $attendance = Attendance::updateOrCreate(
            [
                'employee_id' => $user->id,
                'date' => $today,
            ],
            [
                'check_in' => Carbon::now(),
                'check_in_latitude' => $request->latitude,
                'check_in_longitude' => $request->longitude,
                'status' => 'present',
            ]
        );
        
        return redirect()->route('employee.dashboard')->with('success', 'Checked in successfully.');
    }
    
    public function checkOut(Request $request)
    {
        $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
        ]);
        
        $user = Auth::user();
        $today = Carbon::today();
        
        $attendance = Attendance::where('employee_id', $user->id)
            ->whereDate('date', $today)
            ->first();
            
        if (!$attendance) {
            return back()->with('error', 'Please check in first.');
        }
        
        $checkIn = Carbon::parse($attendance->check_in);
        $workHours = Carbon::now()->diffInHours($checkIn);
        
        $attendance->update([
            'check_out' => Carbon::now(),
            'check_out_latitude' => $request->latitude,
            'check_out_longitude' => $request->longitude,
            'work_hours' => $workHours,
        ]);
        
        return redirect()->route('employee.dashboard')->with('success', 'Checked out successfully.');
    }
}