<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
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\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Illuminate\Support\Facades\DB;



class UserAuthController extends Controller
{

    public function register(Request $request)
    {
     // dd(env('MAIL_HOST'));

        // Validate the request data
        $validator = Validator::make($request->all(), [
            'year_start' => 'required|date',
            'user_type' => 'required|string',
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8',
        ], [
            'year_start.required' => 'Please specify trading year.',
            'user_type.required' => 'Please specify account type.',
            'first_name.required' => 'First name is required.',
            'last_name.required' => 'Last name is required.',
            'email.required' => 'Please specify your email.',
            'password.required' => 'Please choose a strong password.',
        ]);

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

        // Begin the transaction
        DB::beginTransaction();

        try {
            // Create the user
            $user = User::create([
                'affiliate_id' => $request->input('affiliate_id') ?? null,
                'standing_id' => $this->get_standing_id(),
                'user_type' => $request->input('user_type'),
                'first_name' => $request->input('first_name'),
                'last_name' => $request->input('last_name'),
                'business_name' => $request->input('business_name'),
                'email' => $request->input('email'),
                'password' => Hash::make($request->input('password')),
                'account_status' => '1'
            ]);

            // Create the trading year
            $year_start = Carbon::parse($request->input('year_start'));
            $year_end = Carbon::parse($request->input('year_end'));
            $trading_Year = $year_start->year . '-' . $year_end->year;

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


            // Add tradingYear to user object
            $user->tradingYear = $tradingYear;

            // Create profile settings, address, and other related data
            // $this->createUserProfile($user->id);

            // Commit the transaction
            DB::commit();

            $send = $this->sendRegistrationEmail($user);

            if ($send) {
                return response()->json([
                    'success' => true,
                    'message' => 'Registration successful'
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Registration successful, but email could not be sent.'
                ], 200);
            }


        } catch (\Exception $e) {
            // Rollback the transaction
            DB::rollback();

            return response()->json([
                'success' => false,
                'message' => 'Registration failed. Please try again.',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    private function createUserProfile($userId)
    {
        ProfileSetting::create([
            'user_id' => $userId,
            'profile_image'  => '',
            'date_of_birth'  => null,
            'contact_no'  => '',
            'your_role'  => '',
            'badge_no'  => '',
            'taxi_company'  => '',
            'local_council'  => '',
        ]);

        ProfileAddress::create([
            'user_id' => $userId,
            'address_line1' => '',
            'address_line2' => '',
            'address_line3' => '',
            'county' => '',
            'post_code' => '',
            'town_city' => '',
        ]);

        PercentageAdjustment::create([
            'user_id' => $userId,
            'private_use_adj_car'       =>  '0',
            'override_mileage'          =>  '0',
            'private_use_adj_phone'     =>  '0',
            'got_another_job'           =>  '0',
            'radio_rent_cash'           =>  '0',
            'radio_rent_card_bank'      =>  '0',
            'radio_rent_acc_contract'   =>  '0',
            'radio_rent_sub_contract'   =>  '0'
        ]);

        // IdDocument::create([
        //     'user_id' => $userId,
        //     'file_type' => ' ',
        //     'file_name' => ' ',
        //     'verified' => ' ',
        // ]);
    }

 


    private function sendRegistrationEmail($user)
    {
        \Log::info("📧 Starting sendRegistrationEmail for user: {$user->email}");

        $mail = new PHPMailer(true);

        try {
            \Log::info("Configuring PHPMailer...");

            // Use SMTP instead of mail()
            $mail->isSMTP();
            
            $mail->Host       = env('MAIL_HOST'); // Change to your provider
            $mail->SMTPAuth   = true;
            $mail->Username   = env('MAIL_USERNAME');
            $mail->Password   = env('MAIL_PASSWORD');
            
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = 465;
            $mail->CharSet = 'UTF-8'; 


            \Log::info("SMTP Config set", [
                'host' => $mail->Host,
                'port' => $mail->Port,
                'username' => $mail->Username,
            ]);

            // Format the dates
            $startDate = Carbon::parse($user->tradingYear->tradingyear_startdate)->format('Y-m-d');
            $endDate   = Carbon::parse($user->tradingYear->tradingyear_enddate)->format('Y-m-d');

            \Log::info("Dates formatted", [
                'startDate' => $startDate,
                'endDate'   => $endDate,
            ]);

            // Recipients
            $mail->setFrom(config('mail.from.address'), 'Taxita');
            $mail->addAddress($user->email);
            $mail->addCC('ansar131@hotmail.com');

            \Log::info("Recipients added", [
                'to' => $user->email,
                'cc' => 'ansar131@hotmail.com'
            ]);

            // Content
            $mail->isHTML(true);
            $mail->Subject = 'Welcome to Taxita - Your Registration is Complete!';

            $mail->Body = "
            <html>
                <head>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            color: #333;
                            line-height: 1.6;
                        }
                        .header, .footer {
                            background-color: #e0e0e0;
                            color: #ffffff;
                            padding: 20px;
                            text-align: center;
                        }
                        .header img {
                            max-width: 150px;
                            margin-bottom: 10px;
                        }
                        .content {
                            padding: 20px;
                            background-color: #f9f9f9;
                            border: 1px solid #dddddd;
                            margin: 20px auto;
                            max-width: 600px;
                            border-radius: 10px;
                        }
                        h1, h2 {
                            color: #004080;
                        }
                        ul {
                            list-style-type: none;
                            padding: 0;
                        }
                        ul li {
                            margin-bottom: 10px;
                        }
                        a {
                            color: #004080;
                            text-decoration: none;
                        }
                        a:hover {
                            text-decoration: underline;
                        }
                        .footer p {
                            margin: 5px 0;
                        }
                    </style>
                </head>
                <body>
                    <div class='header'>
                        <img src='https://taxita.co.uk/wp-content/uploads/2022/11/taxita-logo-with-circle.png' alt='Taxita Logo'>
                        <h1>Welcome to Taxita!</h1>
                    </div>
                    <div class='content'>
                        <p>Dear " . $user->first_name . ",</p>
                        <p>We are excited to inform you that your registration has been successfully completed. Below are the details of your trading year and profile information:</p>
                        <h2>Trading Year:</h2>
                        <ul>
                            <li><strong>Start Date:</strong> " . $startDate . "</li>
                            <li><strong>End Date:</strong> " . $endDate . "</li>
                        </ul>
                        <h2>Profile Information:</h2>
                        <p><strong>Profile ID:</strong> " . $user->standing_id . "</p>
                        <p>Please make sure to quote your Profile ID for any future communications with us.</p>
                        <h2>Important Note:</h2>
                        <p>Please note that registering for a free plan account does not grant access to the rolling profit & loss section. For more details, kindly review our <a href='https://taxita.co.uk/terms-and-conditions'>Terms & Conditions</a> and <a href='https://taxita.co.uk/privacy-policy'>Privacy Policy</a>.</p>
                        <p>If you have any questions or need further assistance, feel free to reach out to us.</p>
                        <p>Thank you for choosing Taxita!</p>
                        <p>Best regards,<br>
                        The Taxita Team</p>
                    </div>
                    <div class='footer'>
                        <p><strong>Web:</strong> <a href='https://www.taxita.co.uk' style='color: #ffffff;'>www.taxita.co.uk</a></p>
                        <p><strong>Web App:</strong> <a href='https://www.taxita.co.uk/app/' style='color: #ffffff;'>www.taxita.co.uk/app/</a></p>
                    </div>
                </body>
            </html>";

            \Log::info("Email body & subject set");

            // Send
            try{
                
                // $send = $mail->send();

                return $mail->send();
                if ($send) {
                    \Log::info("✅ Email sent successfully to {$user->email}");
                    return response()->json([
                        'success' => true,
                        'message' => 'Registration successfully.'
                    ], 200);
                } else {
                    \Log::warning("⚠️ PHPMailer send() returned false for {$user->email}");
                    return response()->json([
                        'success' => false,
                        'message' => 'Failed to send registration email.'
                    ], 200);
                }
            } catch (Exception $e) {
                \Log::error("❌ PHPMailer exception", ['error' => $e->getMessage()]);
                return response()->json([
                    'success' => false,
                    'message' => 'Unable to send registration email.',
                    'error'   => $e->getMessage()
                ], 200);
            }

        } catch (Exception $e) {
            \Log::error("PHPMailer exception", ['error' => $e->getMessage()]);
            return response()->json([
                'status'  => false,
                'message' => 'Unable to send registration email',
                'error'   => $e->getMessage()
            ], 200);
        }
    }




    public function verify_affiliate_id() {}

    public function get_standing_id()
    {
        $maxValue = User::orderBy('id', 'desc')->value('standing_id');

        if ($maxValue > 0) {
            $standing_id = $maxValue + 1;
        } else {
            $standing_id = 100001;
        }

        return $standing_id;
    }


    public function login(Request $request)
    {
        // Wrap the code in a try-catch block to handle any unexpected errors.
        try {
            // Use Validator class for better control over validation
            $validator = Validator::make($request->all(), [
                'email' => 'required|email|max:255',
                'password' => 'required|string|min:6',
            ]);

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

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

            // Check if user exists
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'No account exists with this email address.',
                    'user' => null,
                ], 404);
            }

            // Check if the password matches
            if (!Hash::check($request->password, $user->password)) {
                return response()->json([
                    'success' => false,
                    'message' => 'The specified password is wrong.',
                    'user' => null,
                ], 401);
            }

            // Check if the account is active
            if (!$user->account_status) {
                return response()->json([
                    'success' => false,
                    'message' => 'Your account is not active, please contact the administrator.',
                    'user' => null,
                ], 403);
            }

            // Generate an API token for the user
            $user->token = $user->createToken(config('app.name'))->plainTextToken;

            // Prepare the response data
            $responseData = [
                'id' => $user->id,
                'standing_id' => $user->standing_id,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'affiliate_id' => $user->affiliate_id,
                'user_type' => $user->user_type,
                'email' => $user->email,
                'current_trading_year_id' => $user->current_trading_year_id,
                'current_trading_year' => $user->current_trading_year,
                'token' => $user->token,
            ];

            // Return success response with the user data
            return response()->json([
                'success' => true,
                'message' => 'Authenticated successfully, loading dashboard...',
                'userAuth' => $user->current_trading_year_id, // Added for further use
                'user' => $responseData,
            ], 200);
        } catch (\Exception $e) {
            // Catch and handle any unexpected exceptions
            return response()->json([
                'success' => false,
                'message' => 'An error occurred during login. Please try again later.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function profile(Request $request)
    {
        if ($request->user()) {
            return response()->json([
                'message' => 'Profile Data',
                'data' => $request->user()
            ], 200);
        } else {
            return response()->json([
                "message" => 'Not Authenticated'
            ], 401);
        }
    }

    public function logout(Request $request)
    {
        $user = User::where('id', $request->user()->id)->first();


        if ($user) {
            $user->tokens()->delete();
            return response()->json([
                'message' => 'Logged Out succesfully',

            ]);
        } else {
            return response()->json([
                "message" => 'User Not Found!'
            ], 404);
        }
    }
}