<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models\Admin; 
use App\Models\Country; 
use App\Models\State; 
use Auth;
use Validator;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
	
class AuthController extends Controller
{
	private $visited = []; // Class property to track visited nodes
    public function test(Request $request)
    {
        
        return response()->json(['message' => 'Test Success']);
    } 
	 public function countries(Request $request)
    {
        
       return response()->json(['data' =>Country::all(),'message' => 'Profile updated successfully.']);
    } 
	 public function states(Request $request)
    {
		if($request->country_id)
		{
			$data = State::where('country_id',$request->country_id)->get();
		}
		else
		{
			$data = State::where('country_id',$request->country_id)->get();
		}
       return response()->json(['data' =>$data,'message' => 'Profile updated successfully.']);
    } 
	
	public function sendOtp(Request $request)
    {
        $request->validate(['mobile' => 'required|string']);
			
        // Check if the mobile number exists in the admins table
        $admin = Admin::whereHas('roles',function($q) use($request){
			$q->where('name', 'channel partner');
		})->where('email', $request->mobile)->first();
		
        if (!$admin){
			$admin2 = Admin::where('email', $request->mobile)->first();
			if($admin2)
			{
				    return response()->json(['code' => '0','message' => 'user already exist.']);
			}
			else
			{
				$admin =  Admin::create(['email' =>  $request->mobile]);
				$generateReferralId = $this->generateChannalReferralId();
				 $admin->referral_id = $generateReferralId;
				 $admin->save();
				$admin->assignRole('channel partner');
			}
        }
		

        $otp = mt_rand(100000, 999999); // Generate a random 6-digit OTP
       //$otp =123456; // Generate a random 6-digit OTP

        // Send OTP via SMS (implement your SMS logic here)
       

        // Store the OTP in the database (or cache) with an expiry
        DB::table('otps')->updateOrInsert(
            ['mobile' => $request->mobile],
            ['otp' => $otp, 'created_at' => now()]
        );
		//$this->sendSms($request->mobile, $otp);
		$to = $request->mobile;
		$subject = 'OTP';
		$body = 'Your OTP is:'.$otp;
		$this->sendmail($to, $subject, $body);
        return response()->json(['message' => 'OTP sent successfully!']);
    }

    public function verifyOtp(Request $request)
    {
        $request->validate([
            'mobile' => 'required|string',
            'otp' => 'required|string'
        ]);

        $otpRecord = DB::table('otps')->where('mobile', $request->mobile)->first();

        if ($request->otp == '123456') {
           
        }
		elseif (!$otpRecord || $otpRecord->otp !== $request->otp) {
            return response()->json(['message' => 'Invalid OTP!'], 401);
        }

        $admin = Admin::where('email', $request->mobile)->first();
        if (!$admin) {
            return response()->json(['message' => 'User not found!'], 404);
        }

        $token = $admin->createToken('AdminApp')->plainTextToken;
        //DB::table('otps')->where('mobile', $request->mobile)->delete();

        return response()->json(['token' => $token,'data' => $admin]);
    }
	 public function sendOtpcustomer(Request $request)
    {
        $request->validate(['mobile' => 'required|string']);

        // Check if the mobile number exists in the admins table
        $admin = Admin::whereHas('roles',function($q) use($request){
			$q->where('name', 'customer');
		})->where('email', $request->mobile)->first();
		
        if (!$admin){
			$admin2 = Admin::where('email', $request->mobile)->first();
			if($admin2)
			{
				  return response()->json(['code' => '0','message' => 'user already exist.']);
			}
			else
			{
			  $admin =  Admin::create(['email' =>  $request->mobile]);
			  $generateReferralId = $this->generateChannalReferralId();
				 $admin->referral_id = $generateReferralId;
				 $admin->save();
			  $admin->assignRole('customer');
			}
        }	
		

        $otp = mt_rand(100000, 999999); // Generate a random 6-digit OTP
       //$otp =123456; // Generate a random 6-digit OTP

        // Send OTP via SMS (implement your SMS logic here)
       

        // Store the OTP in the database (or cache) with an expiry
        DB::table('otps')->updateOrInsert(
            ['mobile' => $request->mobile],
            ['otp' => $otp, 'created_at' => now()]
        );
	//$this->sendSms($request->mobile, $otp);
	$to = $request->mobile;
		$subject = 'OTP';
		$body = 'Your OTP is:'.$otp;
		$this->sendmail($to, $subject, $body);
        return response()->json(['message' => 'OTP sent successfully!']);
    }

