<?php

namespace App\Http\Controllers;

use App\Mail\SupportMessage;
use App\Mail\TeacherRequestMessage;
use App\Models\User;
use App\Models\Note;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use App\Models\Course;

class UserController extends Controller {

    public function getUserGeneralInfo() {
        $user = Auth::user();
        $notes = $user->notes()->orderByDesc('id')->take(3)->get(); // Últimos 3 por ID descendente
        $coursesOwned = $user->courses()
        ->wherePivotIn('status_id', [2, 3, 4, 5])
        ->with(['users' => function ($query) {
            $query->wherePivot('favorite', 1);
        }])
        ->orderByDesc('id')
        ->take(4)
        ->get();
        $popularCourses = Course::with(['users' => function ($query) {
            $query->wherePivot('favorite', 1);
        }])
        ->withCount(['users as favorites_count' => function ($query) {
            $query->where('user_courses.favorite', 1);
        }])
        ->orderByDesc('favorites_count')
        ->take(4)
        ->get();
        return view('pages.common.home', compact('notes','coursesOwned', 'popularCourses'));
    }

    /**
     * Obtiene la información del usuario autenticado
     */
    public function getMyInfo()
    {
        $user = Auth::user();
        return view('pages.common.myProfile', compact('user'));
    }

    public function getMyInfo2()
    {
        $user = Auth::user();
        return view('pages.common.settings', compact('user'));
    }

    public function myCourses()
    {
        $user = Auth::user(); // o cualquier usuario que tengas

        $courses = $user->courses()
            ->join('user_course_statuses', 'user_courses.status_id', '=', 'user_course_statuses.id') // ✅ INNER JOIN
            ->whereIn('user_courses.status_id', [2, 3, 4, 5])
            ->with(['users' => function ($query) {
                $query->wherePivot('favorite', 1);
            }])
            ->orderByDesc('courses.id')
            ->select('courses.*', 'user_courses.status_id', 'user_course_statuses.name as status_name') // ✅ añadimos nombre del estado
            ->get();

        return view('pages.student.myCourses', compact('courses'));
    }

    public function getMyNotes()
    {
        $user = Auth::user();
        $notes = $user->notes; // Asumiendo que tienes una relación notes en tu modelo User
        return view('pages.student.myNotes', compact('notes'));
    }

    public function getMyCertificates()
    {
        $user = Auth::user();
        $certificates = $user->certificates ?? collect(); // Si no hay certificados, devuelve una colección vacía
        return view('pages.student.myCertificates', compact('certificates'));
    }

    public function editMyInfo(Request $request)
    {
        $user = Auth::user();

        // Primero validamos los campos básicos
        $request->validate([
            'name' => 'required|string|max:255',
            'surname' => 'required|string|max:255',
            'username' => 'required|string|max:255|unique:users,username,' . $user->id,
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
        ]);

        // Validación personalizada para la contraseña
        if ($request->filled('password')) {
            if (empty($request->password_confirmation)) {
                return redirect()->back()->withInput()->with('error', 'Debes confirmar la contraseña');
            }

            if ($request->password !== $request->password_confirmation) {
                return redirect()->back()->withInput()->with('error', 'Las contraseñas no coinciden');
            }

            if (strlen($request->password) < 8) {
                return redirect()->back()->withInput()->with('error', 'La contraseña debe tener al menos 8 caracteres');
            }
        }

        $user->name = $request->name;
        $user->surname = $request->surname;
        $user->username = $request->username;
        $user->email = $request->email;

        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        $user->save();

        return redirect()->back()->with('success', 'Perfil actualizado correctamente');
    }

    public function deleteAccount()
    {
        $user = Auth::user();

        // Cambiar el estado a inactivo
        $user->status = 'inactive';
        $user->save();

        // Cerrar sesión
        Auth::logout();

        return redirect()->route('mainPage')->with('success', 'Tu cuenta ha sido eliminada correctamente');
    }

