<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;
use Exception;


class AuthController extends Controller
{
    public function register(Request $request)
    {
         try {
            $validated = $request->validate([
                'name'             => 'required|string|max:255',
                'email'            => 'required|string|email|max:255|unique:users',
                'password'         => 'required|string|min:6|confirmed',
                'phone'            => 'nullable|string|max:20',
                'profile_picture'  => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
                'role'             => 'in:admin,user'
            ]);
            $uploadPath = public_path('uploads');

            if (!file_exists($uploadPath)) {
                mkdir($uploadPath, 0755, true);
            }
            if ($request->hasFile('profile_picture')) {
                $image = $request->file('profile_picture');
                $imageName = time() . '.' . $image->getClientOriginalExtension();
                $image->move($uploadPath, $imageName);
            }
            $role = $request->role ?? 'user';
            $user = User::create([
                'name'            => $request->name,
                'email'           => $request->email,
                'password'        => bcrypt($request->password),
                'phone'           => $request->phone,
                'profile_picture' => $imageName ?? "",
                'role'            => $role,
            ]);
    
           
    
            return response()->json([
                'status' => 'success',
                'user_id' => $user->id,                
                'message' => 'User Successfully Register...',
            ], 201);
    
         } catch (ValidationException $e) {
            return response()->json([
                'message' => 'Validation failed',
                'errors'  => $e->errors(),
            ], 422);
         } catch (Exception $e) {
            Log::error('Register Error: ' . $e->getMessage());
    
            return response()->json([
                'message' => 'An unexpected error occurred. Please try again later.',
            ], 500);
         }
    }

    public function login(Request $request)
    {
        $request->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'token_type'   => 'Bearer',
            'user'         => $user,
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();

        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }

    public function profile(Request $request)
    {
        $user = $request->user();
        if ($user->role === 'admin') {
            $users = User::all()->map(function ($u) {
                return [
                    'id'                  => $u->id,
                    'name'                => $u->name,
                    'email'               => $u->email,
                    'phone'               => $u->phone,
                    'role'                => $u->role,
                    'profile_picture'     => $u->profile_picture,
                    'profile_picture_url' => $u->profile_picture ? url($u->profile_picture) : null,
                    'created_at'          => $u->created_at,
                ];
            });

            return response()->json(['users' => $users], 200);
        }

        // If normal user, return only their profile
        return response()->json([
            'user' => [
                'id'                  => $user->id,
                'name'                => $user->name,
                'email'               => $user->email,
                'phone'               => $user->phone,
                'role'                => $user->role,
                'profile_picture'     => $user->profile_picture,
                'profile_picture_url' => $user->profile_picture ? url($user->profile_picture) : null,
                'created_at'          => $user->created_at,
            ]
        ], 200);
    }

    public function editProfile(Request $request)
    {

        $Authuser = $request->user();
        if (!$Authuser) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        //dd($Authuser->id);

        $user = User::find($Authuser->id);
        $validator = Validator::make($request->all(), [
            'name'            => 'sometimes|string|max:255',
            'email'           => 'sometimes|email|unique:users,email,' . $Authuser->id,
            'phone'           => 'sometimes|string|max:20',
            'profile_picture' => 'sometimes|image|mimes:jpg,jpeg,png|max:2048',
            'password'        => 'sometimes|string|min:6|confirmed', // also needs password_confirmation
        ]);

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

        // Optional field updates
        if ($request->filled('name')) $user->name = $request->name;
        if ($request->filled('email')) $user->email = $request->email;
        if ($request->filled('phone')) $user->phone = $request->phone;

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

        if ($request->hasFile('profile_picture')) {
            $uploadPath = public_path('uploads');
            if (!file_exists($uploadPath)) {
                mkdir($uploadPath, 0755, true);
            }

            $image     = $request->file('profile_picture');
            $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();
            $image->move($uploadPath, $imageName);
            $user->profile_picture = $imageName ?? "";
        }
        $user->save();

        return response()->json([
            'message' => 'Profile updated successfully.',
            'user'    => $user,
        ], 200);
    }
}
