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

use Illuminate\Support\Str;
use App\Models\Movies\Genre;
use App\Models\Movies\Movie;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class MovieController extends Controller
{
    public function index()
    {
        $movies = Movie::with('genre')->latest()->paginate(10);
        return view('admin.pages.movies.index', compact('movies'));
    }

    public function create()
    {
        $genres = Genre::where('is_active', true)->get();
        return view('admin.pages.movies.create', compact('genres'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'genre_id' => 'required|exists:genres,id',
            'release_year' => 'required|integer|min:1900|max:' . date('Y'),
            'duration' => 'required|integer|min:1',
            'director' => 'nullable|string|max:255',
            'cast' => 'nullable|string',
            'poster' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'video_url' => 'required|string|max:255',
            'trailer_url' => 'nullable|string|max:255',
            'content_rating' => 'required|string|max:20',
            'featured' => 'boolean',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Handle file upload for poster
        $posterUrl = null;
        if ($request->hasFile('poster')) {
            
            $posterUrl = storeMedia($request->file('poster'), 'movies/poster');

        }

        // Process cast as an array
        $cast = $request->cast ? explode(',', $request->cast) : [];

        $movie = Movie::create([
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
            'genre_id' => $request->genre_id,
            'release_year' => $request->release_year,
            'duration' => $request->duration,
            'director' => $request->director,
            'cast' => $cast,
            'poster_url' => $posterUrl,
            'video_url' => $request->video_url,
            'trailer_url' => $request->trailer_url,
            'content_rating' => $request->content_rating,
            'featured' => $request->featured ?? false,
            'is_active' => $request->is_active ?? true,
            'views_count' => 0,
        ]);

        return redirect()->route('admin.movies.index')
            ->with('success', 'Movie created successfully.');
    }

    public function edit(Movie $movie)
    {
        $genres = Genre::where('is_active', true)->get();
        return view('admin.pages.movies.edit', compact('movie', 'genres'));
    }

    public function update(Request $request, Movie $movie)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'genre_id' => 'required|exists:genres,id',
            'release_year' => 'required|integer|min:1900|max:' . date('Y'),
            'duration' => 'required|integer|min:1',
            'director' => 'nullable|string|max:255',
            'cast' => 'nullable|string',
            'poster' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'video_url' => 'required|string|max:255',
            'trailer_url' => 'nullable|string|max:255',
            'content_rating' => 'required|string|max:20',
            'featured' => 'boolean',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Handle file upload for poster
        if ($request->hasFile('poster')) {
            // Delete old poster if exists
            if ($movie->poster_url && Storage::exists('public/' . str_replace('/storage/', '', $movie->poster_url))) {
                Storage::delete('public/' . str_replace('/storage/', '', $movie->poster_url));
            }
            
            $posterPath = $request->file('poster')->store('posters', 'public');
            $movie->poster_url = Storage::url($posterPath);
        }

        // Process cast as an array
        $cast = $request->cast ? explode(',', $request->cast) : [];

        $movie->update([
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
            'genre_id' => $request->genre_id,
            'release_year' => $request->release_year,
            'duration' => $request->duration,
            'director' => $request->director,
            'cast' => $cast,
            'video_url' => $request->video_url,
            'trailer_url' => $request->trailer_url,
            'content_rating' => $request->content_rating,
            'featured' => $request->featured ?? false,
            'is_active' => $request->is_active ?? true,
        ]);

        return redirect()->route('admin.movies.index')
            ->with('success', 'Movie updated successfully.');
    }

    public function destroy(Movie $movie)
    {
        $movie->delete();
        return redirect()->route('admin.movies.index')
            ->with('success', 'Movie deleted successfully.');
    }
}