<?php

namespace App\Http\Controllers\Api\Student;

use App\Http\Controllers\Controller;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:student', ['except' => ['login', 'register']]);
    }

    /**
     * Register a new student
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'admission_number' => 'required|string|unique:students,admission_number',
            'email' => 'required|email|unique:students,email',
            'password' => 'required|string|min:8|confirmed',
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'phone' => 'nullable|string',
            'class_id' => 'nullable|exists:classes,id',
            'section_id' => 'nullable|exists:sections,id',
        ]);

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

        $student = Student::create([
            'admission_number' => $request->admission_number,
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'class_id' => $request->class_id,
            'section_id' => $request->section_id,
            'is_active' => true,
        ]);

        $token = JWTAuth::fromUser($student);

        return response()->json([
            'success' => true,
            'message' => 'Student registered successfully',
            'data' => [
                'student' => $student,
                'token' => $token,
                'token_type' => 'Bearer',
                'expires_in' => auth('student')->factory()->getTTL() * 60
            ],
        ], 201);
    }

    /**
     * Login student
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

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

        $credentials = $request->only('email', 'password');

        try {
            if (!$token = auth('student')->attempt($credentials)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid credentials',
                ], 401);
            }

            $student = auth('student')->user();

            if (!$student->is_active) {
                auth('student')->logout();
                return response()->json([
                    'success' => false,
                    'message' => 'Your account is inactive. Please contact administrator.',
                ], 403);
            }

            return response()->json([
                'success' => true,
                'message' => 'Login successful',
                'data' => [
                    'student' => $student->load(['class', 'section', 'parents']),
                    'token' => $token,
                    'token_type' => 'Bearer',
                    'expires_in' => auth('student')->factory()->getTTL() * 60
                ],
            ]);
        } catch (JWTException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Could not create token',
            ], 500);
        }
    }

    /**
     * Get authenticated student profile
     */
    public function profile()
    {
        try {
            $student = auth('student')->user();

            return response()->json([
                'success' => true,
                'data' => $student->load(['class', 'section', 'parents']),
            ]);
        } catch (JWTException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Student not found',
            ], 404);
        }
    }

    /**
     * Update student profile
     */
    public function updateProfile(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'sometimes|string',
            'address' => 'sometimes|string',
            'city' => 'sometimes|string',
        ]);

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

        $student = auth('student')->user();
        $student->update($request->only(['phone', 'address', 'city']));

        return response()->json([
            'success' => true,
            'message' => 'Profile updated successfully',
            'data' => $student,
        ]);
    }

    /**
     * Change password
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:8|confirmed',
        ]);

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

        $student = auth('student')->user();

        if (!Hash::check($request->current_password, $student->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Current password is incorrect',
            ], 400);
        }

        $student->update([
            'password' => Hash::make($request->new_password),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Password changed successfully',
        ]);
    }

    /**
     * Refresh JWT token
     */
    public function refresh()
    {
        try {
            $token = auth('student')->refresh();

            return response()->json([
                'success' => true,
                'token' => $token,
                'token_type' => 'Bearer',
                'expires_in' => auth('student')->factory()->getTTL() * 60
            ]);
        } catch (JWTException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Could not refresh token',
            ], 500);
        }
    }

    /**
     * Logout student
     */
    public function logout()
    {
        try {
            auth('student')->logout();

            return response()->json([
                'success' => true,
                'message' => 'Logged out successfully',
            ]);
        } catch (JWTException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Could not logout',
            ], 500);
        }
    }
}
