<?php

namespace App\Http\Controllers\Api\Parent;

use App\Http\Controllers\Controller;
use App\Models\ParentModel;
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:parent', ['except' => ['login', 'register']]);
    }

    /**
     * Register a new parent
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|unique:parents,email',
            'password' => 'required|string|min:8|confirmed',
            'phone' => 'required|string',
            'occupation' => 'nullable|string',
        ]);

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

        $parent = ParentModel::create([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'occupation' => $request->occupation,
            'is_active' => true,
        ]);

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

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

    /**
     * Login parent
     */
    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('parent')->attempt($credentials)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid credentials',
                ], 401);
            }

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

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

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

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

            return response()->json([
                'success' => true,
                'data' => $parent->load(['students']),
            ]);
        } catch (JWTException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Parent not found',
            ], 404);
        }
    }

    /**
     * Update parent profile
     */
    public function updateProfile(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'sometimes|string|max:255',
            'last_name' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string',
            'occupation' => 'sometimes|string',
            'address' => 'sometimes|string',
        ]);

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

        $parent = auth('parent')->user();
        $parent->update($request->only(['first_name', 'last_name', 'phone', 'occupation', 'address']));

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

    /**
     * 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);
        }

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

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

        $parent->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('parent')->refresh();

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

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

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