<?php

namespace App\Http\Controllers\API;
use App\Http\Resources\UserResource;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Laravel\Sanctum\PersonalAccessToken;



class LoginController extends Controller
{
    public function login_post(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string',
        ]);
        if ($validator->fails()) {
            Log::error('Validation errors:', $validator->errors()->toArray());
            return response()->json([
                'status' => 'error',
                'data' => null,
                'message' => 'Validation errors',
                'code' => 422,
                'errors' => $validator->errors()
            ], 422);
        }
        $user = User::where('email', $request->email)->first();
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid email or password.',
                'code' => 401
            ], 401);
        }
        Auth::login($user);
        $token = $user->createToken('YourAppName')->plainTextToken;
        return response()->json([
            'status' => 'success',
            'data' => [
                'token' => $token,
                'user' => $user
            ],
            'message' => 'User logged in successfully!',
            'code' => 200,
        ], 200);
    }

    public function logout(Request $request)
    {

        if (!auth()->guard('sanctum')->check()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Please login!',
                'data' => [],
                'code' => 401,
            ], 401);
        }


        try {
            $user = auth()->guard('sanctum')->user();
            $token = $request->bearerToken();

            if ($token) {
                $token = PersonalAccessToken::findToken($token);
                if ($token) {
                    $token->delete();
                }
            }

            return response()->json([
                'status' => 'success',
                'message' => 'Logged out successfully.',
                'code' => 200,
            ], 200);
        } catch (\Exception $e) {

            return response()->json([
                'status' => 'error',
                'message' => 'Failed to log out. Please try again.',
                'code' => 500,
            ], 500);
        }
    }

    public function reset_password(Request $request)
    {

        $validated = $request->validate([
            'old_password'              => 'required',
            'new_password'              => 'required|min:8|confirmed',
            'new_password_confirmation' => 'required',
        ]);
        if (!auth('sanctum')->check()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Please login!',
                'data' => [],
                'code' => 401,
            ], 401);
        }
        $user = auth('sanctum')->user();
        if (!Hash::check($validated['old_password'], $user->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Old password is incorrect'
            ], 400);
        }
        $user->password = Hash::make($validated['new_password']);
        $user->save();
        return response()->json([
            'success' => true,
            'message' => 'Password has been successfully updated.'
        ]);
    }

  
    public function profile_update(Request $request)
    {
        if (!auth('sanctum')->check()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Please login!',
                'data'    => [],
                'code'    => 401,
            ], 401);
        }
    
        $user = auth('sanctum')->user();
    
        $validator = Validator::make($request->all(), [
            'name'         => 'required|string|max:255',
            'email'        => 'required|email|unique:users,email,' . $user->id,
            'phone_number' => 'required|numeric',
            // 'profile_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',   
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Validation errors occurred.',
                'data'    => $validator->errors(),
                'code'    => 422,
            ], 422);
        }
    
        $user->name         = $request->input('name');
        $user->email        = $request->input('email');
        $user->phone_number = $request->input('phone_number');
    
        if ($request->hasFile('profile_image')) {
            $fileName        = time() . '_' . $request->file('profile_image')->getClientOriginalName();
            $destinationPath = public_path('assets/images/profile');
            $request->file('profile_image')->move($destinationPath, $fileName);
            $imagePath = 'assets/images/profile/' . $fileName;
    
            // Delete the old profile image if it exists
            if ($user->profile_image && file_exists(public_path($user->profile_image))) {
                unlink(public_path($user->profile_image));
            }
            $user->profile_image = $imagePath;
        }
    
        $user->save();
    
        return response()->json([
            'status' => 'success',
            'data' => new UserResource($user), // Return the updated user data
            'message' => 'Profile updated successfully.',
            'code' => 200,
        ], 200);
    }
    
}