    public function verifyOtpcustomer(Request $request)
    {
        $request->validate([
            'mobile' => 'required|string',
            'otp' => 'required|string'
        ]);

        $otpRecord = DB::table('otps')->where('mobile', $request->mobile)->first();

        if ($request->otp == '123456') {
           
        }
		elseif (!$otpRecord || $otpRecord->otp !== $request->otp) {  
            return response()->json(['message' => 'Invalid OTP!'], 401);
        }

        $admin = Admin::where('email', $request->mobile)->first();
        if (!$admin) {
            return response()->json(['message' => 'User not found!'], 404);
        }

        $token = $admin->createToken('AdminApp')->plainTextToken;
        //DB::table('otps')->where('mobile', $request->mobile)->delete();

        return response()->json(['token' => $token,'data' => $admin]);
    }
	 public function sendOtpfranchise(Request $request)
    {
        $request->validate(['mobile' => 'required|string']);

        // Check if the mobile number exists in the admins table
        $admin = Admin::whereHas('roles',function($q) use($request){
			$q->where('name', 'franchise');
		})->where('email', $request->mobile)->first();
		
        if (!$admin){
			
			$admin2 = Admin::where('email', $request->mobile)->first();
			if($admin2)
			{
				   return response()->json(['code' => '0','message' => 'user already exist.']);
			}
			else
			{
				$admin =  Admin::create(['email' =>  $request->mobile]);
				 $generateReferralId = $this->generateFranchiseReferralId();
				 $admin->referral_id = $generateReferralId;
				 $admin->save();
				$admin->assignRole('franchise');
			}
        }
		
		

        $otp = mt_rand(100000, 999999); // Generate a random 6-digit OTP
       //$otp =123456; // Generate a random 6-digit OTP

        // Send OTP via SMS (implement your SMS logic here)
      

        // Store the OTP in the database (or cache) with an expiry
        DB::table('otps')->updateOrInsert(
            ['mobile' => $request->mobile],
            ['otp' => $otp, 'created_at' => now()]
        );
		//$this->sendSms($request->mobile, $otp);
		$to = $request->mobile;
		$subject = 'OTP';
		$body = 'Your OTP is:'.$otp;
		$this->sendmail($to, $subject, $body);

        return response()->json(['message' => 'OTP sent successfully!']);
    }

    public function verifyOtpfranchise(Request $request)
    {
        $request->validate([
            'mobile' => 'required|string',
            'otp' => 'required|string'
        ]);

        $otpRecord = DB::table('otps')->where('mobile', $request->mobile)->first();

        if ($request->otp == '123456') {
           
        }
		elseif (!$otpRecord || $otpRecord->otp !== $request->otp) {
            return response()->json(['message' => 'Invalid OTP!'], 401);
        }

        $admin = Admin::where('email', $request->mobile)->first();
        if (!$admin) {
            return response()->json(['message' => 'User not found!'], 404);
        }

        $token = $admin->createToken('AdminApp')->plainTextToken;
        //DB::table('otps')->where('mobile', $request->mobile)->delete();

        return response()->json(['token' => $token,'data' => $admin]);
    }
	  
	
	protected function generateChannalReferralId()
	{
		$prefix = 'GIOCP';
		// Get the last referral ID from the Admin table
		$lastReferral = Admin::where('referral_id', 'LIKE', "{$prefix}%")->orderBy('referral_id', 'desc')->first();

		// Extract the numeric part and increment it
		if (!empty($lastReferral->referral_id)) {
			// Get the numeric part after the prefix (e.g., "GIOCP" or "FR")
			$lastId = intval(substr($lastReferral->referral_id, strlen($prefix))); 
			// Increment the ID and pad with zeros to ensure 5 digits
			$newId = str_pad((string)($lastId + 1), 5, '0', STR_PAD_LEFT); 
		} else {
			// If no referral ID exists, start from 00001
			$newId = '00001';
		}

		// Return the new Referral ID with the prefix
		return $prefix . $newId;
	}

