<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CourseSession;
use App\Models\SessionVideo;
use Illuminate\Http\Request;

class VideoAdminController extends Controller {
    public function index(CourseSession $session){
        $videos = $session->videos;
        return view('admin.videos.index', compact('session','videos'));
    }
    public function store(Request $r, CourseSession $session){
        $data = $r->validate([
            'title'=>'required|max:190',
            'source_type'=>'required|in:url,file',
            'source_path'=>'required',
            'duration'=>'nullable|integer|min:1',
            'order'=>'nullable|integer|min:1',
            'thumbnail_image'=>'nullable|image|max:3072'
        ]);
        $data['order'] = $data['order'] ?? (int)($session->videos()->max('order') ?? 0) + 1;
        $thumbPath = $this->storeThumbnail($r);
        if ($thumbPath) {
            $data['thumbnail_path'] = $thumbPath;
        }
        $session->videos()->create($data);
        return back()->with('success','ভিডিও যুক্ত হয়েছে');
    }
    public function update(Request $r, SessionVideo $video){
        $data = $r->validate([
            'title'=>'required|max:190',
            'source_type'=>'required|in:url,file',
            'source_path'=>'required',
            'duration'=>'nullable|integer|min:1',
            'order'=>'nullable|integer|min:1',
            'thumbnail_image'=>'nullable|image|max:3072'
        ]);
        $thumbPath = $this->storeThumbnail($r);
        if ($thumbPath) {
            $this->deleteThumbnail($video->thumbnail_path ?? null);
            $data['thumbnail_path'] = $thumbPath;
        }
        $video->update($data);
        return back()->with('success','ভিডিও আপডেট হয়েছে');
    }
    public function destroy(SessionVideo $video){
        $this->deleteThumbnail($video->thumbnail_path ?? null);
        $video->delete();
        return back()->with('success','ভিডিও ডিলিট হয়েছে');
    }

    private function storeThumbnail(Request $request): ?string
    {
        if (!$request->hasFile('thumbnail_image')) {
            return null;
        }

        $file = $request->file('thumbnail_image');
        if (!$file || !$file->isValid()) {
            return null;
        }

        $ext = $file->getClientOriginalExtension();
        $name = time() . '_' . uniqid('course_thumb_', true) . '.' . $ext;
        $dir = ensure_public_directory('images/course_thumbs');
        $file->move($dir, $name);
        optimize_uploaded_image($dir . DIRECTORY_SEPARATOR . $name);

        return '/images/course_thumbs/' . $name;
    }

    private function deleteThumbnail(?string $path): void
    {
        if (!$path) {
            return;
        }

        delete_public_asset($path);
    }
}
