<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\WatchHistory;
use Illuminate\Support\Facades\Auth;

class WatchHistoryController extends Controller
{

    public function store(Request $request)
    {
        if (!Auth::check()) {
            return response()->noContent();
        }

        $request->validate([
            'watchable_type' => 'required|string|in:movie,episode,tv_channel',
            'watchable_id' => 'required|integer',
            'duration' => 'required|integer|min:1',
            'watched_seconds' => 'required|integer|min:0',
        ]);

        // Ensure watched seconds doesn't exceed duration
        $watchedSeconds = min($request->watched_seconds, $request->duration);

        $watchHistory = WatchHistory::firstOrNew([
            'user_id' => Auth::id(),
            'watchable_type' => $request->watchable_type,
            'watchable_id' => $request->watchable_id,
        ]);

        // Only update if the new position is further than previous
        if ($watchedSeconds > ($watchHistory->watched_seconds ?? 0)) {
            $watchHistory->watched_seconds = $watchedSeconds;
            $watchHistory->duration = $request->duration;
            $watchHistory->completion_percentage = min(
                100,
                round(($watchedSeconds / $request->duration) * 100, 2)
            );
            $watchHistory->last_watched_at = now();
            $watchHistory->save();
        }

        return response()->noContent();
    }

    public function loadMore(Request $request)
    {
        $histories = WatchHistory::with([
            'movie',
            'episode.season', // Load season through episode
            'episode.tvshow' // Load tvshow through episode
        ])
            ->where('user_id', auth()->id())
            ->orderBy('last_watched_at', 'desc')
            ->paginate(15, ['*'], 'page', $request->page);

        $html = '';
        foreach ($histories as $history) {
            $html .= view('user.history_item', [
                'history' => $history,
                'video_url' => ''
            ])->render();
        }

        return response()->json([
            'html' => $html,
            'has_more' => $histories->hasMorePages()
        ]);
    }
}