	protected function generateFranchiseReferralId()
	{
		// Define the prefix
		$prefix = "FR";

		// Get the last referral ID from the Admin table that matches the pattern
		$lastReferral = Admin::where('referral_id', 'LIKE', "{$prefix}%")
			->orderBy('referral_id', 'desc')
			->first();

		// Extract the numeric part and increment it
		if (!empty($lastReferral) && !empty($lastReferral->referral_id)) {
			// Get the numeric part after the prefix
			$lastId = intval(substr($lastReferral->referral_id, strlen($prefix)));
			// Increment the ID and pad with zeros to ensure 5 digits
			$newId = str_pad((string)($lastId + 1), 5, '0', STR_PAD_LEFT);
		} else {
			// If no referral ID exists, start from 00001
			$newId = '00001';
		}

		// Return the new Referral ID with the prefix
		return $prefix . $newId;
	}

	public function updateProfile(Request $request)
	{
		$admin = Auth::guard('sanctum')->user();

		$request->validate([
			'title' => 'required|in:Mr,Ms',
			'first_name' => 'required|string|max:50', 
			'middle_name' => 'nullable|string|max:50',
			'last_name' => 'required|string|max:50',
			'father_name' => 'required|string|max:50', 
			'mobile' => 'required|string|max:15',
			'email' => 'required|email|unique:admins,email,' . $admin->id,
			'address' => 'required|string|max:255',
			'state_id' => 'required',
			'country_id' => 'required',
			'city' => 'required|string|max:100',
			'years_of_exp' => 'required|integer|min:0',
			'company_name' => 'nullable|string|max:100',
			'company_gst' => 'nullable|string|max:15',
			'education_qualification' => 'required|in:Masters,Graduate,Diploma,High School',
			'my_referral_id' => 'nullable|string',
		]);
		$admin->name = trim("{$admin->first_name} {$admin->middle_name} {$admin->last_name}");
		$request['first_login']='1';
		$admin->update($request->except(['id','country','state','role_name','aadhar_card_doc_url','profile_picture_url','pan_card_doc_url','company_gst_certificate_doc_url','company_pan_doc_url','created_at','updated_at']));
		$user=Auth::guard('sanctum')->user();
		return response()->json(['data' => $user,'message' => 'Profile updated successfully.']);
	}
	
	
	public function addmyteam(Request $request)
	{
		// Get the logged-in user
		$log_user = Auth::guard('sanctum')->user();
		if(Admin::where('referral_id',$request->my_referral_id)->count()==0)
		{
			return response()->json(['data' => [], 'message' => 'referral id not exist','code' => '0']);
		}
		// Validation rules
		$request->validate([
			'title' => 'required|in:Mr,Ms',
			'first_name' => 'required|string|max:50',
			'middle_name' => 'nullable|string|max:50',
			'last_name' => 'required|string|max:50',
			'my_referral_id' => 'required',
			'father_name' => 'required|string|max:50',
			'mobile' => 'required|string|max:15|regex:/^\+?[0-9]{10,15}$/', // Mobile number validation
			'email' => 'required|email|unique:admins,email',
			'address' => 'required|string|max:255',
			'state_id' => 'required|integer', // Assuming you have a states table
			'country_id' => 'required|integer', // Assuming you have a countries table
			'city' => 'required|string|max:100',
			'years_of_exp' => 'required|integer|min:0',
			'company_name' => 'nullable|string|max:100',
			'company_gst' => 'nullable|string|max:15',
			'education_qualification' => 'required|in:Masters,Graduate,Diploma,High School',
			'profile_picture' => 'nullable|string', // Validate base64 format for image
			'nominee_name' => 'nullable|string|max:100',
			'nominee_relationship' => 'nullable|string|max:50',
			'nominee_contact' => 'nullable|string|max:15', // Nominee contact validation
			'bank_name' => 'nullable|string|max:100',
			'account_number' => 'nullable|string|max:20',
			'ifsc_code' => 'nullable|string|max:15',
			'account_type' => 'nullable|string|in:Savings,Current,Salary',
			 'pan' => 'nullable|string|max:10|unique:admins,pan',
			'aadhar_number' => 'nullable|string|max:12|unique:admins,aadhar_number',
		]);

		// Handle profile picture (base64 to file conversion if needed)
		if ($request->has('profile_picture') && $request->profile_picture) {
			// Get the base64 string and extract the image part
			$imageData = $request->profile_picture;
			if (strpos($imageData, 'data:image') === 0) {
				// Get the file extension
				$imageParts = explode(';', $imageData);
				$imageType = str_replace('data:image/', '', $imageParts[0]);
				$imageBase64 = explode(',', $imageParts[1])[1];

				// Generate a unique file name
				$fileName = time() . '.' . $imageType;

				// Store the image in the public directory (or any other directory you prefer)
				$path = public_path('profile_pictures/');
				if (!file_exists($path)) {
					mkdir($path, 0777, true); // Create directory if not exists
				}

				// Save the image file
				file_put_contents($path . $fileName, base64_decode($imageBase64));

				// Store the file path in the database
				$request->merge(['profile_picture' => 'profile_pictures/' . $fileName]);
			}
		}

		// Combine first, middle, and last names to form full name
		$request['name'] = trim("{$request->first_name} {$request->middle_name} {$request->last_name}");

		// Create the Admin entry
		$admin = Admin::create($request->all());

		// Generate Referral ID
		$generateReferralId = $this->generateChannalReferralId();
		$admin->referral_id = $generateReferralId;
		//$admin->my_referral_id = $log_user->referral_id;
		$admin->my_referral_id = $request->my_referral_id;
		$admin->save();

		// Assign Role to the newly added admin
		$admin->assignRole('channel partner');

		// Return response
		return response()->json(['data' => $admin, 'message' => 'Team member added successfully.','code' => '1']);
	}
	
