<?php

namespace App\Http\Controllers;

use App\Models\HomepageVideo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Illuminate\Validation\ValidationException;

class HomepageVideoController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $videos = HomepageVideo::orderBy('display_order', 'asc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($video) {
                return [
                    'id' => $video->id,
                    'title' => $video->title,
                    'description' => $video->description,
                    'video_url' => $video->video_url,
                    'display_order' => $video->display_order,
                    'status' => $video->status,
                ];
            });

        return Inertia::render('home_videos/HomeVideos', [
            'videos' => $videos,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'description' => 'nullable|string',
                'video_url' => 'required|url|max:2048',
                'display_order' => 'nullable|integer|min:0',
                'status' => 'required',
            ]);

            // Convert status to boolean (handles string '0', '1', true, false)
            $status = filter_var($validated['status'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
            if ($status === null) {
                $status = $validated['status'] == 1 || $validated['status'] === true || $validated['status'] === '1';
            }

            if (empty($validated['display_order'] ?? null)) {
                $validated['display_order'] = null;
            }
            if (empty($validated['description'] ?? null)) {
                $validated['description'] = null;
            }

            $video = HomepageVideo::create([
                'title' => $validated['title'],
                'description' => $validated['description'] ?? null,
                'video_url' => $validated['video_url'],
                'display_order' => $validated['display_order'] ?? null,
                'status' => $status,
            ]);

            DB::commit();
            return Redirect::back()->with('success', [
                'message' => 'Video created successfully',
                'check' => false,
            ]);
        } catch (ValidationException $e) {
            DB::rollBack();
            return Redirect::back()->withErrors($e->errors())->withInput();
        } catch (\Exception $e) {
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Error: ' . $e->getMessage(),
                'check' => false,
            ]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $video = HomepageVideo::findOrFail($id);

        return response()->json([
            'id' => $video->id,
            'title' => $video->title,
            'description' => $video->description,
            'video_url' => $video->video_url,
            'display_order' => $video->display_order,
            'status' => $video->status,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            DB::beginTransaction();

            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'description' => 'nullable|string',
                'video_url' => 'required|url|max:2048',
                'display_order' => 'nullable|integer|min:0',
                'status' => 'required',
            ]);

            // Convert status to boolean (handles string '0', '1', true, false)
            $status = filter_var($validated['status'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
            if ($status === null) {
                $status = $validated['status'] == 1 || $validated['status'] === true || $validated['status'] === '1';
            }

            if (empty($validated['display_order'] ?? null)) {
                $validated['display_order'] = null;
            }
            if (empty($validated['description'] ?? null)) {
                $validated['description'] = null;
            }

            $video = HomepageVideo::findOrFail($id);

            $video->update([
                'title' => $validated['title'],
                'description' => $validated['description'] ?? null,
                'video_url' => $validated['video_url'],
                'display_order' => $validated['display_order'] ?? null,
                'status' => $status,
            ]);

            DB::commit();
            return Redirect::back()->with('success', [
                'message' => 'Video updated successfully',
                'check' => false,
            ]);
        } catch (ValidationException $e) {
            DB::rollBack();
            return Redirect::back()->withErrors($e->errors())->withInput();
        } catch (\Exception $e) {
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Error: ' . $e->getMessage(),
                'check' => false,
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $video = HomepageVideo::findOrFail($id);

        $video->delete();

        return Redirect::back()->with('success', [
            'message' => 'Video deleted successfully',
            'check' => false,
        ]);
    }
}