    public function filterCourses(Request $request)
    {
        try {
            $user   = Auth::user();
            $status = $request->input('status');

            $query = $user->courses()
                ->wherePivotIn('status_id', [2,3,4,5])              // filtro global
                ->withPivot('favorite','status_id')                 // traer pivot
                ->join('user_course_statuses',                      // para el nombre del estado
                    'user_courses.status_id',
                    '=',
                    'user_course_statuses.id')
                ->select([
                    'courses.*',
                    'user_courses.favorite',
                    'user_courses.status_id',
                    'user_course_statuses.name as status_name',
                ]);

            // filtros por estado
            if ($status === 'in_progress') {
                $query->wherePivotIn('status_id', [2,3]);
            } elseif ($status === 'completed') {
                $query->wherePivotIn('status_id', [4,5]);
            }

            // ← aquí: movemos withCount tras el select y el join,
            //     y usamos where('user_courses.favorite',1) en lugar de wherePivot
            $query->withCount([
                'users as favorites' => function($q){
                    $q->where('user_courses.favorite', 1);
                }
            ]);

            $filtered = $query
                ->orderByDesc('courses.id')
                ->get();

            return response()->json(['courses' => $filtered]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Error al filtrar los cursos: ' . $e->getMessage()
            ], 500);
        }
    }


    public function show($id) {
        $note = Note::findOrFail($id);
        return view('pages.student.note', compact('note'));
    }

    public function update(Request $request, $id) {
        $note = Note::findOrFail($id);

        // Validar datos
        $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
        ]);

        // Actualizar la nota
        $note->update([
            'title' => $request->input('title'),
            'content' => $request->input('content'),
        ]);

        // Redirigir a la página del perfil o de notas con un mensaje de éxito
        return redirect()->route('note.show', ['id' => $note->id])->with('success', 'Nota actualizada correctamente.');
    }

    public function destroy($id) {
        $note = Note::findOrFail($id);
        $note->delete();

        return redirect()->back();
    }

    public function createAndRedirect() {
        $note = new Note();
        $user = Auth::user();
        $note->title = 'Nueva nota';
        $note->content = '';
        $note->owner_id = $user->id;
        $note->save();

        return redirect()->route('note.show', ['id' => $note->id]);
    }

    public function show2()
    {
        $user = Auth::user();
        $notes = $user->notes;
        return view('pages.student.myNotes2', compact('notes'));
    }

    public function send(Request $request) {

        $request->validate([
            'message' => 'required|string|max:2000',
        ]);

        $userEmail = Auth::user()->email;
        $userName = Auth::user()->name;

        Mail::to('info.dailystudy@gmail.com')->send(new SupportMessage($userEmail, $userName, $request->message));

        return back()->with('success', 'Message sent successfully!');

    }

    public function submitTeacherRequest(Request $request) {

        $errors = [];

        if (empty($request->name)) {
            $errors['name'] = 'Name is required';
        } elseif (!preg_match('/^[a-zA-Z]+$/', $request->name)) {
            $errors['name'] = 'Name must contain letters only, without spaces';
        }

        if (empty($request->surname)) {
            $errors['surname'] = 'Surname is required';
        } elseif (!preg_match('/^[a-zA-Z\s]+$/', $request->surname)) {
            $errors['surname'] = 'Surname must contain letters only';
        }

        if (empty($request->email)) {
            $errors['email'] = 'Email is required';
        } elseif (!filter_var($request->email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Email is not valid';
        } elseif (!User::where('email', $request->email)->exists()) {
            $errors['email'] = 'Email is not registered';
        }

        if (!empty($request->linkedin)) {
            if (!preg_match('/^(https?:\/\/)?(www\.)?linkedin\.com\/.*$/', $request->linkedin)) {
                $errors['linkedin'] = 'LinkedIn URL is not valid';
            }
        }

        if (!$request->hasFile('cv')) {
            $errors['cv'] = 'CV is required';
        } elseif (!$request->file('cv')->isValid() || $request->file('cv')->getClientOriginalExtension() !== 'pdf') {
            $errors['cv'] = 'CV must be a valid PDF file';
        }

        if (!$request->hasFile('portfolio')) {
            $errors['portfolio'] = 'Portfolio is required';
        } elseif (!$request->file('portfolio')->isValid() || $request->file('portfolio')->getClientOriginalExtension() !== 'pdf') {
            $errors['portfolio'] = 'Portfolio must be a valid PDF file';
        }
    
        if (!empty($errors)) {
            return redirect()->route('teacher.request')->withInput()->withErrors($errors);
        }

        $request->validate([
            'linkedin' => 'nullable|url',
            'cv' => 'required|mimes:pdf|max:10240',
            'portfolio' => 'required|mimes:pdf|max:10240',
        ]);

        $user = Auth::user();
        Log::info('Authenticated user:', ['id' => $user->id, 'email' => $user->email]);

        // Subida de archivos
        $cvPath = $request->file('cv')->store('cv_files', 'public');
        $portfolioPath = $request->file('portfolio')->store('portfolio_files', 'public');
        Log::info('Files stored', ['cv' => $cvPath, 'portfolio' => $portfolioPath]);

        // Intentar actualizar
        $updated = $user->update([
            'change_role' => true,
            'cv' => $cvPath,
            'portfolio' => $portfolioPath,
            'linkedin' => $request->linkedin,
        ]);

        Log::info('User update result:', ['updated' => $updated]);
        Log::info('User new data:', $user->only(['change_role', 'cv', 'portfolio', 'linkedin']));

        // Enviar correo al admin
        Mail::to('info.dailystudy@gmail.com')->send(new TeacherRequestMessage($user));
        Log::info('Teacher request email sent to admin.');

        return redirect()->route('mainPage')->with('success', 'Your request has been sent successfully.');
    }

}