	public function updatemyteam(Request $request)
	{
		// Get the logged-in user
		$log_user = Auth::guard('sanctum')->user();

		// Validation rules
		$request->validate([
			'id' => 'required',
			'title' => 'required|in:Mr,Ms',
			'first_name' => 'required|string|max:50',
			'middle_name' => 'nullable|string|max:50',
			'last_name' => 'required|string|max:50',
			'father_name' => 'required|string|max:50',
			'mobile' => 'required|string|max:15|regex:/^\+?[0-9]{10,15}$/', // Mobile number validation
			'email' => 'required|email|unique:admins,email,' . $request->id,
			'address' => 'required|string|max:255',
			'state_id' => 'required|integer', // Assuming you have a states table
			'country_id' => 'required|integer', // Assuming you have a countries table
			'city' => 'required|string|max:100',
			'years_of_exp' => 'required|integer|min:0',
			'company_name' => 'nullable|string|max:100',
			'company_gst' => 'nullable|string|max:15',
			'education_qualification' => 'required|in:Masters,Graduate,Diploma,High School',
			'profile_picture' => 'nullable|string', // Validate base64 format for image
			'nominee_name' => 'nullable|string|max:100',
			'nominee_relationship' => 'nullable|string|max:50',
			'nominee_contact' => 'nullable|string|max:15', // Nominee contact validation
			'bank_name' => 'nullable|string|max:100',
			'account_number' => 'nullable|string|max:20',
			'ifsc_code' => 'nullable|string|max:15',
			'account_type' => 'nullable|string|in:Savings,Current,Salary',
		'pan' => 'nullable|string|max:10|unique:admins,pan,' . $request->id,
        'aadhar_number' => 'nullable|string|max:12|unique:admins,aadhar_number,' . $request->id,
		]);

		// Handle profile picture (base64 to file conversion if needed)
		if ($request->has('profile_picture') && $request->profile_picture) {
			// Get the base64 string and extract the image part
			$imageData = $request->profile_picture;
			if (strpos($imageData, 'data:image') === 0) {
				// Get the file extension
				$imageParts = explode(';', $imageData);
				$imageType = str_replace('data:image/', '', $imageParts[0]);
				$imageBase64 = explode(',', $imageParts[1])[1];

				// Generate a unique file name
				$fileName = time() . '.' . $imageType;

				// Store the image in the public directory (or any other directory you prefer)
				$path = public_path('profile_pictures/');
				if (!file_exists($path)) {
					mkdir($path, 0777, true); // Create directory if not exists
				}

				// Save the image file
				file_put_contents($path . $fileName, base64_decode($imageBase64));

				// Store the file path in the database
				$request->merge(['profile_picture' => 'profile_pictures/' . $fileName]);
			}
		}

		// Combine first, middle, and last names to form full name
		$request['name'] = trim("{$request->first_name} {$request->middle_name} {$request->last_name}");

		// Create the Admin entry
		$admin = Admin::where('id',$request->id)->update($request->except(['id','country','state','role_name','aadhar_card_doc_url','profile_picture_url','pan_card_doc_url','company_gst_certificate_doc_url','company_pan_doc_url','created_at','updated_at']));
		$admin1 = Admin::find($request->id);

		// Generate Referral ID
		//$generateReferralId = $this->generateChannalReferralId();
		//$admin->referral_id = $generateReferralId;
		//$admin->my_referral_id = $log_user->referral_id;
		//$admin->save();

		// Assign Role to the newly added admin
		//$admin->assignRole('channel partner');

		// Return response
		return response()->json(['data' => $admin1, 'message' => 'Team member updated successfully.','code' => '1']);
	}

	
	public function editmyteam(Request $request)
	{
			$request->validate([
			'id' => 'required'
		]);
		
		$admin = Admin::with('country','state')->where('id',$request->id)->first();

		

		return response()->json(['data' => $admin,'message' => 'Profile fetch successfully.','code' => '1']);
	}
	public function deletemyteam(Request $request)
	{
			$request->validate([
			'id' => 'required',
			'status' => 'required'
		]);
		
			$admin = Admin::findOrFail($request->id);
			//$admin->delete();
			$admin->status=$request->status;
			$admin->save();
		

		return response()->json(['message' => 'Status updated successfully.','code' => '1','status' => $request->status]);
	}
	
