<?php

namespace App\Http\Controllers\Admin;

use App\Exports\WebinarsExport;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Panel\WebinarStatisticController;
use App\Mail\SendNotifications;
use App\Models\BundleWebinar;
use App\Models\Bundle;
use App\Models\WebinarForItem;
use App\Models\Translation\WebinarForItemTranslation;
use App\Models\Category;
use App\Models\Faq;
use App\Models\File;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\Notification;
use App\Models\Prerequisite;
use App\Models\Quiz;
use App\Models\Reward;
use App\Models\RewardAccounting;
use App\Models\Role;
use App\Models\Sale;
use App\Models\Session;
use App\Models\SpecialOffer;
use App\Models\Tag;
use App\Models\TextLesson;
use App\Models\Ticket;
use App\Models\Translation\WebinarTranslation;
use App\Models\WebinarChapter;
use App\Models\WebinarChapterItem;
use App\Models\WebinarExtraDescription;
use App\Models\WebinarFilterOption;
use App\Models\WebinarPartnerTeacher;
use App\User;
use App\Models\Webinar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class WebinarController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('admin_webinars_list');

        removeContentLocale();

        $type = $request->get('type', 'webinar');
        $query = Webinar::where('webinars.type', $type);

        $totalWebinars = $query->count();
        $totalPendingWebinars = deepClone($query)->where('webinars.status', 'pending')->count();
        $totalDurations = deepClone($query)->sum('duration');
        $totalSales = deepClone($query)->join('sales', 'webinars.id', '=', 'sales.webinar_id')
            ->select(DB::raw('count(sales.webinar_id) as sales_count'))
            ->whereNotNull('sales.webinar_id')
            ->whereNull('sales.refund_at')
            ->first();

        $categories = Category::where('parent_id', null)
            ->with('subCategories')
            ->get();

        $inProgressWebinars = 0;
        if ($type == 'webinar') {
            $inProgressWebinars = $this->getInProgressWebinarsCount();
        }

        $query = $this->filterWebinar($query, $request)
            ->with([
                'category',
                'teacher' => function ($qu) {
                    $qu->select('id', 'full_name');
                },
                'sales' => function ($query) {
                    $query->whereNull('refund_at');
                }
            ]);

        $webinars = $query->paginate(10);

        if ($request->get('status', null) == 'active_finished') {
            foreach ($webinars as $key => $webinar) {
                if ($webinar->last_date > time()) { // is in progress
                    unset($webinars[$key]);
                }
            }
        }

        $data = [
            'pageTitle' => trans('admin/pages/webinars.webinars_list_page_title'),
            'webinars' => $webinars,
            'totalWebinars' => $totalWebinars,
            'totalPendingWebinars' => $totalPendingWebinars,
            'totalDurations' => $totalDurations,
            'totalSales' => !empty($totalSales) ? $totalSales->sales_count : 0,
            'categories' => $categories,
            'inProgressWebinars' => $inProgressWebinars,
            'classesType' => $type,
        ];

        $teacher_ids = $request->get('teacher_ids', null);
        if (!empty($teacher_ids)) {
            $data['teachers'] = User::select('id', 'full_name')->whereIn('id', $teacher_ids)->get();
        }

        return view('admin.webinars.lists', $data);
    }

    private function filterWebinar($query, $request)
    {
        $from = $request->get('from', null);
        $to = $request->get('to', null);
        $title = $request->get('title', null);
        $teacher_ids = $request->get('teacher_ids', null);
        $category_id = $request->get('category_id', null);
        $status = $request->get('status', null);
        $sort = $request->get('sort', null);

        $query = fromAndToDateFilter($from, $to, $query, 'created_at');

        if (!empty($title)) {
            $query->whereTranslationLike('title', '%' . $title . '%');
        }

        if (!empty($teacher_ids) and count($teacher_ids)) {
            $query->whereIn('teacher_id', $teacher_ids);
        }

        if (!empty($category_id)) {
            $query->where('category_id', $category_id);
        }

        if (!empty($status)) {
            $time = time();

            switch ($status) {
                case 'active_not_conducted':
                    $query->where('webinars.status', 'active')
                        ->where('start_date', '>', $time);
                    break;
                case 'active_in_progress':
                    $query->where('webinars.status', 'active')
                        ->where('start_date', '<=', $time)
                        ->join('sessions', 'webinars.id', '=', 'sessions.webinar_id')
                        ->select('webinars.*', 'sessions.date', DB::raw('max(`date`) as last_date'))
                        ->groupBy('sessions.webinar_id')
                        ->where('sessions.date', '>', $time);
                    break;
                case 'active_finished':
                    $query->where('webinars.status', 'active')
                        ->where('start_date', '<=', $time)
                        ->join('sessions', 'webinars.id', '=', 'sessions.webinar_id')
                        ->select('webinars.*', 'sessions.date', DB::raw('max(`date`) as last_date'))
                        ->groupBy('sessions.webinar_id');
                    break;
                default:
                    $query->where('webinars.status', $status);
                    break;
            }
        }

        if (!empty($sort)) {
            switch ($sort) {
                case 'has_discount':
                    $now = time();
                    $webinarIdsHasDiscount = [];

                    $tickets = Ticket::where('start_date', '<', $now)
                        ->where('end_date', '>', $now)
                        ->get();

                    foreach ($tickets as $ticket) {
                        if ($ticket->isValid()) {
                            $webinarIdsHasDiscount[] = $ticket->webinar_id;
                        }
                    }

                    $specialOffersWebinarIds = SpecialOffer::where('status', 'active')
                        ->where('from_date', '<', $now)
                        ->where('to_date', '>', $now)
                        ->pluck('webinar_id')
                        ->toArray();

                    $webinarIdsHasDiscount = array_merge($specialOffersWebinarIds, $webinarIdsHasDiscount);

                    $query->whereIn('id', $webinarIdsHasDiscount)
                        ->orderBy('created_at', 'desc');
                    break;
                case 'sales_asc':
                    $query->join('sales', 'webinars.id', '=', 'sales.webinar_id')
                        ->select('webinars.*', 'sales.webinar_id', 'sales.refund_at', DB::raw('count(sales.webinar_id) as sales_count'))
                        ->whereNotNull('sales.webinar_id')
                        ->whereNull('sales.refund_at')
                        ->groupBy('sales.webinar_id')
                        ->orderBy('sales_count', 'asc');
                    break;
                case 'sales_desc':
                    $query->join('sales', 'webinars.id', '=', 'sales.webinar_id')
                        ->select('webinars.*', 'sales.webinar_id', 'sales.refund_at', DB::raw('count(sales.webinar_id) as sales_count'))
                        ->whereNotNull('sales.webinar_id')
                        ->whereNull('sales.refund_at')
                        ->groupBy('sales.webinar_id')
                        ->orderBy('sales_count', 'desc');
                    break;

                case 'price_asc':
                    $query->orderBy('price', 'asc');
                    break;

                case 'price_desc':
                    $query->orderBy('price', 'desc');
                    break;

                case 'income_asc':
                    $query->join('sales', 'webinars.id', '=', 'sales.webinar_id')
                        ->select('webinars.*', 'sales.webinar_id', 'sales.total_amount', 'sales.refund_at', DB::raw('(sum(sales.total_amount) - (sum(sales.tax) + sum(sales.commission))) as amounts'))
                        ->whereNotNull('sales.webinar_id')
                        ->whereNull('sales.refund_at')
                        ->groupBy('sales.webinar_id')
                        ->orderBy('amounts', 'asc');
                    break;

                case 'income_desc':
                    $query->join('sales', 'webinars.id', '=', 'sales.webinar_id')
                        ->select('webinars.*', 'sales.webinar_id', 'sales.total_amount', 'sales.refund_at', DB::raw('(sum(sales.total_amount) - (sum(sales.tax) + sum(sales.commission))) as amounts'))
                        ->whereNotNull('sales.webinar_id')
                        ->whereNull('sales.refund_at')
                        ->groupBy('sales.webinar_id')
                        ->orderBy('amounts', 'desc');
                    break;

                case 'created_at_asc':
                    $query->orderBy('created_at', 'asc');
                    break;

                case 'created_at_desc':
                    $query->orderBy('created_at', 'desc');
                    break;

                case 'updated_at_asc':
                    $query->orderBy('updated_at', 'asc');
                    break;

                case 'updated_at_desc':
                    $query->orderBy('updated_at', 'desc');
                    break;
            }
        } else {
            $query->orderBy('created_at', 'desc');
        }


        return $query;
    }

    private function getInProgressWebinarsCount()
    {
        $count = 0;
        $webinars = Webinar::where('type', 'webinar')
            ->where('status', 'active')
            ->where('start_date', '<=', time())
            ->whereHas('sessions')
            ->get();

        foreach ($webinars as $webinar) {
            if ($webinar->isProgressing()) {
                $count += 1;
            }
        }

        return $count;
    }

    public function create()
    {
        $this->authorize('admin_webinars_create');

        removeContentLocale();

        $teachers = User::where('role_name', Role::$teacher)->get();
        $categories = Category::where('parent_id', null)->get();

        $data = [
            'pageTitle' => trans('admin/main.webinar_new_page_title'),
            'teachers' => $teachers,
            'categories' => $categories
        ];

        return view('admin.webinars.create', $data);
    }

    public function store(Request $request)
    {
        $this->authorize('admin_webinars_create');

        $this->validate($request, [
            'type' => 'required|in:webinar,course,text_lesson',
            'title' => 'required|max:255',
            'slug' => 'max:255|unique:webinars,slug',
            'thumbnail' => 'required',
            'image_cover' => 'required',
            'description' => 'required',
            'teacher_id' => 'required|exists:users,id',
            'category_id' => 'required',
            'duration' => 'required',
            'start_date' => 'required_if:type,webinar',
            'capacity' => 'required_if:type,webinar',
            'points'    => 'nullable|numeric',
            'order_show' => 'nullable|numeric',
            'currency' => 'nullable|in:EGP,USD',
        ]);

        $data = $request->all();

        if ($data['type'] != Webinar::$webinar) {
            $data['start_date'] = null;
        }

        if (!empty($data['start_date']) and $data['type'] == Webinar::$webinar) {
            if (empty($data['timezone']) or !getFeaturesSettings('timezone_in_create_webinar')) {
                $data['timezone'] = getTimezone();
            }

            $startDate = convertTimeToUTCzone($data['start_date'], $data['timezone']);

            $data['start_date'] = $startDate->getTimestamp();
        }

        if (empty($data['slug'])) {
            $data['slug'] = Webinar::makeSlug($data['title']);
        }

        if (empty($data['video_demo'])) {
            $data['video_demo_source'] = null;
        }

        if (!empty($data['video_demo_source']) and !in_array($data['video_demo_source'], ['upload', 'youtube', 'vimeo', 'external_link'])) {
            $data['video_demo_source'] = 'upload';
        }

        try {
            $webinar = DB::transaction(function () use ($data, $request) {
                $webinar = Webinar::create($this->buildWebinarAttributes($data, true));

                if (!$webinar->exists || empty($webinar->id)) {
                    throw new \RuntimeException('Failed to create webinar record.');
                }

                $this->saveWebinarTranslation($webinar, $data);

                $filters = $request->get('filters', null);
                if (!empty($filters) and is_array($filters)) {
                    WebinarFilterOption::where('webinar_id', $webinar->id)->delete();
                    foreach ($filters as $filter) {
                        WebinarFilterOption::create([
                            'webinar_id' => $webinar->id,
                            'filter_option_id' => $filter
                        ]);
                    }
                }

                if (!empty($request->get('tags'))) {
                    $tags = explode(',', $request->get('tags'));
                    Tag::where('webinar_id', $webinar->id)->delete();

                    foreach ($tags as $tag) {
                        Tag::create([
                            'webinar_id' => $webinar->id,
                            'title' => $tag,
                        ]);
                    }
                }

                if (!empty($request->get('partner_instructor')) and !empty($request->get('partners'))) {
                    WebinarPartnerTeacher::where('webinar_id', $webinar->id)->delete();

                    foreach ($request->get('partners') as $partnerId) {
                        WebinarPartnerTeacher::create([
                            'webinar_id' => $webinar->id,
                            'teacher_id' => $partnerId,
                        ]);
                    }
                }

                return $webinar->refresh();
            });
        } catch (\Throwable $e) {
            report($e);

            return back()
                ->withInput()
                ->withErrors(['error' => trans('public.request_failed') . ': ' . $e->getMessage()]);
        }

        $locale = mb_strtolower($data['locale'] ?? getDefaultLocale());

        return redirect('/admin/webinars/' . $webinar->id . '/edit?locale=' . $locale);
    }

    public function edit(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        $webinar = Webinar::where('id', $id)
            ->with([
                'tickets',
                'sessions' => function ($query) {
                    $query->with('allowedUsers');
                },
                'files' => function ($query) {
                    $query->with('allowedUsers');
                },
                'textLessons' => function ($query) {
                    $query->with('allowedUsers');
                },
                'faqs',
                'category' => function ($query) {
                    $query->with(['filters' => function ($query) {
                        $query->with('options');
                    }]);
                },
                'filterOptions',
                'prerequisites',
                'quizzes',
                'webinarPartnerTeacher' => function ($query) {
                    $query->with(['teacher' => function ($query) {
                        $query->select('id', 'full_name');
                    }]);
                },
                'tags',
                'assignments',
                'chapters' => function ($query) {
                    $query->orderBy('order', 'asc');
                    $query->with([
                        'chapterItems' => function ($query) {
                            $query->orderBy('order', 'asc');
                        }
                    ]);
                },
            ])
            ->first();

        if (empty($webinar)) {
            abort(404);
        }

        $locale = $request->get('locale', app()->getLocale());
        storeContentLocale($locale, $webinar->getTable(), $webinar->id);

        $categories = Category::where('parent_id', null)
            ->with('subCategories')
            ->get();

        $teacherQuizzes = Quiz::where('webinar_id', null)
            ->where('creator_id', $webinar->teacher_id)
            ->get();

        $tags = $webinar->tags->pluck('title')->toArray();
        
        // Collect all user IDs that are already assigned to any lecture (file, session, textLesson)
        $assignedUserIds = collect();
        foreach ($webinar->files as $file) {
            $assignedUserIds = $assignedUserIds->merge($file->allowedUsers->pluck('id'));
        }
        foreach ($webinar->sessions as $session) {
            $assignedUserIds = $assignedUserIds->merge($session->allowedUsers->pluck('id'));
        }
        foreach ($webinar->textLessons as $textLesson) {
            $assignedUserIds = $assignedUserIds->merge($textLesson->allowedUsers->pluck('id'));
        }
        $assignedUserIds = $assignedUserIds->unique()->values()->all();
        
        // Get all assigned users first (these MUST be in the list)
        $allUsers = collect();
        if (!empty($assignedUserIds)) {
            $assignedUsers = User::select('id', 'full_name', 'email')
                ->whereIn('id', $assignedUserIds)
                ->whereIn('status', ['active', 'pending', 'inactive'])
                ->orderBy('full_name', 'asc')
                ->get();
            $allUsers = $allUsers->merge($assignedUsers);
        }
        
        // Also get first 10 other users (for quick selection of new users)
        $otherUsers = User::select('id', 'full_name', 'email')
            ->whereIn('status', ['active', 'pending', 'inactive'])
            ->orderBy('full_name', 'asc');
        
        if (!empty($assignedUserIds)) {
            $otherUsers->whereNotIn('id', $assignedUserIds);
        }
        
        $otherUsers = $otherUsers->limit(10)->get();
        $allUsers = $allUsers->merge($otherUsers);
        
        // Remove duplicates and sort
        $allUsers = $allUsers->unique('id')->sortBy('full_name')->values();

        $data = [
            'pageTitle' => trans('admin/main.edit') . ' | ' . $webinar->title,
            'categories' => $categories,
            'webinar' => $webinar,
            'webinarCategoryFilters' => $webinar->category->filters,
            'webinarFilterOptions' => $webinar->filterOptions->pluck('filter_option_id')->toArray(),
            'tickets' => $webinar->tickets,
            'chapters' => $webinar->chapters,
            'sessions' => $webinar->sessions,
            'files' => $webinar->files,
            'textLessons' => $webinar->textLessons,
            'faqs' => $webinar->faqs,
            'assignments' => $webinar->assignments,
            'teacherQuizzes' => $teacherQuizzes,
            'prerequisites' => $webinar->prerequisites,
            'webinarQuizzes' => $webinar->quizzes,
            'webinarPartnerTeacher' => $webinar->webinarPartnerTeacher,
            'webinarTags' => $tags,
            'defaultLocale' => getDefaultLocale(),
            'allUsers' => $allUsers,
        ];

        return view('admin.webinars.create', $data);
    }

    public function searchUsers(Request $request)
    {
        try {
            $this->authorize('admin_webinars_edit');
        } catch (\Exception $e) {
            \Log::error('Search users authorization failed', [
                'error' => $e->getMessage(),
                'user' => auth()->user()->id ?? 'not authenticated'
            ]);
            return response()->json([
                'error' => 'Unauthorized'
            ], 403);
        }

        $search = trim($request->get('q', ''));
        
        \Log::info('Search users request', [
            'search' => $search,
            'user_id' => auth()->user()->id ?? 'not authenticated'
        ]);

        $usersQuery = User::select('id', 'full_name', 'email')
            ->whereIn('status', ['active', 'pending', 'inactive']);

        if ($search !== '') {
            $usersQuery->where(function($query) use ($search) {
                $query->where('full_name', 'LIKE', "%{$search}%")
                      ->orWhere('email', 'LIKE', "%{$search}%");
            });
        }

        $users = $usersQuery
            ->orderBy('full_name', 'asc')
            ->limit(200) // Increased limit for "show all users" feature
            ->get();

        $results = [];
        foreach ($users as $user) {
            $results[] = [
                'id' => $user->id,
                'text' => $user->full_name . ' (' . $user->email . ')'
            ];
        }

        return response()->json($results);
    }

    public function showAllUsers(Request $request)
    {
        $this->authorize('admin_webinars_edit');

        $search = trim($request->get('q', ''));
        $selectedIds = $request->get('selected_ids', '');
        $onlySelected = (bool) $request->get('only_selected', false);
        $selectIdentifier = $request->get('select_identifier', '');

        $usersQuery = User::select('id', 'full_name', 'email')
            ->whereIn('status', ['active', 'pending', 'inactive']);

        if ($search !== '') {
            $usersQuery->where(function($query) use ($search) {
                $query->where('full_name', 'LIKE', "%{$search}%")
                      ->orWhere('email', 'LIKE', "%{$search}%");
            });
        }

        // If only_selected is set and we have selected IDs, restrict to those users
        $selectedIdsArray = [];
        if (!empty($selectedIds)) {
            $selectedIdsArray = array_filter(array_map('intval', explode(',', $selectedIds)));
        }

        if ($onlySelected && !empty($selectedIdsArray)) {
            $usersQuery->whereIn('id', $selectedIdsArray);
        }

        $users = $usersQuery
            ->orderBy('full_name', 'asc')
            ->limit(500) // Show up to 500 users
            ->get();


        $data = [
            'pageTitle' => trans('admin/main.all_users'),
            'users' => $users,
            'selectedIds' => $selectedIdsArray,
            'search' => $search,
            'selectIdentifier' => $selectIdentifier,
        ];

        return view('admin.webinars.show_all_users', $data);
    }

    public function getUsersByIds(Request $request)
    {
        $this->authorize('admin_webinars_edit');

        $userIds = $request->get('ids', []);
        
        if (empty($userIds) || !is_array($userIds)) {
            return response()->json([]);
        }

        // Filter and convert to integers
        $userIds = array_filter(array_map('intval', $userIds));
        
        if (empty($userIds)) {
            return response()->json([]);
        }

        $users = User::select('id', 'full_name', 'email')
            ->whereIn('id', $userIds)
            ->whereIn('status', ['active', 'pending', 'inactive'])
            ->orderBy('full_name', 'asc')
            ->get();

        $results = [];
        foreach ($users as $user) {
            $results[] = [
                'id' => $user->id,
                'text' => $user->full_name . ' (' . $user->email . ')'
            ];
        }

        return response()->json($results);
    }

    public function update(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');
        $data = $request->all();

        $webinar = Webinar::find($id);
        $isDraft = (!empty($data['draft']) and $data['draft'] == 1);
        $reject = (!empty($data['draft']) and $data['draft'] == 'reject');
        $publish = (!empty($data['draft']) and $data['draft'] == 'publish');

        $rules = [
            'type' => 'required|in:webinar,course,text_lesson',
            'title' => 'required|max:255',
            'slug' => 'max:255|unique:webinars,slug,' . $webinar->id,
            'thumbnail' => 'required',
            'image_cover' => 'required',
            'description' => 'required',
            'teacher_id' => 'required|exists:users,id',
            'category_id' => 'required',
             'points'    => 'nullable|numeric',
              'order_show' => 'nullable|numeric',
            'currency' => 'nullable|in:EGP,USD',
        ];

        if ($webinar->isWebinar()) {
            $rules['start_date'] = 'required|date';
            $rules['duration'] = 'required';
            $rules['capacity'] = 'required|integer';
        }

        $this->validate($request, $rules);

        if (!empty($data['teacher_id'])) {
            $teacher = User::find($data['teacher_id']);
            $creator = $webinar->creator;

            if (empty($teacher) or ($creator->isOrganization() and ($teacher->organ_id != $creator->id and $teacher->id != $creator->id))) {
                $toastData = [
                    'title' => trans('public.request_failed'),
                    'msg' => trans('admin/main.is_not_the_teacher_of_this_organization'),
                    'status' => 'error'
                ];
                return back()->with(['toast' => $toastData]);
            }
        }


        if (empty($data['slug'])) {
            $data['slug'] = Webinar::makeSlug($data['title']);
        }

        $data['status'] = $publish ? Webinar::$active : ($reject ? Webinar::$inactive : ($isDraft ? Webinar::$isDraft : Webinar::$pending));
        $data['updated_at'] = time();

        if (!empty($data['start_date']) and $webinar->type == 'webinar') {
            if (empty($data['timezone']) or !getFeaturesSettings('timezone_in_create_webinar')) {
                $data['timezone'] = getTimezone();
            }

            $startDate = convertTimeToUTCzone($data['start_date'], $data['timezone']);

            $data['start_date'] = $startDate->getTimestamp();
        } else {
            $data['start_date'] = null;
        }

        $data['private'] = (!empty($data['private']) and $data['private'] == 'on');
        $data['support'] = !empty($data['support']) ? true : false;
        $data['certificate'] = !empty($data['certificate']) ? true : false;
        $data['downloadable'] = !empty($data['downloadable']) ? true : false;
        $data['partner_instructor'] = !empty($data['partner_instructor']) ? true : false;
        $data['subscribe'] = !empty($data['subscribe']) ? true : false;
        $data['forum'] = !empty($data['forum']) ? true : false;

        if (empty($data['partner_instructor'])) {
            WebinarPartnerTeacher::where('webinar_id', $webinar->id)->delete();
            unset($data['partners']);
        }

        if ($data['category_id'] !== $webinar->category_id) {
            WebinarFilterOption::where('webinar_id', $webinar->id)->delete();
        }

        $filters = $request->get('filters', null);
        if (!empty($filters) and is_array($filters)) {
            WebinarFilterOption::where('webinar_id', $webinar->id)->delete();
            foreach ($filters as $filter) {
                WebinarFilterOption::create([
                    'webinar_id' => $webinar->id,
                    'filter_option_id' => $filter
                ]);
            }
        }

        if (!empty($request->get('tags'))) {
            $tags = explode(',', $request->get('tags'));
            Tag::where('webinar_id', $webinar->id)->delete();

            foreach ($tags as $tag) {
                Tag::create([
                    'webinar_id' => $webinar->id,
                    'title' => $tag,
                ]);
            }
        }

        if (!empty($request->get('partner_instructor')) and !empty($request->get('partners'))) {
            WebinarPartnerTeacher::where('webinar_id', $webinar->id)->delete();

            foreach ($request->get('partners') as $partnerId) {
                WebinarPartnerTeacher::create([
                    'webinar_id' => $webinar->id,
                    'teacher_id' => $partnerId,
                ]);
            }
        }
        unset($data['_token'],
            $data['current_step'],
            $data['draft'],
            $data['get_next'],
            $data['partners'],
            $data['tags'],
            $data['filters'],
            $data['ajax']
        );

        if (empty($data['video_demo'])) {
            $data['video_demo_source'] = null;
        }

        if (!empty($data['video_demo_source']) and !in_array($data['video_demo_source'], ['upload', 'youtube', 'vimeo', 'external_link'])) {
            $data['video_demo_source'] = 'upload';
        }

        $updateData = $this->buildWebinarAttributes($data, false);
        unset($updateData['creator_id'], $updateData['created_at'], $updateData['status']);
        $updateData['status'] = $data['status'];
        $updateData['private'] = $data['private'] ?? false;
        $updateData['start_date'] = $data['start_date'] ?? null;

        $webinar->update($updateData);

        $this->saveWebinarTranslation($webinar, $data);

        if ($publish) {
            sendNotification('course_approve', ['[c.title]' => $webinar->title], $webinar->teacher_id);

            $createClassesReward = RewardAccounting::calculateScore(Reward::CREATE_CLASSES);
            RewardAccounting::makeRewardAccounting(
                $webinar->creator_id,
                $createClassesReward,
                Reward::CREATE_CLASSES,
                $webinar->id,
                true
            );

        } elseif ($reject) {
            sendNotification('course_reject', ['[c.title]' => $webinar->title], $webinar->teacher_id);
        }

        removeContentLocale();

        return back();
    }

    public function destroy(Request $request, $id)
    {
        $this->authorize('admin_webinars_delete');

        Webinar::find($id)->delete();

        return redirect('/admin/webinars');
    }

    public function search(Request $request)
    {
        $term = $request->get('term');

        $option = $request->get('option', null);

        $query = Webinar::select('id')
            ->whereTranslationLike('title', "%$term%");

        if (!empty($option) and $option == 'just_webinar') {
            $query->where('type', Webinar::$webinar);
            $query->where('status', Webinar::$active);
        }

        $webinar = $query->get();

        return response()->json($webinar, 200);
    }

    public function exportExcel(Request $request)
    {
        $this->authorize('admin_webinars_export_excel');

        $query = Webinar::query();

        $query = $this->filterWebinar($query, $request)
            ->with(['teacher' => function ($qu) {
                $qu->select('id', 'full_name');
            }, 'sales']);

        $webinars = $query->get();

        $webinarExport = new WebinarsExport($webinars);

        return Excel::download($webinarExport, 'webinars.xlsx');
    }

    public function studentsLists(Request $request, $id)
    {
        $this->authorize('admin_webinar_students_lists');

        $webinar = Webinar::where('id', $id)
            ->with([
                'teacher' => function ($qu) {
                    $qu->select('id', 'full_name');
                },
                'chapters' => function ($query) {
                    $query->where('status', 'active');
                },
                'sessions' => function ($query) {
                    $query->where('status', 'active');
                },
                'assignments' => function ($query) {
                    $query->where('status', 'active');
                },
                'quizzes' => function ($query) {
                    $query->where('status', 'active');
                },
                'files' => function ($query) {
                    $query->where('status', 'active');
                },
            ])
            ->first();


        if (!empty($webinar)) {

            $query = User::join('sales', 'sales.buyer_id', 'users.id')
                ->leftJoin('webinar_reviews', function ($query) use ($webinar) {
                    $query->on('webinar_reviews.creator_id', 'users.id')
                        ->where('webinar_reviews.webinar_id', $webinar->id);
                })
                ->select('users.*', 'webinar_reviews.rates', DB::raw('sales.created_at as purchase_date'))
                ->where('sales.webinar_id', $webinar->id)
                ->whereNull('sales.refund_at');

            $students = $this->studentsListsFilters($webinar, $query, $request)
                ->orderBy('sales.created_at', 'desc')
                ->paginate(10);

            $userGroups = Group::where('status', 'active')
                ->orderBy('created_at', 'desc')
                ->get();

            $totalExpireStudents = 0;
            if (!empty($webinar->access_days)) {
                $accessTimestamp = $webinar->access_days * 24 * 60 * 60;

                $totalExpireStudents = User::join('sales', 'sales.buyer_id', 'users.id')
                    ->select('users.*', DB::raw('sales.created_at as purchase_date'))
                    ->where('sales.webinar_id', $webinar->id)
                    ->whereRaw('sales.created_at + ? < ?', [$accessTimestamp, time()])
                    ->whereNull('sales.refund_at')
                    ->count();
            }

            $webinarStatisticController = new WebinarStatisticController();

            $allStudentsIds = User::join('sales', 'sales.buyer_id', 'users.id')
                ->select('users.*', DB::raw('sales.created_at as purchase_date'))
                ->where('sales.webinar_id', $webinar->id)
                ->whereNull('sales.refund_at')
                ->pluck('id')
                ->toArray();

            $learningPercents = [];
            foreach ($allStudentsIds as $studentsId) {
                $learningPercents[$studentsId] = $webinarStatisticController->getCourseProgressForStudent($webinar, $studentsId);
            }

            foreach ($students as $student) {
                $student->learning = !empty($learningPercents[$student->id]) ? $learningPercents[$student->id] : 0;
            }

            $roles = Role::all();

            $data = [
                'pageTitle' => trans('admin/main.students'),
                'webinar' => $webinar,
                'students' => $students,
                'userGroups' => $userGroups,
                'roles' => $roles,
                'totalStudents' => $students->total(),
                'totalActiveStudents' => $students->total() - $totalExpireStudents,
                'totalExpireStudents' => $totalExpireStudents,
                'averageLearning' => count($learningPercents) ? round(array_sum($learningPercents) / count($learningPercents), 2) : 0,
            ];

            return view('admin.webinars.students', $data);
        }

        abort(404);
    }

    private function studentsListsFilters($webinar, $query, $request)
    {
        $from = $request->input('from');
        $to = $request->input('to');
        $full_name = $request->get('full_name');
        $sort = $request->get('sort');
        $group_id = $request->get('group_id');
        $role_id = $request->get('role_id');
        $status = $request->get('status');

        $query = fromAndToDateFilter($from, $to, $query, 'sales.created_at');

        if (!empty($full_name)) {
            $query->where('users.full_name', 'like', "%$full_name%");
        }

        if (!empty($sort)) {
            if ($sort == 'rate_asc') {
                $query->orderBy('webinar_reviews.rates', 'asc');
            }

            if ($sort == 'rate_desc') {
                $query->orderBy('webinar_reviews.rates', 'desc');
            }
        }

        if (!empty($group_id)) {
            $userIds = GroupUser::where('group_id', $group_id)->pluck('user_id')->toArray();

            $query->whereIn('users.id', $userIds);
        }

        if (!empty($role_id)) {
            $query->where('users.role_id', $role_id);
        }

        if (!empty($status)) {
            if ($status == 'expire' and !empty($webinar->access_days)) {
                $accessTimestamp = $webinar->access_days * 24 * 60 * 60;

                $query->whereRaw('sales.created_at + ? < ?', [$accessTimestamp, time()]);
            }
        }

        return $query;
    }

    public function notificationToStudents($id)
    {
        $this->authorize('admin_webinar_notification_to_students');

        $webinar = Webinar::findOrFail($id);

        $data = [
            'pageTitle' => trans('notification.send_notification'),
            'webinar' => $webinar
        ];

        return view('admin.webinars.send-notification-to-course-students', $data);
    }


    public function sendNotificationToStudents(Request $request, $id)
    {
        $this->authorize('admin_webinar_notification_to_students');

        $this->validate($request, [
            'title' => 'required|string',
            'message' => 'required|string',
        ]);

        $data = $request->all();

        $webinar = Webinar::where('id', $id)
            ->with([
                'sales' => function ($query) {
                    $query->whereNull('refund_at');
                    $query->with([
                        'buyer'
                    ]);
                }
            ])
            ->first();

        if (!empty($webinar)) {
            foreach ($webinar->sales as $sale) {
                if (!empty($sale->buyer)) {
                    $user = $sale->buyer;

                    Notification::create([
                        'user_id' => $user->id,
                        'group_id' => null,
                        'sender_id' => auth()->id(),
                        'title' => $data['title'],
                        'message' => $data['message'],
                        'sender' => Notification::$AdminSender,
                        'type' => 'single',
                        'created_at' => time()
                    ]);

                    if (!empty($user->email) and env('APP_ENV') == 'production') {
                        \Mail::to($user->email)->send(new SendNotifications(['title' => $data['title'], 'message' => $data['message']]));
                    }
                }
            }

            $toastData = [
                'title' => trans('public.request_success'),
                'msg' => trans('update.the_notification_was_successfully_sent_to_n_students', ['count' => count($webinar->sales)]),
                'status' => 'success'
            ];

            return redirect("/admin/webinars/{$webinar->id}/students")->with(['toast' => $toastData]);
        }

        abort(404);
    }

    public function orderItems(Request $request)
    {
        $this->authorize('admin_webinars_edit');
        $data = $request->all();

        $validator = Validator::make($data, [
            'items' => 'required',
            'table' => 'required',
        ]);

        if ($validator->fails()) {
            return response([
                'code' => 422,
                'errors' => $validator->errors(),
            ], 422);
        }

        $tableName = $data['table'];
        $itemIds = explode(',', $data['items']);

        if (!is_array($itemIds) and !empty($itemIds)) {
            $itemIds = [$itemIds];
        }

        if (!empty($itemIds) and is_array($itemIds) and count($itemIds)) {
            switch ($tableName) {
                case 'tickets':
                    foreach ($itemIds as $order => $id) {
                        Ticket::where('id', $id)
                            ->update(['order' => ($order + 1)]);
                    }
                    break;
                case 'sessions':
                    foreach ($itemIds as $order => $id) {
                        Session::where('id', $id)
                            ->update(['order' => ($order + 1)]);
                    }
                    break;
                case 'files':
                    foreach ($itemIds as $order => $id) {
                        File::where('id', $id)
                            ->update(['order' => ($order + 1)]);
                    }
                    break;
                case 'text_lessons':
                    foreach ($itemIds as $order => $id) {
                        TextLesson::where('id', $id)
                            ->update(['order' => ($order + 1)]);
                    }
                    break;
                case 'webinar_chapters':
                    foreach ($itemIds as $order => $id) {
                        WebinarChapter::where('id', $id)
                            ->update(['order' => ($order + 1)]);
                    }
                    break;
                case 'webinar_chapter_items':
                    foreach ($itemIds as $order => $id) {
                        WebinarChapterItem::where('id', $id)
                            ->update(['order' => ($order + 1)]);
                    }
                case 'bundle_webinars':
                    foreach ($itemIds as $order => $id) {
                        BundleWebinar::where('id', $id)
                            ->update(['order' => ($order + 1)]);
                    }
                    break;
            }
        }

        return response()->json([
            'title' => trans('public.request_success'),
            'msg' => trans('update.items_sorted_successful')
        ]);
    }


    public function getContentItemByLocale(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        $data = $request->all();

        $validator = Validator::make($data, [
            'item_id' => 'required',
            'locale' => 'required',
            'relation' => 'required',
        ]);

        if ($validator->fails()) {
            return response([
                'code' => 422,
                'errors' => $validator->errors(),
            ], 422);
        }

        $webinar = Webinar::where('id', $id)->first();

        if (!empty($webinar)) {

            $itemId = $data['item_id'];
            $locale = $data['locale'];
            $relation = $data['relation'];

            if (!empty($webinar->$relation)) {
                $item = $webinar->$relation->where('id', $itemId)->first();

                if (!empty($item)) {
                    foreach ($item->translatedAttributes as $attribute) {
                        try {
                            $item->$attribute = $item->translate(mb_strtolower($locale))->$attribute;
                        } catch (\Exception $e) {
                            $item->$attribute = null;
                        }
                    }

                    return response()->json([
                        'item' => $item
                    ], 200);
                }
            }
        }

        abort(403);
    }
    
     public function store_features(Request $request){
         
     }
     
      public function store_items(Request $request){
        \Log::info('WebinarController store_items - Start', [
            'all_data' => $request->all(),
        ]);

        try {
            $this->authorize('admin_webinars_edit');
            \Log::info('WebinarController store_items - Authorization passed');

            $this->validate($request, [
                'description' => 'required',
                'image' => 'nullable',
                'webinar_id' => 'required',
            ]);
            \Log::info('WebinarController store_items - Validation passed');

            $data = $request->all();

            $creator = null;

            if (!empty($data['webinar_id'])) {
                $webinar = Webinar::findOrFail($data['webinar_id']);
                \Log::info('WebinarController store_items - Webinar found', ['webinar_id' => $webinar->id]);

                $creator = $webinar->creator;
                \Log::info('WebinarController store_items - Creator found', ['creator_id' => $creator->id ?? 'null']);
            } else if (!empty($data['bundle_id'])) {
                $bundle = Bundle::findOrFail($data['bundle_id']);
                \Log::info('WebinarController store_items - Bundle found', ['bundle_id' => $bundle->id]);

                $creator = $bundle->creator;
            }

            // Check if background_color column exists
            $hasBackgroundColor = false;
            try {
                $columns = DB::select("SHOW COLUMNS FROM webinar_for_items WHERE Field = 'background_color'");
                $hasBackgroundColor = !empty($columns);
            } catch (\Exception $e) {
                \Log::warning('WebinarController store_items - Could not check for background_color column', [
                    'error' => $e->getMessage()
                ]);
            }

            // Insert directly using PDO to get the ID
            $insertData = [
                'webinar_id' => !empty($data['webinar_id']) ? intval($data['webinar_id']) : null,
                'bundle_id' => !empty($data['bundle_id']) ? intval($data['bundle_id']) : null,
                'image' => !empty($data['image']) ? $data['image'] : null,
                'created_at' => now(),
                'updated_at' => now(),
            ];

            if ($hasBackgroundColor && !empty($data['background_color'])) {
                $insertData['background_color'] = $data['background_color'];
            }
            
            \Log::info('WebinarController store_items - Step 2: Before insert', [
                'insertData' => $insertData,
                'hasBackgroundColor' => $hasBackgroundColor,
            ]);
            
            // Use PDO directly to ensure we get the ID
            $pdo = DB::connection()->getPdo();
            
            if ($hasBackgroundColor) {
                $stmt = $pdo->prepare("INSERT INTO webinar_for_items (webinar_id, bundle_id, image, background_color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $insertData['webinar_id'],
                    $insertData['bundle_id'],
                    $insertData['image'],
                    $insertData['background_color'] ?? null,
                    $insertData['created_at'],
                    $insertData['updated_at'],
                ]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO webinar_for_items (webinar_id, bundle_id, image, created_at, updated_at) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([
                    $insertData['webinar_id'],
                    $insertData['bundle_id'],
                    $insertData['image'],
                    $insertData['created_at'],
                    $insertData['updated_at'],
                ]);
            }
            
            $id = $pdo->lastInsertId();
            
            \Log::info('WebinarController store_items - Step 3: After insert', [
                'id' => $id,
            ]);
            
            if ($id > 0) {
                // Load the model with the correct ID
                $faq = WebinarForItem::find($id);
                
                \Log::info('WebinarController store_items - Step 4: Model loaded', [
                    'id' => $faq->id,
                    'webinar_id' => $faq->webinar_id,
                ]);

                \Log::info('WebinarController store_items - Step 5: Creating translation', [
                    'webinar_for_item_id' => $id,
                    'locale' => mb_strtolower($data['locale']),
                    'description' => $data['description'],
                ]);

                WebinarForItemTranslation::updateOrCreate([
                    'webinar_for_item_id' => $id,
                    'locale' => mb_strtolower($data['locale']),
                ], [
                    'description' => $data['description'],
                ]);

                \Log::info('WebinarController store_items - Step 6: Translation created');
            } else {
                \Log::error('WebinarController store_items - Failed to insert', [
                    'id' => $id,
                ]);
                throw new \Exception('Failed to insert WebinarForItem - ID is ' . $id);
            }

            \Log::info('WebinarController store_items - Success');
            
            return response()->json([
                'code' => 200,
                'title' => 'نجح',
                'text' => 'تم الحفظ بنجاح',
            ], 200);

        } catch (\Illuminate\Validation\ValidationException $e) {
            \Log::error('WebinarController store_items - Validation failed', [
                'errors' => $e->errors(),
            ]);
            
            return response()->json([
                'code' => 422,
                'title' => 'خطأ في التحقق',
                'text' => 'يرجى التحقق من البيانات المدخلة',
                'errors' => $e->errors(),
            ], 422);

        } catch (\Exception $e) {
            \Log::error('WebinarController store_items - Exception', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            
            return response()->json([
                'code' => 500,
                'title' => 'خطأ',
                'text' => 'حدث خطأ أثناء الحفظ: ' . $e->getMessage(),
            ], 500);
        }
     }

    private function buildWebinarAttributes(array $data, bool $isCreate): array
    {
        $attributes = [
            'type' => $data['type'],
            'slug' => $data['slug'],
            'teacher_id' => $data['teacher_id'],
            'creator_id' => $data['teacher_id'],
            'thumbnail' => $data['thumbnail'],
            'image_cover' => $data['image_cover'],
            'video_demo' => $data['video_demo'] ?? null,
            'video_demo_source' => !empty($data['video_demo']) ? ($data['video_demo_source'] ?? null) : null,
            'capacity' => $data['capacity'] ?? null,
            'start_date' => !empty($data['start_date']) ? $data['start_date'] : null,
            'timezone' => $data['timezone'] ?? null,
            'duration' => $data['duration'] ?? null,
            'support' => !empty($data['support']),
            'certificate' => !empty($data['certificate']),
            'downloadable' => !empty($data['downloadable']),
            'partner_instructor' => !empty($data['partner_instructor']),
            'subscribe' => !empty($data['subscribe']),
            'forum' => !empty($data['forum']),
            'access_days' => $data['access_days'] ?? null,
            'price' => $data['price'] ?? null,
            'points' => $data['points'] ?? null,
            'category_id' => $data['category_id'],
            'message_for_reviewer' => $data['message_for_reviewer'] ?? null,
            'updated_at' => time(),
        ];

        if ($isCreate) {
            $attributes['status'] = Webinar::$pending;
            $attributes['created_at'] = time();
        }

        $attributes = array_merge($attributes, $this->webinarCustomFields($data));

        return $attributes;
    }

    private function webinarCustomFields(array $data): array
    {
        $fields = [];

        if (Schema::hasColumn('webinars', 'certified_from')) {
            $fields['certified_from'] = $data['certified_from'] ?? null;
        }

        if (Schema::hasColumn('webinars', 'age_level')) {
            $fields['age_level'] = $data['age_level'] ?? null;
        }

        if (Schema::hasColumn('webinars', 'order_show')) {
            $fields['order_show'] = $data['order_show'] ?? null;
        }

        if (Schema::hasColumn('webinars', 'currency')) {
            $fields['currency'] = \App\Support\PaymentCurrency::normalize(
                $data['currency'] ?? null,
                \App\Support\PaymentCurrency::defaultItemCurrency()
            );
        }

        return $fields;
    }

    private function saveWebinarTranslation(Webinar $webinar, array $data): void
    {
        if (empty($webinar->id)) {
            throw new \RuntimeException('Cannot save webinar translation without a valid webinar id.');
        }

        $locale = mb_strtolower($data['locale'] ?? getDefaultLocale());

        $translationData = [
            'title' => $data['title'],
            'description' => $data['description'],
            'seo_description' => $data['seo_description'] ?? null,
        ];

        if (Schema::hasColumn('webinar_translations', 'description_2')) {
            $translationData['description_2'] = $data['description_2'] ?? null;
        }

        WebinarTranslation::updateOrCreate([
            'webinar_id' => $webinar->id,
            'locale' => $locale,
        ], $translationData);
    }
     
}
