<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\GraduateVideo;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class GraduateVideosController extends Controller
{
    public function index(Request $request)
    {
        $q = trim((string) $request->input('q', ''));

        $videos = GraduateVideo::query()
            ->active()
            ->when($q !== '', function ($query) use ($q) {
                $like = '%'.str_replace(['%', '_'], ['\\%', '\\_'], $q).'%';
                $query->where(function ($qq) use ($like) {
                    $qq->where('title', 'like', $like)
                        ->orWhere('description', 'like', $like);
                });
            })
            ->orderBy('sort_order')
            ->orderByDesc('id')
            ->paginate(12)
            ->withQueryString();

        $seoSettings = getSeoMetas('graduate-videos');
        $pageTitle = ! empty($seoSettings['title']) ? $seoSettings['title'] : 'فيديوهات الخريجين';
        $pageDescription = ! empty($seoSettings['description']) ? $seoSettings['description'] : 'فيديوهات الخريجين';
        $pageRobot = getPageRobot('graduate-videos');

        return view('web.default.pages.graduate_videos.index', [
            'pageTitle' => $pageTitle,
            'pageDescription' => $pageDescription,
            'pageRobot' => $pageRobot,
            'page' => 'graduate-videos',
            'videos' => $videos,
            'searchQuery' => $q,
        ]);
    }

    public function show(GraduateVideo $graduate_video)
    {
        if (! $graduate_video->enabled) {
            abort(404);
        }

        $suggested = GraduateVideo::query()
            ->active()
            ->where('id', '!=', $graduate_video->id)
            ->orderBy('sort_order')
            ->orderByDesc('id')
            ->limit(6)
            ->get();

        $seoSettings = getSeoMetas('graduate-videos');
        $pageTitle = $graduate_video->title.' | '.(! empty($seoSettings['title']) ? $seoSettings['title'] : 'فيديوهات الخريجين');
        $pageDescription = ! empty($graduate_video->description)
            ? Str::limit(strip_tags($graduate_video->description), 160, '')
            : (! empty($seoSettings['description']) ? $seoSettings['description'] : $graduate_video->title);

        return view('web.default.pages.graduate_videos.show', [
            'pageTitle' => $pageTitle,
            'pageDescription' => $pageDescription,
            'pageRobot' => getPageRobot('graduate-videos'),
            'page' => 'graduate-videos',
            'video' => $graduate_video,
            'suggestedVideos' => $suggested,
        ]);
    }
}