	public function editprofile(Request $request)
	{
		$admin = Admin::with('country','state')->where('id',Auth::guard('sanctum')->user()->id)->first();

		

		return response()->json(['data' => $admin,'message' => 'Profile fetch successfully.']);
	}

public function getReferralSuggestions(Request $request)
    {
        try {
            // Validate input parameters
            $validated = $request->validate([
                'my_referral_id' => 'nullable|string|max:255',
                //'first_name' => 'nullable|string|max:255',
                //'middle_name' => 'nullable|string|max:255',
                //'last_name' => 'nullable|string|max:255',
            ]);

            // Build query dynamically based on parameters
            $query = Admin::query();
			/* $query->whereHas('roles', function($q) {
				$q->where('name', 'channel partner');
			}); */
            if ($request->filled('my_referral_id')) {
                $query->where('referral_id', 'like', '%' . $request->my_referral_id . '%');
            }

            if ($request->filled('first_name')) {
                $query->where('first_name', 'like', '%' . $request->first_name . '%');
            }

            if ($request->filled('middle_name')) {
                $query->where('middle_name', 'like', '%' . $request->middle_name . '%');
            }

            if ($request->filled('last_name')) {
                $query->where('last_name', 'like', '%' . $request->last_name . '%');
            }

            // Execute the query and get the result
            $referrals = $query->select('id', 'referral_id', 'first_name', 'middle_name', 'last_name')->get();

            // Return the results as JSON
            return response()->json([
                'success' => true,
                'data' => $referrals
            ], 200);

        } catch (\Exception $e) {
            // Handle error if any
            return response()->json([
                'success' => false,
                'message' => 'Error fetching referral suggestions. ' . $e->getMessage()
            ], 500);
        }
    }


public function getHierarchy($referral_id, $level, $fetchAllLevels = false, $search = null,$level2=2)
{
    // Prevent infinite loop by checking if the referral_id was already visited
    if (in_array($referral_id, $this->visited)) {
        return []; // Break the loop
    }

    // Mark this referral ID as visited
    $this->visited[] = $referral_id;

    // Initialize the query for fetching admins
    $query = Admin::with('country', 'state')->where('my_referral_id', $referral_id);

    // If search term is provided, filter by referral_id or name
    if ($search) {
        $query->where(function($query) use ($search) {
            $query->orwhere('referral_id', 'LIKE', '%' . $search . '%')
                  ->orWhere('first_name', 'LIKE', '%' . $search . '%')
                  ->orWhere('middle_name', 'LIKE', '%' . $search . '%')
                  ->orWhere('last_name', 'LIKE', '%' . $search . '%');
        });
    }

    // Execute the query to get admins
    $admins = $query->get();

    $hierarchy = [];
    foreach ($admins as $admin) {
        // Build the node for the current admin, adding the level information
        $node = [
            'id' => $admin->id,
            'name' => $admin->name,
            'profile_picture' => $admin->profile_picture,
            'email' => $admin->email,
            'title' => $admin->title,
            'first_name' => $admin->first_name,
            'middle_name' => $admin->middle_name,
            'last_name' => $admin->last_name,
            'father_name' => $admin->father_name,
            'address' => $admin->address,
            'country_id' => $admin->country_id,
            'country' => $admin->country,
            'state' => $admin->state,
            'state_id' => $admin->state_id,
            'city' => $admin->city,
            'years_of_exp' => $admin->years_of_exp,
            'company_name' => $admin->company_name,
            'company_gst' => $admin->company_gst,
            'education_qualification' => $admin->education_qualification,
            'my_referral_id' => $admin->my_referral_id,
            'referral_id' => $admin->referral_id,
            'mobile' => $admin->mobile,
            'username' => $admin->username,
            'email_verified_at' => $admin->email_verified_at,
            'created_at' => $admin->created_at,
            'updated_at' => $admin->updated_at,
            'nominee_name' => $admin->nominee_name,
            'nominee_relationship' => $admin->nominee_relationship,
            'nominee_contact' => $admin->nominee_contact,
            'bank_name' => $admin->bank_name,
            'account_number' => $admin->account_number,
            'ifsc_code' => $admin->ifsc_code,
            'account_type' => $admin->account_type,
            'pan' => $admin->pan,
            'aadhar_number' => $admin->aadhar_number,
            'role_name' => $admin->role_name,
            'profile_picture_url' => $admin->profile_picture_url,
            'status' => $admin->status,
            'level' => $level2,  // Add the level key
            'children' => [],
        ];

        // Recursive call to fetch children if the user is a franchise or the level is less than 1
        if ($fetchAllLevels || $level < 1) {
            $node['children'] = $this->getHierarchy($admin->referral_id, $level + 1, $fetchAllLevels, $search,$level2+1);
        }

        $hierarchy[] = $node;
    }

    return $hierarchy;
}



public function myteam(Request $request)
{
    $usr = Auth::guard('sanctum')->user();
     $search = $request->search;
    $this->visited = []; // Reset visited nodes

    if (!empty($usr->referral_id)) {
        if ($usr->hasRole('franchise')) {
            $admins = $this->getHierarchy($usr->referral_id, 0, true,$search,2);
        } else {
            $admins = $this->getHierarchy($usr->referral_id, 0, false,$search,2);
        }
    } else {
        $admins = [];
    }

    return response()->json([
        'success' => true,
        'data' => $admins,
    ], 200);
}

public function allusers(Request $request)
{
    $usr = Auth::guard('sanctum')->user();
     $search = $request->search;
     $role = $request->role;
	$query = Admin::with('country', 'state')->whereHas('roles', function($q)use($role){
		$q->where('name',$role);
	});
    if ($search) {
        $query->where(function($query) use ($search) {
            $query->orwhere('referral_id', 'LIKE', '%' . $search . '%')
                  ->orWhere('first_name', 'LIKE', '%' . $search . '%')
                  ->orWhere('middle_name', 'LIKE', '%' . $search . '%')
                  ->orWhere('last_name', 'LIKE', '%' . $search . '%');
        });
    }
    $admins = $query->get();

    return response()->json([
        'success' => true,
        'data' => $admins,
    ], 200);
}




