// app/Http/Controllers/Employee/EmployeeVisitController.php
<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Visit;
use App\Models\VisitTrack;
use Carbon\Carbon;

class EmployeeVisitController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $visits = Visit::where('employee_id', $user->id)
            ->orderBy('scheduled_date', 'desc')
            ->orderBy('scheduled_time', 'desc')
            ->paginate(10);
            
        return view('employee.visits.index', compact('visits'));
    }
    
    public function today()
    {
        $user = Auth::user();
        $today = Carbon::today();
        
        $visits = Visit::where('employee_id', $user->id)
            ->whereDate('scheduled_date', $today)
            ->orderBy('scheduled_time')
            ->get();
            
        return view('employee.visits.today', compact('visits'));
    }
    
    public function show(Visit $visit)
    {
        // Authorization - ensure employee can only view their own visits
        if ($visit->employee_id !== Auth::id()) {
            abort(403);
        }
        
        $trackPoints = VisitTrack::where('visit_id', $visit->id)
            ->orderBy('recorded_at')
            ->get();
            
        return view('employee.visits.show', compact('visit', 'trackPoints'));
    }
    
    public function startVisit(Request $request, Visit $visit)
    {
        // Authorization
        if ($visit->employee_id !== Auth::id()) {
            abort(403);
        }
        
        if ($visit->status !== 'scheduled') {
            return redirect()->back()->with('error', 'Visit cannot be started.');
        }
        
        $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
        ]);
        
        $visit->update([
            'status' => 'started',
            'started_at' => Carbon::now(),
            'start_latitude' => $request->latitude,
            'start_longitude' => $request->longitude,
        ]);
        
        // Record first tracking point
        VisitTrack::create([
            'visit_id' => $visit->id,
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
            'recorded_at' => Carbon::now(),
        ]);
        
        return redirect()->back()->with('success', 'Visit started successfully. Tracking active.');
    }
    
    public function completeVisit(Request $request, Visit $visit)
    {
        // Authorization
        if ($visit->employee_id !== Auth::id()) {
            abort(403);
        }
        
        if ($visit->status !== 'started') {
            return redirect()->back()->with('error', 'Visit must be started first.');
        }
        
        $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
            'comment' => 'nullable|string|max:500',
        ]);
        
        // Calculate distance (simplified - in production use Haversine formula)
        $distance = $this->calculateDistance(
            $visit->start_latitude, $visit->start_longitude,
            $request->latitude, $request->longitude
        );
        
        $visit->update([
            'status' => 'completed',
            'completed_at' => Carbon::now(),
            'end_latitude' => $request->latitude,
            'end_longitude' => $request->longitude,
            'distance_km' => $distance,
            'employee_comment' => $request->comment,
        ]);
        
        // Record final tracking point
        VisitTrack::create([
            'visit_id' => $visit->id,
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
            'recorded_at' => Carbon::now(),
        ]);
        
        return redirect()->back()->with('success', 'Visit completed successfully.');
    }
    
    private function calculateDistance($lat1, $lon1, $lat2, $lon2)
    {
        $earthRadius = 6371; // Kilometers
        
        $latDiff = deg2rad($lat2 - $lat1);
        $lonDiff = deg2rad($lon2 - $lon1);
        
        $a = sin($latDiff/2) * sin($latDiff/2) +
             cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
             sin($lonDiff/2) * sin($lonDiff/2);
        
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        
        return round($earthRadius * $c, 2);
    }
}