<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\TradingYear;
use App\Models\ProfileSetting;
use App\Models\ProfileAddress;
use App\Models\PercentageAdjustment;
use App\Models\IdDocument;
use Carbon\Carbon;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Illuminate\Support\Facades\DB;


class SocialiteController extends Controller
{
    public function googleLogin()
    {
        return Socialite::driver('google')->redirect();
    }

    public function googleAuthentication(Request $request)
    {
        try {
            // If your frontend sends access_token
            $googleUser = Socialite::driver('google')->stateless()
                ->userFromToken($request->input('access_token'));

            // Check if user exists
            $user = User::where('google_id', $googleUser->id)->first();

            if ($user) {
                // Login existing user
                $token = $user->createToken(config('app.name'))->plainTextToken;

                return response()->json([
                    'success' => true,
                    'message' => 'Authenticated successfully',
                    'user'    => $user,
                    'token'   => $token,
                ]);
            } else {
                DB::beginTransaction();

                // Split Google full name
                $names = explode(' ', $googleUser->name, 2);

                $user = User::create([
                    'affiliate_id'  => $request->input('affiliate_id') ?? null,
                    'standing_id'   => $this->get_standing_id(),
                    'user_type'     => 'personal',
                    'first_name'    => $names[0] ?? '',
                    'last_name'     => $names[1] ?? '',
                    'email'         => $googleUser->email,
                    'google_id'     => $googleUser->id,
                    'password'      => Hash::make(uniqid()), // random password
                    'account_status'=> 1,
                ]);

                // Trading year
                $year_start = now();
                $year_end   = now()->subYear();
                $trading_Year = $year_start->year . '-' . $year_end->year;

                $tradingYear = TradingYear::create([
                    'user_id'               => $user->id,
                    'tradingYear'           => $trading_Year,
                    'tradingyear_startdate' => $year_start->toDateString(),
                    'tradingyear_enddate'   => $year_end->toDateString(),
                    'trading_status'        => 1,
                    'active_trading_year'   => 1,
                    'finalise_year'         => 0,
                ]);

                DB::commit();

                // Token
                $token = $user->createToken(config('app.name'))->plainTextToken;

                return response()->json([
                    'success' => true,
                    'message' => 'Registration successful',
                    'user'    => $user,
                    'token'   => $token,
                ]);
            }
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'success' => false,
                'message' => 'Google authentication failed',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }


}