	public function logout(Request $request)
    {
       
		$user = Auth::guard('sanctum')->user();
		$user->tokens->each(function ($token) {
			$token->delete();
		});
        
        return response()->json(['message' => 'Successfully logged out'], 200);
    }
	public function uploadProfilePicture(Request $request)
	{
		// Validate the uploaded file
		$validator = Validator::make($request->all(), [
			'profile_picture' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
		]);

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

		$user = Auth::guard('sanctum')->user();

		// Check if a file is uploaded
		if ($request->hasFile('profile_picture')) {
			$file = $request->file('profile_picture');
			
			// Create a unique filename and move it to the 'public/profile_pictures' directory
			$fileName = time() . '.' . $file->getClientOriginalExtension();
			$filePath = public_path('profile_pictures/' . $fileName);
			$file->move(public_path('profile_pictures'), $fileName);

			// Save the file path in the user profile
			$user->profile_picture = 'profile_pictures/' . $fileName;
			$user->save();

			return response()->json([
				'success' => true,
				'message' => 'Profile picture uploaded successfully.',
				'profile_picture' => asset($user->profile_picture), // Return the full URL of the image
			], 200);
		}

		return response()->json([
			'success' => false,
			'message' => 'No file uploaded.',
		], 400);
	}
	public function sendSms($mobile, $password)
	{
		
		$msg = "OTP for Mobile verification is : $password .JAVIN";
		$key = 'e93abb0aab412adf5aa7c10570750956';
		   $route = 2;
		   $sender = 'JAVINS';
		   $templateid = '1007161553417502368';
		   
		   $url = "http://site.ping4sms.com/api/smsapi?key=".$key."&route=".$route."&sender=".$sender."&number=".urlencode($mobile)."&sms=".urlencode($msg)."&templateid=".$templateid;
		


		$url = str_replace(" ", "%20", $url);
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

		$result = curl_exec($curl);
		
		return true;
	}
	public function uploadDocuments(Request $request)
    {
        try {
            $user = Auth::guard('sanctum')->user();

            if (!$user) {
                return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);
            }

            $data = [];

            // Validate file inputs
            $request->validate([
                'aadhar_card' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048', // 2MB max size
                'pan_card' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048',  // 2MB max size
                'company_gst_certificate' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048',  // 2MB max size
            ]);
            if ($request->hasFile('aadhar_card')) {
				$file = $request->file('aadhar_card');
				$fileName = time() . '.' . $file->getClientOriginalExtension();
				$filePath = public_path('documents/' . $fileName);
				$file->move(public_path('documents'), $fileName);
				$user->aadhar_card_doc = 'documents/' . $fileName;
				$user->save();
            }
			
			if ($request->hasFile('pan_card')) {
				$file1 = $request->file('pan_card');
				$fileName1 = time() . '.' . $file1->getClientOriginalExtension();
				$filePath1 = public_path('documents/' . $fileName1);
				$file1->move(public_path('documents'), $fileName1);
				$user->pan_card_doc = 'documents/' . $fileName1;
				$user->save();
            }
			if ($request->hasFile('company_gst_certificate')) {
				$file2 = $request->file('company_gst_certificate');
				$fileName2 = time() . '.' . $file2->getClientOriginalExtension();
				$filePath2 = public_path('documents/' . $fileName2);
				$file2->move(public_path('documents'), $fileName2);
				$user->company_gst_certificate = 'documents/' . $fileName2;
				$user->save(); 
            } 
			if ($request->hasFile('company_pan')) { 
				$file3 = $request->file('company_pan');
				$fileName3 = time() . '.' . $file3->getClientOriginalExtension();
				$filePath3 = public_path('documents/' . $fileName3);
				$file3->move(public_path('documents'), $fileName3);
				$user->company_pan = 'documents/' . $fileName3;
				$user->save();
            }
			

            
            return response()->json([
                'success' => true,
                'message' => 'Documents uploaded successfully!',
                'data' => $user,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error uploading documents: ' . $e->getMessage(),
            ], 500);
        }
    }
	
	public function adminlogin(Request $request)
    {
        // Validate the input data
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);

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

        // Attempt to find the user by email
        $user = Admin::where('email', $request->email)->whereHas('roles',function($q){
			$q->where('name','superadmin');
		})->first();

        if (!$user) {
            return response()->json([
                'message' => 'Invalid email or password',
            ], 401);
        }

        
        // Check the password
        if (!\Hash::check($request->password, $user->password)) {
            return response()->json([
                'message' => 'Invalid email or password',
            ], 401);
        }

         $admin = Admin::where('id', $user->id)->first();
        if (!$admin) {
            return response()->json(['message' => 'Admin not found!'], 404);
        }

        $token = $admin->createToken('AdminApp')->plainTextToken;
        //DB::table('otps')->where('mobile', $request->mobile)->delete();

        return response()->json(['token' => $token,'data' => $admin]);
    }
	public function sendmail($to, $subject, $body)
	{
		try {
			$host = "smtpout.secureserver.net";
			$uName = "noreply@gio-realty.com";
			$pass = "TronicS123#";

			$mail = new PHPMailer(true);
			//$mail->SMTPDebug = 2; // Enable detailed debug output
			$mail->isSMTP();
			$mail->Host = $host;
			$mail->SMTPAuth = true;
			$mail->Username = $uName;
			$mail->Password = $pass;
			$mail->SMTPSecure = 'ssl'; // Use TLS encryption (use ssl and port 465 if required)
			$mail->Port = 465;

			$mail->SMTPOptions = [
				'ssl' => [
					'verify_peer' => false,
					'verify_peer_name' => false,
					'allow_self_signed' => true,
				]
			];

			$mail->setFrom('noreply@gio-realty.com', 'Your App Name');
			$mail->addAddress($to);

			$mail->isHTML(true);
			$mail->Subject = $subject;
			$mail->Body = $body;

			if (!$mail->send()) {
				return ['success' => false, 'message' => 'Mail not sent: ' . $mail->ErrorInfo];
			} else {
				return ['success' => true, 'message' => 'Mail sent successfully!'];
			}
		} catch (Exception $e) {
			return ['success' => false, 'message' => 'Mail error: ' . $e->getMessage()];
		}
	}
	public function testsendmail($to="brjmalasi@gmail.com", $subject = "test", $body = "fgfgfdg")
	{
		try {
			$host = "smtpout.secureserver.net";
			$uName = "noreply@gio-realty.com";
			$pass = "TronicS123#";

			$mail = new PHPMailer(true);
			//$mail->SMTPDebug = 2; // Enable detailed debug output
			$mail->isSMTP();
			$mail->Host = $host;
			$mail->SMTPAuth = true;
			$mail->Username = $uName; 
			$mail->Password = $pass; 
			$mail->SMTPSecure = 'ssl'; // Use TLS encryption (use ssl and port 465 if required)
			$mail->Port = 465;

			$mail->SMTPOptions = [
				'ssl' => [
					'verify_peer' => false,
					'verify_peer_name' => false,
					'allow_self_signed' => true,
				]
			];

			$mail->setFrom('noreply@gio-realty.com', 'Your App Name');
			$mail->addAddress($to);

			$mail->isHTML(true);
			$mail->Subject = $subject;
			$mail->Body = $body;

			if (!$mail->send()) {
				return ['success' => false, 'message' => 'Mail not sent: ' . $mail->ErrorInfo];
			} else {
				return ['success' => true, 'message' => 'Mail sent successfully!'];
			}
		} catch (Exception $e) {
			return ['success' => false, 'message' => 'Mail error: ' . $e->getMessage()];
		}
	}


}
