<?php
namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\CourseSession;
use App\Models\GeneralSetting;
use App\Models\SessionVideo;
use App\Models\VideoProgress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CourseController extends Controller
{
    public function dashboard(){
        $courses = Course::orderBy('id')->get();
        $coursesBanner = trim((string) (GeneralSetting::query()->value('courses_banner') ?? ''));

        if ($courses->isEmpty()) {
            return view('course.empty', compact('coursesBanner'));
        }

        return view('course.dashboard', compact('courses', 'coursesBanner'));
    }

    public function show(Course $course){
        $course->load(['sessions.videos']);
        $coursesBanner = trim((string) (GeneralSetting::query()->value('courses_banner') ?? ''));

        return view('course.show', compact('course', 'coursesBanner'));
    }

    public function session(CourseSession $session){
        $session->load('videos');
        $stats = $this->sessionProgress($session);
        return view('course.session', compact('session','stats'));
    }

    public function watch(SessionVideo $video){
        $session = $video->session()->with('course')->first();
        $progress = VideoProgress::firstOrCreate([
            'user_id'=>Auth::id(),
            'video_id'=>$video->id
        ]);
        return view('course.watch', compact('video','session','progress'));
    }

    public function progress(Request $r, SessionVideo $video){
        $data = $r->validate([
            'seconds' => 'required|integer|min:0',
            'duration'=> 'nullable|integer|min:0',
            'completed'=> 'nullable|boolean',
        ]);

        $vp = VideoProgress::firstOrCreate([
            'user_id'=>Auth::id(),
            'video_id'=>$video->id
        ]);

        $newSeconds = max((int)$vp->seconds_watched, (int)$data['seconds']);
        $vp->seconds_watched = $newSeconds;

        if(isset($data['duration']) && $video->duration === null){
            $video->duration = (int)$data['duration'];
            $video->save();
        }

        $duration = $video->duration ?? ($data['duration'] ?? 0);
        if(($duration > 0 && $newSeconds >= (int)floor($duration * 0.95)) || ($data['completed'] ?? false)){
            if(!$vp->completed_at){ $vp->completed_at = now(); }
        }
        $vp->save();

        $session = $video->session()->with(['videos'])->first();
        $courseSessions = $session->course->sessions()->with('videos')->get();
        [$overallPct, $sessionStats] = $this->computeProgress($courseSessions);

        return response()->json([
            'ok'=>true,
            'video_completed'=> (bool)$vp->completed_at,
            'session_pct' => $sessionStats[$session->id]['pct'] ?? 0,
            'overall_pct' => $overallPct,
        ]);
    }

    private function computeProgress($sessions){
        $userId = Auth::id();
        $totalVideos = 0; $completedVideos = 0; $sessionStats = [];

        foreach($sessions as $s){
            $vCount = $s->videos->count();
            $totalVideos += $vCount;

            $done = VideoProgress::where('user_id',$userId)
                ->whereIn('video_id',$s->videos->pluck('id'))
                ->whereNotNull('completed_at')
                ->count();

            $completedVideos += $done;
            $sessionStats[$s->id] = [
                'title'=>$s->title,
                'total'=>$vCount,
                'done'=>$done,
                'pct'=>$vCount ? round(($done*100)/$vCount) : 0
            ];
        }
        $overallPct = $totalVideos ? round(($completedVideos*100)/$totalVideos) : 0;
        return [$overallPct, $sessionStats];
    }

    private function sessionProgress(CourseSession $session){
        $userId = Auth::id();
        $ids = $session->videos->pluck('id');
        $done = VideoProgress::where('user_id',$userId)->whereIn('video_id',$ids)->whereNotNull('completed_at')->count();
        $total = $session->videos->count();
        return ['total'=>$total,'done'=>$done,'pct'=>$total? round(($done*100)/$total) : 0];
    }
}
