<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Session;
use App\Models\TextLesson;
use App\Models\File;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminLectureController extends Controller
{
    /**
     * Show the students assignment page for a lecture
     * 
     * @param int $id Lecture ID
     * @param string|null $type Lecture type (session, text_lesson, file) - will auto-detect if not provided
     * @return \Illuminate\View\View
     */
    public function showStudentsPage($id, $type = null)
    {
        $this->authorize('admin_webinars_edit');

        // Auto-detect lecture type if not provided
        if (!$type) {
            $session = Session::find($id);
            if ($session) {
                $type = 'session';
                $lecture = $session;
            } else {
                $textLesson = TextLesson::find($id);
                if ($textLesson) {
                    $type = 'text_lesson';
                    $lecture = $textLesson;
                } else {
                    $file = File::find($id);
                    if ($file) {
                        $type = 'file';
                        $lecture = $file;
                    } else {
                        abort(404, 'Lecture not found');
                    }
                }
            }
        } else {
            // Load lecture based on type
            switch ($type) {
                case 'session':
                    $lecture = Session::findOrFail($id);
                    break;
                case 'text_lesson':
                    $lecture = TextLesson::findOrFail($id);
                    break;
                case 'file':
                    $lecture = File::findOrFail($id);
                    break;
                default:
                    abort(404, 'Invalid lecture type');
            }
        }

        // Get assigned users
        $assignedUsers = DB::table('lecture_user')
            ->where('lecture_id', $id)
            ->where('lecture_type', $type)
            ->join('users', 'lecture_user.user_id', '=', 'users.id')
            ->select('users.id', 'users.full_name', 'users.email', 'users.role_name', 'lecture_user.created_at')
            ->orderBy('users.full_name')
            ->get();

        // Get all users for dropdown
        $allUsers = User::select('id', 'full_name', 'email', 'role_name')
            ->where('status', 'active')
            ->orderBy('full_name')
            ->get();

        $data = [
            'pageTitle' => 'Manage Lecture Students',
            'lecture' => $lecture,
            'lectureType' => $type,
            'assignedUsers' => $assignedUsers,
            'allUsers' => $allUsers,
        ];

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

    /**
     * Assign a student to a lecture
     * 
     * @param Request $request
     * @param int $id Lecture ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function assignStudent(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        $request->validate([
            'user_id' => 'required|exists:users,id',
            'lecture_type' => 'required|in:session,text_lesson,file',
        ]);

        $userId = $request->input('user_id');
        $lectureType = $request->input('lecture_type');

        // Verify lecture exists
        $lecture = $this->getLecture($id, $lectureType);
        if (!$lecture) {
            return response()->json([
                'code' => 404,
                'msg' => 'Lecture not found'
            ], 404);
        }

        // Check if already assigned (prevent duplication)
        $exists = DB::table('lecture_user')
            ->where('lecture_id', $id)
            ->where('user_id', $userId)
            ->where('lecture_type', $lectureType)
            ->exists();

        if ($exists) {
            return response()->json([
                'code' => 422,
                'msg' => 'User is already assigned to this lecture'
            ], 422);
        }

        // Assign user using syncWithoutDetaching to avoid duplication
        // Insert directly into pivot table with lecture_type
        DB::table('lecture_user')->insert([
            'lecture_id' => $id,
            'user_id' => $userId,
            'lecture_type' => $lectureType,
            'created_at' => time(),
            'updated_at' => time(),
        ]);

        $user = User::find($userId);

        return response()->json([
            'code' => 200,
            'msg' => 'Student assigned successfully',
            'user' => [
                'id' => $user->id,
                'full_name' => $user->full_name,
                'email' => $user->email,
            ]
        ]);
    }

    /**
     * Remove a student from a lecture
     * 
     * @param int $id Lecture ID
     * @param int $userId User ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeStudent($id, $userId)
    {
        $this->authorize('admin_webinars_edit');

        // Auto-detect lecture type
        $type = $this->detectLectureType($id);

        // Get lecture
        $lecture = $this->getLecture($id, $type);
        if (!$lecture) {
            return response()->json([
                'code' => 404,
                'msg' => 'Lecture not found'
            ], 404);
        }

        // Remove user from pivot table
        DB::table('lecture_user')
            ->where('lecture_id', $id)
            ->where('user_id', $userId)
            ->where('lecture_type', $type)
            ->delete();

        return response()->json([
            'code' => 200,
            'msg' => 'Student removed successfully'
        ]);
    }

    /**
     * Get lecture instance based on type
     */
    private function getLecture($id, $type)
    {
        switch ($type) {
            case 'session':
                return Session::find($id);
            case 'text_lesson':
                return TextLesson::find($id);
            case 'file':
                return File::find($id);
            default:
                return null;
        }
    }

    /**
     * Auto-detect lecture type from ID
     */
    private function detectLectureType($id)
    {
        if (Session::find($id)) {
            return 'session';
        }
        if (TextLesson::find($id)) {
            return 'text_lesson';
        }
        if (File::find($id)) {
            return 'file';
        }
        return 'session'; // default
    }
}

