<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;




class ApiController extends Controller
{
    public function __construct()
    {
    }

    //All PujaService API's
    public function getAllPooja($page_number = 1, $count = 0)
    {
        $section_title = "Puja Services";
        if ($page_number < 1) {
            $page_number = 1;
        }
        Paginator::currentPageResolver(function () use ($page_number) {
            return $page_number;
        });

        $pujas = DB::table('poojaservices')->orderBy('created_at', 'desc');

        if ($count > 0) {
            $pujas = $pujas->paginate($count);
        } else {
            $pujas = $pujas->get();
        }

        if ($pujas instanceof \Illuminate\Pagination\AbstractPaginator || $pujas instanceof \Illuminate\Pagination\LengthAwarePaginator) {
            if ($pujas->total() > 0) {
                $response_details = [];
                $sl = 1;
                foreach ($pujas as $puja) {
                    $response_details[] = [
                        'slno' => $sl,
                        'Title' => $puja->name, // Directly use the 'name' column
                        'Description' => $puja->description, // Directly use the 'description' column
                        'Amount' => $puja->amount,
                        'Capacity' => $puja->capacity,
                    ];
                    $sl++;
                }

                $response = [
                    'responseCode' => 200,
                    "responseMsg" => "data fetched",
                    'title' => $section_title,
                    'data_count' => $pujas->total(),
                    'data' => ['records' => $response_details],
                ];
                return response()->json($response, 200);
            } else {
                return response()->json([
                    "responseCode" => 201,
                    'responseMsg' => 'There is no data',
                    'title' => $section_title,
                    'data' => []
                ], 200);
            }
        } elseif ($pujas instanceof \Illuminate\Support\Collection) {
            if ($pujas->count() > 0) {
                $response_details = [];
                $sl = 1;
                foreach ($pujas as $puja) {
                    $response_details[] = [
                        'slno' => $sl,
                        'PujaServiceId' => $puja->id,
                        'Title' => $puja->name_en, 
                        'Description' => $puja->description_en, 
                        'Amount' => $puja->amount,
                        'Time' => $puja->time,
                        'Type' => $puja->type,
                        'Capacity' => $puja->capacity,
                        'Image' => $puja->images,
                        'start_date' => $puja->start_date,
                        'frequency' => $puja->frequency,
                        'prasad_delivery' => $puja->prasad_delivery,
                        'information' => $puja->information_dec,
                    ];
                    $sl++;
                }

                $response = [
                    'responseCode' => 200,
                    "responseMsg" => "data fetched",
                    'title' => $section_title,
                    'data_count' => $pujas->count(),
                    'data' => ['records' => $response_details],
                ];
                return response()->json($response, 200);
            } else {
                return response()->json([
                    "responseCode" => 201,
                    'responseMsg' => 'There is no data',
                    'title' => $section_title,
                    'data' => []
                ], 200);
            }
        } else {
            return response()->json([
                "responseCode" => 500,
                'responseMsg' => 'Unexpected error occurred',
                'title' => $section_title,
                'data' => []
            ], 500);
        }
    }

    
public function getByPujaServiceId(Request $request)
{
    // echo "Pati"; exit();
    $validator = Validator::make($request->all(), [
        'PujaServiceId' => 'required|integer',
    ]);

    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }else{
     $id = $request->input('PujaServiceId');
    $pujas = DB::table('poojaservices')->where('id',$id)
					->first();
    }
 $response_details[] = [
                    
                    'PujaServiceId' => $pujas->id,
                    'Title' => $pujas->name_en,
                    'Description' => $pujas->description_en,
                    'Amount' => $pujas->amount,
                    'Time' => $pujas->time,
                    'Type' => $pujas->type,
                    'Capacity' => $pujas->capacity,
                    'Image' =>$pujas->images,
                    'start_date' =>$pujas->start_date,
                    'frequency' =>$pujas->frequency,
                    'prasad_delivery'=>$pujas->prasad_delivery,
                    'information' => $pujas->information_dec,
                ];
                
            return response()->json([
				'responseCode' => '200',
				'responseMsg' => 'Pooja Services fetched successfully',
                'data' => ['records' => $response_details],
                
            ]);

}

public function getUserDetailsByEmailId(Request $request)
{
    $email = $request->input('email');
    $userDetails = DB::table('users_details')
                    ->select('users_details.*', 'user_spouses.devote_name', 'user_spouses.spouse_name','user_spouses.gothram')
                    ->join('user_spouses', 'users_details.id', '=', 'user_spouses.user_id')
                    ->where('email', $email)
                    ->get();

    if ($userDetails->isEmpty()) {
        return response()->json([
            'responseCode' => '404',
            'responseMsg' => 'No user found with the provided email address',
        ], 404);
    }

    // Extracting user details
    $userData = [
        //'slno' => $sl,
        'email' => $userDetails[0]->email,
        'phone' => $userDetails[0]->phone_no,
        'message' => $userDetails[0]->message,
        'address' => $userDetails[0]->address,
        //'user_id' => $userDetails[0]->id,
    ];

    // Extracting user spouse details
    $spouseData = [];
    foreach ($userDetails as $detail) {
        $spouseData[] = [
            //'slno' => $sl,
            'devote_name' => $detail->devote_name,
            'spouse_name' => $detail->spouse_name,
            'gothram' => $detail->gothram,

        ];
        //$sl++;
    }

    return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'User details fetched successfully',
       // 'slno' => $sl,
        'UserDetails' => $userData,
        'SpouseDetails' => $spouseData,
    ]);

}
public function poojaBooking1(Request $request)
{
    // Check if email already exists
    $existingUser = DB::table('users_details')->where('email', $request->input('email'))->first();
   
    // Check if slots are available for the selected pooja service
    $poojaService = DB::table('poojaservices')->where('id', $request->input('pooja_service_id'))->first();

    if ($poojaService && $poojaService->capacity <= 0) {
        return response()->json([
            'responseCode' => '400',
            'responseMsg' => 'Slot not available for the selected pooja service',
        ], 400);
    }

    // Insert user record and get the user ID
    if ($existingUser) {
    $email = $request->input('email');
   $userId = DB::table('users_details')->where('email', $email)->value('id');
DB::table('users_details')
    ->where('email', $email)
    ->update([
        'email' => $request->input('email'),
        'phone_no' => $request->input('phone_no'),
        'message' => $request->input('message'),
        'address' => $request->input('address'),
    ]);
    }else{
    $userId = DB::table('users_details')->insertGetId([
        'email' => $request->input('email'),
        'phone_no' => $request->input('phone_no'),
        'message' => $request->input('message'),
        'address' => $request->input('address'),
        
    ]);
    }

   
      
     // print_r($uId);exit;
   // Extract family member names from the input
$familyMembers = $request->input('family_member_name');

// Prepare spouse data as an array of names
$familyMemberData = [];
foreach ($familyMembers as $member) {
    $familyMemberData[] = $member;
}

// Insert into user_spouses table
DB::table('user_spouses')->insert([
    'user_id' =>$userId,
    'devote_name' => $request->input('devote_name'),
    'spouse_name' => $request->input('spouse_name'),
    'gothram' => $request->input('gothram'),
    'add_family_members' => json_encode($familyMemberData),
]);

   // Insert pooja booking record
    $bookingId = DB::table('poojabookings')->insertGetId([
        'pooja_service_id' => $request->input('pooja_service_id'),
        'user_id' => $userId,
        'pooja_time' => $request->input('pooja_time'),
        'start_date' =>$request->input('start_date'),
    ]);

    // Fetch the inserted booking record
    $booking = DB::table('poojabookings')->where('id', $bookingId)->first();

    return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'Pooja booking and user details inserted successfully',
        'data' => $booking,
    ]);
}

public function poojaBooking(Request $request)
{
    $familyMembers = $request->input('family_member_name');

// Prepare spouse data as an array of names
$familyMemberData = [];
foreach ($familyMembers as $member) {
    $familyMemberData[] = $member;
}

// Insert into user_spouses table
 $devoteeId = DB::table('user_spouses')->insertGetId([
    //'user_id' =>$userId,
    'devote_name' => $request->input('devote_name'),
    'spouse_name' => $request->input('spouse_name'),
    'gothram' => $request->input('gothram'),
    'add_family_members' => json_encode($familyMemberData),
    'puja_duration' => $request->input('puja_duration'),
    'start_date' => $request->input('start_date'),
     'type' =>'puja',
    
]);

// cart table
$cartId = DB::table('pooja_cart')->insertGetId([
    'user_gotram_id' =>$devoteeId,
    'puja_service_id' => $request->input('puja_service_id'),
    'amount' => $request->input('amount'),
   
]);

$devoteeD = DB::table('user_spouses')->where('id',$devoteeId)->get();
$pujaService = DB::table('poojaservices')->where('id',$request->input('puja_service_id'))->value('name_en');


  $gotram_id= $devoteeD[0]->id;
  $gothram = $devoteeD[0]->gothram;
  $devote_name= $devoteeD[0]->devote_name;
  $spouse_name = $devoteeD[0]->spouse_name;
  $date = $devoteeD[0]->start_date;
  //$cartId = $cartId[0]->id;

  

 return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'Pooja booking and user details inserted successfully',
        'gotram_id' => $gotram_id,
        'puja_service' =>$pujaService,
        'devote_name' =>$devote_name,
        'spouse_name' => $spouse_name,
        'date_time' =>$date,
        'cart_id' =>$cartId,
        'amount' =>$request->input('amount'),
        
        
    ]);

}


public function poojaCommonData(Request $request)
{
  
    $uId = $request->input('user_id');
    $cId = $request->input('cart_id');
    $gId = $request->input('gotram_id');

    $userCount = DB::table('pooja_common')->where('user_id', $uId)->count();
    $cartCount = DB::table('pooja_common')->where('cart_id', $cId)->count();
    $gotramCount = DB::table('pooja_common')->where('gotram_id', $gId)->count();

if($userCount > 0 && $cartCount> 0 && $gotramCount > 0){

$data = DB::table('pooja_common')
            ->select('user_spouses.*', 'pooja_common.*', 'pooja_cart.id AS cart_id','pooja_cart.puja_service_id','pooja_cart.deleted_flag', 'poojaservices.name_en AS pojaservice_name','poojaservices.id AS puja_service_id')
            ->join('user_spouses', 'pooja_common.gotram_id', '=', 'user_spouses.id')
            ->join('pooja_cart', 'pooja_common.cart_id', '=', 'pooja_cart.id')
            ->join('poojaservices', 'pooja_cart.puja_service_id', '=', 'poojaservices.id')
                 ->where('user_spouses.deleted_flag', '=', NULL)
                ->where('pooja_cart.deleted_flag', '=', NULL)
            ->where('pooja_common.gotram_id', $gId)
          
            ->first();
              if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'pooja_cart' => [
                'cart_id' => $data->cart_id,
                 'puja_service_id' => $data->puja_service_id,
                'puja_service_name' => $data->pojaservice_name,
                // Add other fields from pooja_cart table as needed
            ],

        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }

// print_r($data);exit;
}elseif($userCount == 0 && $cartCount == 0 && $gotramCount == 0){
DB::table('pooja_common')->insert([
 'user_id' => $uId,
 'cart_id' => $cId,
 'gotram_id' => $gId,
 'status' => '1',

]);

$data = DB::table('pooja_common')
            ->select('user_spouses.*', 'pooja_common.*', 'pooja_cart.id AS cart_id','pooja_cart.puja_service_id','pooja_cart.deleted_flag', 'poojaservices.name_en AS pojaservice_name','poojaservices.id AS puja_service_id')
            ->join('user_spouses', 'pooja_common.gotram_id', '=', 'user_spouses.id')
            ->join('pooja_cart', 'pooja_common.cart_id', '=', 'pooja_cart.id')
            ->join('poojaservices', 'pooja_cart.puja_service_id', '=', 'poojaservices.id')
              ->where('user_spouses.deleted_flag', '=', NULL)
                ->where('pooja_cart.deleted_flag', '=', NULL)
            ->where('pooja_common.gotram_id', $gId)
               
            ->first();
              if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'pooja_cart' => [
                'cart_id' => $data->cart_id,
                 'puja_service_id' => $data->puja_service_id,
                'puja_service_name' => $data->pojaservice_name,
                // Add other fields from pooja_cart table as needed
            ],

        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }




}elseif ($userCount > 0 ) {
    $data = DB::table('pooja_common')
                ->select('user_spouses.*', 'pooja_common.*', 'pooja_cart.id AS cart_id','pooja_cart.puja_service_id','pooja_cart.amount', 'poojaservices.name_en AS pojaservice_name','poojaservices.id AS puja_service_id')
                ->join('user_spouses', 'pooja_common.gotram_id', '=', 'user_spouses.id')
                ->join('pooja_cart', 'pooja_common.cart_id', '=', 'pooja_cart.id')
                ->join('poojaservices', 'pooja_cart.puja_service_id', '=', 'poojaservices.id')
                  ->where('user_spouses.deleted_flag', '=', NULL)
                ->where('pooja_cart.deleted_flag', '=', NULL)
                ->where('pooja_common.user_id', $uId)
                 
                ->first();
              
    if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'pooja_cart' => [
                'cart_id' => $data->cart_id,
                'puja_service_id' => $data->puja_service_id,
                'puja_service_name' => $data->pojaservice_name,
                'amount' => $data->amount,
                // Add other fields from pooja_cart table as needed
            ]
        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }
}
   
}

public function fetchDataBygId(Request $request)
{
    $devoteeId = $request->input('gotram_id');
    $cId = $request->input('cart_id');
    $gCount = DB::table('user_spouses')->where('id', $devoteeId)->count();
    $cartCount = DB::table('pooja_cart')->where('id', $cId)->count();
    $status = DB::table('pooja_common')->where('gotram_id', $devoteeId)->value('status');
    if($gCount>0 && $cartCount > 0){


    $cartDetails = DB::table('pooja_cart')
                    ->select('user_spouses.*', 'pooja_cart.*', 'poojaservices.name_en AS pojaservice_name')
                    ->join('user_spouses', 'pooja_cart.user_gotram_id', '=', 'user_spouses.id')
                    ->join('poojaservices', 'pooja_cart.puja_service_id', '=', 'poojaservices.id')
                     ->where('user_spouses.id', $devoteeId)
                     ->where('user_spouses.deleted_flag', '=', NULL)
                    ->where('pooja_cart.deleted_flag', '=', NULL)
                    ->first();
    //$cartDetails = $cartDetailsQuery->first();
                    // ->where('user_spouses.id', $devoteeId)
                    // ->first();

    if ($cartDetails) {

        $gotramId = $devoteeId;
        $gothram = $cartDetails->gothram;
        $devoteName = $cartDetails->devote_name;
        $spouseName = $cartDetails->spouse_name;
        $date = $cartDetails->start_date;
        $amount = $cartDetails->amount;

        $pujaServiceId = $cartDetails->puja_service_id;
        $serviceName = $cartDetails->pojaservice_name;


        // Return or process the data as required
        return response()->json([
            'gotram_id' => $gotramId,
            'gothram' => $gothram,
            'devote_name' => $devoteName,
            'spouse_name' => $spouseName,
            'start_date' => $date,
            'puja_service_id' => $pujaServiceId,
            'service_name' => $serviceName,
            'amount' => $amount,

        ]);
    } else {

        return response()->json([
            'message' => 'No data found'
        ], 404);
    }

}elseif($gCount>0 && $cartCount > 0 && $status == 1){
       $data = DB::table('pooja_common')
                ->select('user_spouses.*', 'pooja_common.*', 'pooja_cart.id AS cart_id','pooja_cart.puja_service_id','pooja_cart.amount', 'poojaservices.name_en AS pojaservice_name','poojaservices.id AS puja_service_id')
                ->join('user_spouses', 'pooja_common.gotram_id', '=', 'user_spouses.id')
                ->join('pooja_cart', 'pooja_common.cart_id', '=', 'pooja_cart.id')
                ->join('poojaservices', 'pooja_cart.puja_service_id', '=', 'poojaservices.id')
                ->where('pooja_common.user_id', $uId)
                 ->where('user_spouses.deleted_flag', '!=', 1)
                ->where('pooja_cart.deleted_flag', '!=', 1)
                ->first();

    if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'pooja_cart' => [
                'cart_id' => $data->cart_id,
                'puja_service_id' => $data->puja_service_id,
                'puja_service_name' => $data->pojaservice_name,
                'amount' => $data->amount,
                // Add other fields from pooja_cart table as needed
            ]
        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }
}
}

public function cartDetailsById(Request $request)
{
    $devoteeId = $request->input('gotram_id');
    $userId = $request->input('user_id');

    $cartDetailsQuery = DB::table('pooja_cart')
                    ->select('user_spouses.*', 'pooja_cart.*', 'poojaservices.name_en AS pojaservice_name')
                    ->join('user_spouses', 'pooja_cart.user_gotram_id', '=', 'user_spouses.id')
                    ->join('poojaservices', 'pooja_cart.puja_service_id', '=', 'poojaservices.id');
                    
                     if (!empty($userId)) {
        $cartDetailsQuery->where('user_spouses.user_id', $userId);
    }else{
        $cartDetailsQuery->where('user_spouses.id', $devoteeId);
    }
    $cartDetails = $cartDetailsQuery->first();
                    // ->where('user_spouses.id', $devoteeId)
                    // ->first();

    if ($cartDetails) {
       
        $gotramId = $cartDetails->id; 
        $gothram = $cartDetails->gothram;
        $devoteName = $cartDetails->devote_name;
        $spouseName = $cartDetails->spouse_name;
        $date = $cartDetails->start_date;
       
        $pujaServiceId = $cartDetails->puja_service_id;
        $serviceName = $cartDetails->pojaservice_name;
        

        // Return or process the data as required
        return response()->json([
            'gotram_id' => $gotramId,
            'gothram' => $gothram,
            'devote_name' => $devoteName,
            'spouse_name' => $spouseName,
            'start_date' => $date,
            'puja_service_id' => $pujaServiceId,
            'service_name' => $serviceName
           
        ]);
    } else {
       
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }
}
public function userDetailsById(Request $request)
    {
        $userId = $request->input('user_id');

        // Fetch user data by joining tables
        $userData = DB::table('users_details')
            ->select(
                'users_details.*', 
                'user_spouses.*', 
                'poojabookings.*'
            )
            ->leftJoin('user_spouses', 'users_details.id', '=', 'user_spouses.user_id')
            ->leftJoin('poojabookings', 'users_details.id', '=', 'poojabookings.user_id')
            
            ->where('users_details.id', $userId)
            ->get();
            
            //$responceData =[];
            $userData = [
        //'slno' => $sl,
        'user_id'=>$userData[0]->id,
        
    ];

        if ($userData->isNotEmpty()) {
            // Return response
            return response()->json([
                'user_data' =>$userData
            ]);
        } else {
            // Return error response if user not found
            return response()->json([
                'message' => 'User not found'
            ], 404);
        }
    }


public function bank_response(Request $request)
{
    return [
        'status' => 'success',
        'bank_transaction_id' =>'1212',
        'key'=> 'abcd-1212',
        'message' => 'Pooja payment recorded successfully',
    ];
}
public function generate_payment_transaction_id(Request $request)
{

    $currentDate = date('Ymd');
    $randomNumber = mt_rand(1000, 9999);
    $transactionId = $currentDate . $randomNumber;

    return $transactionId;
}

public function PoojaPayment(Request $request)
{
 $bookingId = DB::table('poojabookings')->insertGetId([
        'pooja_service_id' => $request->input('puja_service_id'),
        'user_id' => $request->input('user_id'),
        //'pooja_time' => $request->input('pooja_time'),
    ]);
    
    $gotramId = $request->input('gotram_id');
    
       $gotram = DB::table('user_spouses')->where('id', $gotramId)
                            ->first();
        $dn = $gotram->devote_name ?? null;
        $gt = $gotram->gothram ?? null;
    
    // $poojaService = DB::table('poojaservices')->where('id',$request->input('pooja_service_id'))->get();
         $poojaService = DB::table('poojaservices')->where('id', $request->input('puja_service_id'))->first();


        $pname = $poojaService->name_en ?? null;
        $img = $poojaService->images ?? null;
        $des = $poojaService->description_en ?? null;
        $date = $poojaService->start_date ?? null;
        $frequency = $poojaService->frequency ?? null;
        $pd = $poojaService->prasad_delivery ?? null;
        //}
    
    


    // Generate payment transaction ID
    $transactionId = $this->generate_payment_transaction_id($request).$bookingId;

    // Insert pooja payment record
    $paymentId = DB::table('payments')->insertGetId([
        'user_id' => $request->input('user_id'),
        
        'booking_id'=> $bookingId,
        'type' => 'Pooja',
        'payment_method' => $request->input('payment_method'),
        'name_on_card' => $request->input('name_on_card'),
        'expire_date' => $request->input('expire_date'),
        'card_number' => $request->input('card_number'),
        'cvv' => $request->input('cvv'),
        'devotee_name' => $request->input('devotee_name'),
        'address' => $request->input('address'),
        'city' => $request->input('city'),
        'state' => $request->input('state'),
        'country' => $request->input('country'),
        'zip' => $request->input('zip'),
        'payment_amount' => $request->input('payment_amount'),
        'payment_generate_transaction_id' => $transactionId,

        // Add other relevant payment details here
    ]);

     $bankResponse = $this->bank_response($request);

    // Insert bank response into payment history
    DB::table('payments_history')->insert([
        'payment_id' => $paymentId,
        'bank_response' => json_encode([
            'status' => $bankResponse['status'],
            'bank_transaction_id' => $bankResponse['bank_transaction_id'],
            'key' => $bankResponse['key'],
            'message' => $bankResponse['message'],
        ]),
    ]);

    // Check if bank response status is success
    if ($bankResponse['status'] === 'success') {

       // $bookingId = $request->input('bookingId');
        $poojaServiceId = DB::table('poojabookings')->where('id', $bookingId)->value('pooja_service_id');
        
        // DB::table('poojaservices')->where('id', $poojaServiceId)->decrement('capacity', 1);
        DB::table('poojabookings')->where('id', $bookingId)->update([
        'ticket' => $transactionId,
       ]);
       
        DB::table('pooja_common')->where('user_id', $request->input('user_id'))->update([
        'booking_id' => $bookingId,
        'status' => '2',
       ]);
    
    }

      // Send email
    Mail::raw('Your Payment has been successfully Completed.', function ($message) use ($request) {
        $message->to('priyanka.sahoo@westechltd.com')
                ->subject('Pooja Payment Confirmation');
    });

    return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'Pooja payment recorded successfully',
        'user_id' =>$request->input('user_id'),
        'Puja_service_name' => $pname,
        'image' =>$img,
        'puja_description' =>$des,
        'start_date' =>$date,
        'frequency' =>$frequency,
        'prasad_delivery' =>$pd,
        'devote_name'=>$dn,
        'gotram' =>$gt,
        'ticket' => $transactionId,
    ]);
}
public function sendEmail()
{

    Mail::to('priyanka.sahoo@westechltd.com')->send(new PoojaPaymentEmail());
}



public function removePuja(Request $request)
{
      $cid = $request->input('cart_id');
       $gid = $request->input('gotram_id');
        DB::table('pooja_cart')
            ->where('id', $cid)
            ->update([
                'deleted_flag' => '1',
               
            ]);

         DB::table('user_spouses')
            ->where('id', $gid)
            ->where('type','puja')
            ->update([
                'deleted_flag' => '1',
               
            ]);
    DB::table('pooja_common')
            ->where('cart_id', $cid)
            ->update([
                'status' => '3',
               
            ]);
            
             return response()->json([
                 'responceCode'=> '200',
            'responceMsg' => 'Cart items removed successfully'
        ]);
        
}

//Events API's
//Api for getAllEvents
public function getEventById(Request $request)
{
    $validator = Validator::make($request->all(), [
        'EventId' => 'required|integer',
    ]);

    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }else{
     $id = $request->input('EventId');
    $events = DB::table('events')->where('id',$id)
					->first();
    }
 $response_details[] = [
                    
                    'EventId' => $events->id,
                    'Title' => $events->event_name_en,
                    'Description' => $events->description_en,
                    'Amount' => $events->event_price,
                    'Capacity' => $events->capacity,
                    'EventDate' =>  $events->event_date,
                    'EventTime' => $events->event_time,
                    'EventDay' => $events->event_day,
                    'Image' => $events->event_img,
                    'start_date' => $events->start_date,
                ];
                
            return response()->json([
				'responseCode' => '200',
				'responseMsg' => 'Pooja Services fetched successfully',
                'data' => ['records' => $response_details],
                
            ]);

}


public function eventBooking1(Request $request)
{
    // Check if email already exists
    $existingUser = DB::table('users_details')->where('email', $request->input('email'))->first();

    // if ($existingUser) {
    //     return response()->json([
            
    //         'responseCode' => '400',
    //         'responseMsg' => 'Email already exists',
    //     ], 400);
    // }

    // Check if slots are available for the selected event
    $event = DB::table('events')->where('id', $request->input('event_id'))->first();

    if ($event && $event->capacity <= 0) {
        return response()->json([
            'responseCode' => '400',
            'responseMsg' => 'Slot not available for the selected event',
        ], 400);
    }

    if ($existingUser) {
    $email = $request->input('email');
    $userId = $existingUser->id;
DB::table('users_details')
    ->where('email', $email)
    ->update([
        'email' => $request->input('email'),
        'phone_no' => $request->input('phone_no'),
        'message' => $request->input('message'),
        'address' => $request->input('address'),
    ]);
    }else{
    $userId= DB::table('users_details')->insertGetId([
        'email' => $request->input('email'),
        'phone_no' => $request->input('phone_no'),
        'message' => $request->input('message'),
        'address' => $request->input('address'),
        
    ]);
    }

    // Extract family member names from the input
$familyMembers = $request->input('family_member_name');

// Prepare spouse data as an array of names
$familyMemberData = [];
foreach ($familyMembers as $member) {
    $familyMemberData[] = $member;
}

// Insert into user_spouses table
DB::table('user_spouses')->insert([
    'user_id' => $userId,
    'devote_name' => $request->input('devote_name'),
    'spouse_name' => $request->input('spouse_name'),
    'gothram' => $request->input('gothram'),
    'add_family_members' => json_encode($familyMemberData),
]);


    // Insert event booking record
    $bookingId = DB::table('event_bookings')->insertGetId([
        'event_id' => $request->input('event_id'),
        'user_id' => $userId,
        'date' => $request->input('date'),
        'speaker' => $request->input('speaker'),
        'ticket' => $request->input('ticket'),

    ]);

    // Fetch the inserted booking record
    $booking = DB::table('event_bookings')->where('id', $bookingId)->first();
     $response_details[] = [
                    'booking_id' => $booking->id,
                    'user_id' => $booking->user_id,
                    'event_id' => $booking->event_id,
                    'date' => $booking->date,
                ];

    return response()->json([
        'responseCode' => '200',
        'responseStatus' => 'Event booking and user details inserted successfully',
        'data' => $response_details,
    ]);
}

public function eventBooking(Request $request)
{
      $familyMembers = $request->input('family_member_name');

// Prepare spouse data as an array of names
$familyMemberData = [];
foreach ($familyMembers as $member) {
    $familyMemberData[] = $member;
}

// Insert into user_spouses table
 $devoteeId = DB::table('user_spouses')->insertGetId([
    //'user_id' =>$userId,
    'devote_name' => $request->input('devote_name'),
    'spouse_name' => $request->input('spouse_name'),
    'gothram' => $request->input('gothram'),
    'add_family_members' => json_encode($familyMemberData),
    //'puja_duration' => $request->input('puja_duration'),
    'start_date' => $request->input('start_date'),
    'type' =>'event',

]);

// cart table
$cartId = DB::table('event_cart')->insertGetId([
    'user_gotram_id' =>$devoteeId,
    'event_id' => $request->input('event_id'),
    'amount' => $request->input('amount'),

]);


$devoteeD = DB::table('user_spouses')->where('id',$devoteeId)->get();
$event = DB::table('events')->where('id',$request->input('event_id'))->value('event_name_en');


  $gotram_id= $devoteeD[0]->id;
  $gothram = $devoteeD[0]->gothram;
  $devote_name= $devoteeD[0]->devote_name;
  $spouse_name = $devoteeD[0]->spouse_name;
  $date = $devoteeD[0]->start_date;
  //$cartId = $cartId[0]->id;



 return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'Event added successfully',
        'gotram_id' => $gotram_id,
        'event' =>$event,
        'devote_name' =>$devote_name,
        'spouse_name' => $spouse_name,
        'date_time' =>$date,
        'cart_id' =>$cartId,
        'amount' =>$request->input('amount'),


    ]);
}


public function eventCommonData(Request $request)
{
  
    $uId = $request->input('user_id');
    $cId = $request->input('cart_id');
    $gId = $request->input('gotram_id');

    $userCount = DB::table('event_common')->where('user_id', $uId)->count();
    $cartCount = DB::table('event_common')->where('cart_id', $cId)->count();
    $gotramCount = DB::table('event_common')->where('gotram_id', $gId)->count();

if($userCount > 0 && $cartCount> 0 && $gotramCount > 0){

$data = DB::table('event_common')
            ->select('user_spouses.*', 'event_common.*', 'event_cart.id AS cart_id','event_cart.event_id','event_cart.amount', 'events.event_name_en AS event_name','events.id AS event_id')
            ->join('user_spouses', 'event_common.gotram_id', '=', 'user_spouses.id')
            ->join('event_cart', 'event_common.cart_id', '=', 'event_cart.id')
            ->join('events', 'event_cart.event_id', '=', 'events.id')
            ->where('user_spouses.type','event')
            ->where('event_common.gotram_id', $gId)
            ->first();
              if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'event_cart' => [
                'cart_id' => $data->cart_id,
                 'event_id' => $data->event_id,
                'event_name' => $data->event_name,
                // Add other fields from pooja_cart table as needed
            ],

        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }

// print_r($data);exit;
}elseif($userCount == 0 && $cartCount == 0 && $gotramCount == 0){
DB::table('event_common')->insert([
 'user_id' => $uId,
 'cart_id' => $cId,
 'gotram_id' => $gId,
 'status' => '1',

]);

$data = DB::table('event_common')
            ->select('user_spouses.*', 'event_common.*', 'event_cart.id AS cart_id','event_cart.event_id','event_cart.amount', 'events.event_name_en AS event_name','events.id AS event_id')
            ->join('user_spouses', 'event_common.gotram_id', '=', 'user_spouses.id')
            ->join('event_cart', 'event_common.cart_id', '=', 'event_cart.id')
            ->join('events', 'event_cart.event_id', '=', 'events.id')
            ->where('event_common.gotram_id', $gId)
            ->first();
              if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'event_cart' => [
                'cart_id' => $data->cart_id,
                 'event_id' => $data->event_id,
                'event_name' => $data->event_name,
                // Add other fields from pooja_cart table as needed
            ],

        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }




}elseif ($userCount > 0 ) {
    $data = DB::table('event_common')
            ->select('user_spouses.*', 'event_common.*', 'event_cart.id AS cart_id','event_cart.event_id','event_cart.amount', 'events.event_name_en AS event_name','events.id AS event_id')
                ->join('user_spouses', 'event_common.gotram_id', '=', 'user_spouses.id')
                ->join('event_cart', 'event_common.cart_id', '=', 'event_cart.id')
                ->join('events', 'event_cart.event_id', '=', 'events.id')
                ->where('event_common.user_id', $uId)
                ->where('user_spouses.deleted_flag', NULL)
                ->where('event_cart.deleted_flag', NULL)
                ->first();
              
    if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'event_cart' => [
                'cart_id' => $data->cart_id,
                'event_id' => $data->event_id,
                'event_name' => $data->event_name,
                'amount' => $data->amount,
                // Add other fields from pooja_cart table as needed
            ]
        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }
}


   
}

public function fetchEventDataBygId(Request $request)
{
    $devoteeId = $request->input('gotram_id');
    $cId = $request->input('cart_id');
    $gCount = DB::table('user_spouses')->where('id', $devoteeId)->count();
    $cartCount = DB::table('event_cart')->where('id', $cId)->count();
    $status = DB::table('event_common')->where('gotram_id', $devoteeId)->value('status');
    if($gCount>0 && $cartCount > 0){


    $cartDetails = DB::table('event_cart')
                    ->select('user_spouses.*', 'event_cart.*', 'events.event_name_en AS event_name','events.start_date AS event_date')
                    ->join('user_spouses', 'event_cart.user_gotram_id', '=', 'user_spouses.id')
                    ->join('events', 'event_cart.event_id', '=', 'events.id')
                    ->where('user_spouses.id',$devoteeId)
                    ->where('type','event')
                    ->where('user_spouses.deleted_flag', NULL)
                    ->where('event_cart.deleted_flag', NULL)
                    ->first();
    //$cartDetails = $cartDetailsQuery->first();
                    // ->where('user_spouses.id', $devoteeId)
                    // ->first();

    if ($cartDetails) {

        $gotramId = $devoteeId;
        $gothram = $cartDetails->gothram;
        $devoteName = $cartDetails->devote_name;
        $spouseName = $cartDetails->spouse_name;
        $date = $cartDetails->start_date;
        $amount = $cartDetails->amount;

        $eventId = $cartDetails->event_id;
        $eventName = $cartDetails->event_name;
         $eventDate = $cartDetails->event_date;
        

        // Return or process the data as required
        return response()->json([
            'gotram_id' => $gotramId,
            'gothram' => $gothram,
            'devote_name' => $devoteName,
            'spouse_name' => $spouseName,
            
            'event_id' => $eventId,
            'event_name' => $eventName,
            'amount' => $amount,
            'start_date' => $eventDate,

        ]);
    } else {

        return response()->json([
            'message' => 'No data found'
        ], 404);
    }

}elseif($gCount>0 && $cartCount > 0 && $status == 1){
       $data = DB::table('event_common')
                ->select('user_spouses.*', 'event_common.*', 'event_cart.id AS cart_id','event_cart.event_id','event_cart.amount', 'events.event_name_en AS event_name','event.id AS event_id','event.start_date AS event_date')
                ->join('user_spouses', 'event_common.gotram_id', '=', 'user_spouses.id')
                ->join('event_cart', 'event_common.cart_id', '=', 'event_cart.id')
                ->join('events', 'event_cart.event_id', '=', 'events.id')
                ->where('event_common.user_id', $uId)
                ->where('event_common.deleted_flag', NULL)
                ->first();

    if ($data) {
        // Prepare the response
        $response = [
            'user_spouse' => [
                //'gotram_id' => $data->id,
                'gothram' => $data->gothram,
                'devote_name' => $data->devote_name,
                'spouse_name' => $data->spouse_name,
                'start_date' => $data->start_date,
                // Add other fields from user_spouses table as needed
            ],
            'event_cart' => [
                'cart_id' => $data->cart_id,
                'event_id' => $data->event_id,
                'event_name' => $data->event_name,
                'amount' => $data->amount,
                 'start_date' => $data->event_date,
                // Add other fields from pooja_cart table as needed
            ]
        ];

        // Return the response
        return response()->json($response);
    } else {
        return response()->json([
            'message' => 'No data found'
        ], 404);
    }
}
}
   


public function Event_bank_response(Request $request)
{
    return [
        'responseCode' => 'failed',
        // 'bank_transaction_id' =>'1212',
        // 'key'=> 'abcd-1212',
        'responseMsg' => 'Event payment recorded successfully',
    ];
}

public function Event_generate_payment_transaction_id(Request $request)
{

    $currentDate = date('Ymd');
    $randomNumber = mt_rand(1000, 9999);
    $transactionId = $currentDate . $randomNumber;

    return $transactionId;
}

//Api For Payments

public function eventPayments1(Request $request)
{

    // Generate payment transaction ID
    $transactionId = $this->generate_payment_transaction_id($request);

    // Insert pooja payment record
    $paymentId = DB::table('payments')->insertGetId([
        'user_id' => $request->input('user_id'),
        'booking_id'=> $request->input('booking_id'),
        'type' => 'Event',
        'payment_method' => $request->input('payment_method'),
        'name_on_card' => $request->input('name_on_card'),
        'expire_date' => $request->input('expire_date'),
        'card_number' => $request->input('card_number'),
        'cvv' => $request->input('cvv'),
        'devotee_name' => $request->input('devotee_name'),
        'address' => $request->input('address'),
        'city' => $request->input('city'),
        'state' => $request->input('state'),
        'country' => $request->input('country'),
        'zip' => $request->input('zip'),
        'payment_amount' => $request->input('payment_amount'),
        'payment_generate_transaction_id' => $transactionId,

        // Add other relevant payment details here
    ]);

     $bankResponse = $this->bank_response($request);

    // Insert bank response into payment history
    DB::table('payments_history')->insert([
        'payment_id' => $paymentId,
        'bank_response' => json_encode([
            'status' => $bankResponse['status'],
            'bank_transaction_id' => $bankResponse['bank_transaction_id'],
            'key' => $bankResponse['key'],
            'message' => $bankResponse['message'],
        ]),
    ]);

    // Check if bank response status is success
    if ($bankResponse['status'] === 'success') {

        $bookingId = $request->input('booking_id');
        $eventid = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
        DB::table('events')->where('id', $eventid)->decrement('capacity', 1);
    }

    return response()->json([
        'responseCode' => '200',
        //'transaction_id' => $transactionId,
        'responseMsg' => 'Event payment recorded successfully',
    ]);
}

public function eventPayments(Request $request)
{


 $bookingId = DB::table('event_bookings')->insertGetId([
        'event_id' => $request->input('event_id'),
        'user_id' => $request->input('user_id'),
        //'pooja_time' => $request->input('pooja_time'),
    ]);
    
    $gotramId = $request->input('gotram_id');
    
       $gotram = DB::table('user_spouses')->where('id', $gotramId)
                            ->first();
        $dn = $gotram->devote_name ?? null;
        $gt = $gotram->gothram ?? null;
    
    // $poojaService = DB::table('poojaservices')->where('id',$request->input('pooja_service_id'))->get();
         $event= DB::table('events')->where('id', $request->input('event_id'))->first();


        $ename = $event->event_name_en ?? null;
        $img = $event->event_img ?? null;
        $des = $event->description_en ?? null;
        $date = $event->start_date ?? null;
       // $frequency = $event->frequency ?? null;
       // $pd = $event->prasad_delivery ?? null;
    // Generate payment transaction ID
    $transactionId = $this->generate_payment_transaction_id($request).$bookingId;

    // Insert pooja payment record
    $paymentId = DB::table('payments')->insertGetId([
        'user_id' => $request->input('user_id'),
        'booking_id'=> $bookingId,
        
        'type' => 'Event',
        'payment_method' => $request->input('payment_method'),
        'name_on_card' => $request->input('name_on_card'),
        'expire_date' => $request->input('expire_date'),
        'card_number' => $request->input('card_number'),
        'cvv' => $request->input('cvv'),
        'devotee_name' => $request->input('devotee_name'),
        'address' => $request->input('address'),
        'city' => $request->input('city'),
        'state' => $request->input('state'),
        'country' => $request->input('country'),
        'zip' => $request->input('zip'),
        'payment_amount' => $request->input('payment_amount'),
        'payment_generate_transaction_id' => $transactionId,

        // Add other relevant payment details here
    ]);

     $bankResponse = $this->bank_response($request);

    // Insert bank response into payment history
    DB::table('payments_history')->insert([
        'payment_id' => $paymentId,
        'bank_response' => json_encode([
            'status' => $bankResponse['status'],
            'bank_transaction_id' => $bankResponse['bank_transaction_id'],
            'key' => $bankResponse['key'],
            'message' => $bankResponse['message'],
        ]),
    ]);

    // Check if bank response status is success
    if ($bankResponse['status'] === 'success') {

        //$bookingId = $request->input('booking_id');
        $eventid = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
        //DB::table('events')->where('id', $eventid)->decrement('capacity', 1);



         $eventId = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
        
        // DB::table('poojaservices')->where('id', $poojaServiceId)->decrement('capacity', 1);
        DB::table('event_bookings')->where('id', $bookingId)->update([
        'ticket' => $transactionId,
       ]);
       
        DB::table('event_common')->where('user_id', $request->input('user_id'))->update([
        'booking_id' => $bookingId,
        'status' => '2',
       ]);
    }

    return response()->json([
        'responseCode' => '200',
        //'transaction_id' => $transactionId,
        'responseMsg' => 'Event payment recorded successfully',
        'user_id' =>$request->input('user_id'),
        'event_name' => $ename,
        'image' =>$img,
        'event_description' =>$des,
        'start_date' =>$date,
        'devote_name'=>$dn,
        'gotram' =>$gt,
        'ticket' => $transactionId,
    ]);
}

public function removeEvent(Request $request)
{
      $cid = $request->input('cart_id');
       $gid = $request->input('gotram_id');
        DB::table('event_cart')
            ->where('id', $cid)
            ->update([
                'deleted_flag' => '1',
               
            ]);

         DB::table('user_spouses')
            ->where('id', $gid)
            ->where('type','event')
            ->update([
                'deleted_flag' => '1',
               
            ]);
    DB::table('event_common')
            ->where('cart_id', $cid)
            ->update([
                'status' => '3',
               
            ]);
            
             return response()->json([
                 'responceCode'=> '200',
            'responceMsg' => 'Cart items removed successfully'
        ]);
        
}

//Events
// public function getAllEvent($page_number = 1, $count = 0, $lang = '')
// {
//     $section_title = "Events";
//     if ($page_number < 1) {
//         $page_number = 1;
//     }
//     Paginator::currentPageResolver(function () use ($page_number) {
//         return $page_number;
//     });

//     $events = DB::table('events')->orderBy('created_at', 'desc');

//     if ($count > 0) {
//         $events = $events->paginate($count);
//     } else {
//         $events = $events->get();
//     }

//     if ($events instanceof \Illuminate\Pagination\AbstractPaginator || $events instanceof \Illuminate\Pagination\LengthAwarePaginator) {
//         // Paginator instance
//         if ($events->total() > 0) {
//             // Process paginated results
//             $response_details = [];
//             $sl = 1;
//             foreach ($events as $event) {
//                 // By Language
//                 $lang = $this->getLanguage($lang);
//                 $title_var = "event_name_$lang";
//                 $title_var2 = "event_name_" . env('DEFAULT_LANGUAGE');
//                 $content_var = "description_$lang";
//                 $content_var2 = "description_" . env('DEFAULT_LANGUAGE');

//                 // Handle language variation
//                 if ($event->$title_var != "") {
//                     $event_title = $event->$title_var;
//                 } else {
//                     $event_title = $event->$title_var2;
//                 }

//                 if ($event->$content_var != "") {
//                     $event_content = $event->$content_var;
//                 } else {
//                     $event_content = $event->$content_var2;
//                 }

//                 $response_details[] = [
//                     'slno' => $sl,
//                     'Title' => $event_title,
//                     'Description' => $event_content,
//                     'Amount' => $event->event_price,
//                     'Capacity' => $event->capacity,
//                 ];
//                 $sl++;
//             }

//             // Response MSG
//             $response = [
//                 'responseCode' => 200,
//                 "responseMsg" => "data fetched",
//                 'title' => $section_title,
//                 'data_count' => $events->total(),
//                 'data' => ['records' => $response_details]
//             ];
//             return response()->json($response, 200);
//         } else {
//             // Handle empty paginated results
//             $response = [
//                 "responseCode" => 201,
//                 'responseMsg' => 'There is no data',
//                 'title' => $section_title,
//                 'data' => []
//             ];
//             return response()->json($response, 200);
//         }
//     } elseif ($events instanceof \Illuminate\Support\Collection) {
//         // Collection instance
//         if ($events->count() > 0) {
//             // Process non-paginated results
//             $response_details = [];
//             $sl = 1;
//             foreach ($events as $event) {
//                 // By Language
//                 $lang = $this->getLanguage($lang);
//                 $title_var = "event_name_$lang";
//                 $title_var2 = "event_name_" . env('DEFAULT_LANGUAGE');
//                 $content_var = "description_$lang";
//                 $content_var2 = "description_" . env('DEFAULT_LANGUAGE');

//                 // Handle language variation
//                 if ($event->$title_var != "") {
//                     $event_title = $event->$title_var;
//                 } else {
//                     $event_title = $event->$title_var2;
//                 }

//                 if ($event->$content_var != "") {
//                     $event_content = $event->$content_var;
//                 } else {
//                     $event_content = $event->$content_var2;
//                 }

//                 $response_details[] = [
//                     'slno' => $sl,
//                     'EventId' => $event->id,
//                     'Title' => $event_title,
//                     'Description' => $event_content,
//                     'EventDate' =>  $event->event_date,
//                     'EventTime' => $event->event_time,
//                     'EventDay' => $event->event_day,
//                     'start_date' => $event->start_date,
//                     'Image' => $event->event_img,
//                     'Amount' => $event->event_price,
//                     'Capacity' => $event->capacity,
//                 ];
//                 $sl++;
//             }

//             // Response MSG
//             $response = [
//                 'responseCode' => 200,
//                 "responseMsg" => "data fetched",
//                 'title' => $section_title,
//                 'data_count' => $events->count(),
//                 'data' => ['records' => $response_details]
//             ];
//             return response()->json($response, 200);
//         } else {
//             // Handle empty non-paginated results
//             $response = [
//                 "responseCode" => 201,
//                 'responseMsg' => 'There is no data',
//                 'title' => $section_title,
//                 'data' => []
//             ];
//             return response()->json($response, 200);
//         }
//     } else {
//         // Handle other cases (e.g., if $pujas is null or not an expected type)
//         $response = [
//             "responseCode" => 500,
//             'responseMsg' => 'Unexpected error occurred',
//             'title' => $section_title,
//             'data' => []
//         ];
//         return response()->json($response, 500);
//     }
// }

public function getAllEvent($page_number = 1, $count = 0)
{
    $section_title = "Events";
    if ($page_number < 1) {
        $page_number = 1;
    }
    Paginator::currentPageResolver(function () use ($page_number) {
        return $page_number;
    });

    $events = DB::table('events')->orderBy('created_at', 'desc');

    if ($count > 0) {
        $events = $events->paginate($count);
    } else {
        $events = $events->get();
    }

    if ($events instanceof \Illuminate\Pagination\AbstractPaginator || $events instanceof \Illuminate\Pagination\LengthAwarePaginator) {
        // Paginator instance
        if ($events->total() > 0) {
            $response_details = [];
            $sl = 1;
            foreach ($events as $event) {
                $response_details[] = [
                    'slno' => $sl,
                    'Title' => $event->event_name,
                    'Description' => $event->description,
                    'Amount' => $event->event_price,
                    'Capacity' => $event->capacity,
                ];
                $sl++;
            }

            $response = [
                'responseCode' => 200,
                "responseMsg" => "data fetched",
                'title' => $section_title,
                'data_count' => $events->total(),
                'data' => ['records' => $response_details]
            ];
            return response()->json($response, 200);
        } else {
            $response = [
                "responseCode" => 201,
                'responseMsg' => 'There is no data',
                'title' => $section_title,
                'data' => []
            ];
            return response()->json($response, 200);
        }
    } elseif ($events instanceof \Illuminate\Support\Collection) {
        // Collection instance
        if ($events->count() > 0) {
            $response_details = [];
            $sl = 1;
            foreach ($events as $event) {
                $response_details[] = [
                    'slno' => $sl,
                    'EventId' => $event->id,
                    'Title' => $event->event_name,
                    'Description' => $event->description,
                    'EventDate' =>  $event->event_date,
                    'EventTime' => $event->event_time,
                    'EventDay' => $event->event_day,
                    'start_date' => $event->start_date,
                    'Image' => $event->event_img,
                    'Amount' => $event->event_price,
                    'Capacity' => $event->capacity,
                ];
                $sl++;
            }

            $response = [
                'responseCode' => 200,
                "responseMsg" => "data fetched",
                'title' => $section_title,
                'data_count' => $events->count(),
                'data' => ['records' => $response_details]
            ];
            return response()->json($response, 200);
        } else {
            $response = [
                "responseCode" => 201,
                'responseMsg' => 'There is no data',
                'title' => $section_title,
                'data' => []
            ];
            return response()->json($response, 200);
        }
    } else {
        $response = [
            "responseCode" => 500,
            'responseMsg' => 'Unexpected error occurred',
            'title' => $section_title,
            'data' => []
        ];
        return response()->json($response, 500);
    }
}

   public function register(Request $request)
    {
        // Validate incoming request
        $validator = Validator::make($request->all(),[
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users_details,email',
            'phone_no' => 'required|string|max:20',
            'address' => 'required|string|max:255',
            'password' => 'required|string|min:6|confirmed',
        ]);

		if ($validator->fails()) {
       return response()->json([
				'responseCode' => '400',
				'responseMsg' => $validator->errors(),
                'data' => ['records' => $response_details],
                
            ]);
    }else{

   $data = DB::table('users_details')->insert([
   
        'name' => $request->input('name'),
        'email' => $request->input('email'),
        'phone_no' => $request->input('phone_no'),
        'address' => $request->input('address'),
        'password' => Hash::make($request->input('password')),
        'created_at' => now(),
        'updated_at' => now(),
    ]);
        // Return success response
         return response()->json([
				'responseCode' => '200',
				'responseMsg' => 'User Register successfully',
                //'data' => $data,
                
            ]);
}
    }
    


//GetAllPrist APi
public function getAllPrist(Request $request)
{
    
    
     $prists= DB::table('prist')->get();
     $pristData = [];

    foreach ($prists as $prist) {
        $photoData[] = [
            'id' => $prist->id,
            'title' => $prist->title_en,
            'content' =>$prist->prist_description_en,
            'photo' => ($prist->image != "") ? url("") . "/uploads/Priest/" . $prist->image : null,
        ];
    }

    return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'Priest fetched successfully',
        'data' => $photoData,
    ]);
    
    
 
       
}


public function getAllPristDetails(Request $request)
{
    
    
     $prists= DB::table('prist_details')->get();
     $pristData = [];

    foreach ($prists as $prist) {
        $photoData[] = [
            'id' => $prist->id,
            'title' => $prist->name_en,
            'content' =>$prist->content_en,
            'contact' =>$prist->contact,
            'photo' => ($prist->image != "") ? url("") . "/uploads/Priest/" . $prist->image : null,
        ];
    }

    return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'Priest fetched successfully',
        'data' => $photoData,
    ]);
    
    
    $prist = DB::table('prist')->get();

    if ($prist->isEmpty()) {
       
        return response()->json([
            'responseCode' => '201',
            'responseMsg' => 'No data found'
        ], 201);
    }

    
    return response()->json([
        'responseCode' => '200',
        'data' => $prist,
        'responseMsg' => 'Prist data  fetched successfully'
    ]);

    
       
}

public function getAllPristDetailsById(Request $request)
{
    
    $id = $request->input('id');
     $prists= DB::table('prist_details')->where('id',$id)->get();
     $pristData = [];

    foreach ($prists as $prist) {
        $photoData[] = [
            'id' => $prist->id,
            'title' => $prist->name_en,
            'content' =>$prist->content_en,
            'contact' =>$prist->contact,
            'photo' => ($prist->image != "") ? url("") . "/uploads/Priest/" . $prist->image : null,
        ];
    }

    return response()->json([
        'responseCode' => '200',
        'responseMsg' => 'Priest fetched successfully',
        'data' => $photoData,
    ]);
    
    
    $prist = DB::table('prist')->get();

    if ($prist->isEmpty()) {
       
        return response()->json([
            'responseCode' => '201',
            'responseMsg' => 'No data found'
        ], 201);
    }

    
    return response()->json([
        'responseCode' => '200',
        'data' => $prist,
        'responseMsg' => 'Prist data  fetched successfully'
    ]);

    
       
}
public function templeClosingStatus(Request $request)
{
    $currentDate = now();
    $closingStatus = DB::table('closing_status')
                ->whereDate('closing_from_date', '<=', $currentDate)
                ->whereDate('closing_to_date', '>=', $currentDate)
                ->first();
      $start_date = $closingStatus->closing_from_date; 
      $end_date = $closingStatus->closing_to_date; 
    
    $announcement = $closingStatus ? $closingStatus->announcement : null;
    
    $Count = $closingStatus ? 1 : 0;

    return response()->json([
        'responseCode' => '200',
        'responseMsg' => $Count ? 'Servic
        e not available' : 'Service available',
        'Count' => $Count,
        'announcement' => $announcement,
        'start_date' =>$start_date,
        'end_date' => $end_date,
        
    ]);
}

public function getCountries()
{
    try {
        $countrie = DB::table('countrie')->get();

        if ($countrie->isEmpty()) {
            return response()->json([]);
        }

        return response()->json([
            'countrie' => $countrie,
            'message' => 'Countries retrieved successfully.'
        ], 200);
    } catch (\Exception $e) {
        return response()->json(['error' => 'Failed to fetch countries: ' . $e->getMessage()], 500);
    }
}

public function getStatesByCountryId(Request $request)
    {
        $countryId = $request->input('country_id');

        $states = DB::table('states')
                    ->join('countrie', 'states.country_id', '=', 'countrie.country_id')
                    ->where('states.country_id', $countryId)
                    ->get(['states.*']);

        if ($states->isEmpty()) {
            return response()->json([]);
        }

        $requestCount = $request->session()->get('request_count', 0);
        $request->session()->put('request_count', ++$requestCount);

        return response()->json([
            'states' => $states,
            'message' => 'States retrieved successfully.',
            'request_count' => $requestCount
        ], 200);
    }


    public function getCitiesByStateId(Request $request)
{
    try {
        $stateId = $request->input('state_id');

        $cities = DB::table('cities')
                    ->join('states', 'cities.state_id', '=', 'states.state_id')
                    ->where('cities.state_id', $stateId)
                    ->get(['cities.*']);

        if ($cities->isEmpty()) {
            return response()->json([]);
        }

        $requestCount = $request->session()->get('request_count', 0);
        $request->session()->put('request_count', ++$requestCount);

        return response()->json([
            'cities' => $cities,
            'message' => 'Cities retrieved successfully.',
            'request_count' => $requestCount
        ], 200);
    } catch (\Exception $e) {
        return response()->json(['error' => 'Failed to fetch cities: ' . $e->getMessage()], 500);
    }
}

/////////
public function userRegister(Request $request)
    {
        $existingUser = DB::table('users_details')->where('email', $request->input('email'))->first();
   
   
   // $userId =$existingUser->id;

    if ($existingUser) {
        return response()->json([
            'responseCode' => '400',
            'responseMsg' => 'Email already exists',
        ], 400);
    }else{
        
        $name = $request->input('firstname') . ' ' . $request->input('lastname');
        $email = $request->input('email');
        $phoneNo = $request->input('phone_no');
        $password = Hash::make($request->input('password'));
        $status = 1;
        $createdAt = now();

      $id =   DB::table('users_details')->insertGetId([
            'name' => $name,
            'email' => $email,
            'phone_no' => $phoneNo,
            'password' => $password,
            'status' => $status,
            'created_at' => $createdAt,
        ]);

        return response()->json([
            'responceCode' => '200',
            'responceMsg' => 'User registered successfully',
            'user_id'=>$id,
            'name' => $name,
            'email' => $email,
            'phone_no' => $phoneNo,

            ]);
    }
    }

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

        $user = DB::table('users_details')
            ->where('email', $request->input('email'))
            ->where('status', 1)
            ->first();
            
          $id = $user->id;
          $name = $user->name;
          $email = $user->email;
          $phone = $user->phone_no;

        if (!$user ) {
            return response()->json(['error' => 'Please enter your correct email '], 401);
        }

        // $token = $user->createToken('authToken')->plainTextToken;
        // return response()->json(['token' => $token], 200);
        return response()->json([
            'responceCode' =>'200',
            'responceMsg' => 'User login successfully',
            'user_id' => $id ,
            'name'=>$name,
            'email' =>$email,
            'phone_no' =>$phone
            ]);

    }
    
//Kitchen
    
//getAllkitchen API
public function getAllkitchen(Request $request)
{
    
    $kitchen = DB::table('master_kitchen')->get();

    if ($kitchen->isEmpty()) {
       
        return response()->json([
            'responseCode' => '201',
            'ResponseMsg' => 'No data found'
        ], 201);
    }
    
    return response()->json([
        'responseCode' => '200',
        'data' => $kitchen,
        'ResponseMsg' => 'Kitchen data fetched successfully'
    ]);
}

public function kitchenAddToCart(Request $request)
{
    $itemId = $request->input('item_id');
    $kitemId = $request->input('master_item_id');
    $kiprice = $request->input('price');
    $cartId = $request->input('cart_id');
    $data = [
        'description' => 'test',
    ];
    
   $existingItem = DB::table('cart_items')
    ->where('item_id', $itemId)
    ->where('master_item_id', $kitemId)
    ->first();

if ($existingItem) {
   
    return response()->json([
        'responceCode' => '201',
        'message' => 'Item already added in cart',
       
    ]);
} else {
     if (empty($itemId) || $itemId == '0') {
        DB::table('items')->insert($data);
        $itemId = DB::getPdo()->lastInsertId();
    } else {
        DB::table('items')->where('id', $itemId)->update($data);
    }

    // Prepare data for insertion into cart_items
    $data2 = [
        'master_item_id' => $request->input('master_item_id'),
        'price' => $request->input('price'),
        'quantity' => $request->input('quantity'),
        'item_id' => $itemId // Use $itemId here
    ];

    // Check if cart_id is provided
    if ($cartId) {
        // If provided, update the cart item
        DB::table('cart_items')->where('id', $cartId)->update($data2);
    } else {
        // If not provided, insert a new cart item and retrieve the cart_id
        $cartId = DB::table('cart_items')->insertGetId($data2);
    }

    // Return the response with the cart_id
    return response()->json([
        'responceCode' => '200',
        'message' => 'Data inserted or updated successfully',
        'item_id' => $itemId,
        'cart_id' => $cartId
    ]);
}
    
}

public function kitchenGetCartData(Request $request)
{
    $Id = $request->input('item_id'); 
   $items = DB::table('cart_items')
            ->select('cart_items.id AS cart_id','cart_items.id AS cart_id','cart_items.item_id','cart_items.price','cart_items.quantity','cart_items.master_item_id','master_kitchen.id','master_kitchen.item_name','master_kitchen.image')
            ->join('master_kitchen', 'cart_items.master_item_id', '=', 'master_kitchen.id')
            ->where('item_id',$Id)
            ->where('cart_items.deleted_flag','0')
            ->get();
    
     return response()->json([
        'responseCode' => '200',
         'ResponseMsg' => 'Kitchen Data fetched successfully',
        'data' => $items,
       
    ]);
}

public function getkitchenById(Request $request)
{

    $validator = Validator::make($request->all(), [
        'kitchen_id' => 'required|integer', 
    ]);

    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }else{
        $Id = $request->input('kitchen_id'); 
        $kitchen = DB::table('master_kitchen')->where('id', $Id)->get();
    }

    if ($kitchen->isEmpty()) {
        
        return response()->json([
            'responseCode' => '201',
            'message' => ' No data found '
        ], 201);

    } elseif( $Id == NULL){
        return response()->json([
            'responseCode' => '202',
            'ResponseMsg' => 'data Not Found'
        ]);
    }
  
    return response()->json([
        'responseCode' => '200',
        'data' => $kitchen,
        'ResponseMsg' => 'Kitchen ID fetched successfully'
    ]);
}


public function itemRemove(Request $request)
{
    $itemId = $request->input('item_id');
    $cartId = $request->input('cart_id');
   // $userId = $request->input('user_id');
    if (!empty($cartId)&& !empty($itemId)) {
    DB::table('cart_items')->where('id',$cartId )->where('item_id',$itemId )->update([
        'deleted_flag' => '1',

        ]);
       
        }elseif(!empty($itemId)){

    DB::table('items')->where('id',$itemId)->update([
        'deleted_flag' => '1',
         ]);

         DB::table('cart_items')->where('item_id',$itemId)->update([
        'deleted_flag' => '1',
         ]);
        }
            
        return response()->json([
        'responceCode' => '200',
        'message' => 'Data Removed successfully',
       
    ]);
}

public function kitchenGetCartDataByUserId(Request $request)
{
     // Check if email already exists
    $existingUser = DB::table('users_details')->where('email', $request->input('email'))->first();
   
   
    //$userId =$existingUser->id;

    // if ($existingUser) {
    //     return response()->json([
    //         'responseCode' => '400',
    //         'responseMsg' => 'Email already exists',
    //     ], 400);
    // }
    
    $Id = $request->input('item_id'); 
   // $CId = $request->input('cart_id'); 
    $UId = $request->input('user_id'); 
    $u = DB::table('kitchen_common')->select('user_id')->where('user_id',$UId)->first();
    //print_r($u);exit;
    $itD = DB::table('kitchen_common')->select('item_id')->where('item_id',$Id)->first();
     //$eventid = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
     
     if($u && $itD){
         DB::table('kitchen_common')->update([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]); 
     }elseif(!$u && !$itD){
  DB::table('kitchen_common')->insert([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]);
     }elseif($u && !$itD){
  DB::table('kitchen_common')->insert([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]);
     }

//   $items = DB::table('kitchen_common')
//                     ->select('cart_items.*', 'kitchen_common.*','master_kitchen.id', 'master_kitchen.item_name', 'master_kitchen.image')
//                     ->join('cart_items','kitchen_common.cart_id', '=', 'cart_items.id')
//                     ->join('master_kitchen', 'cart_items.master_item_id', '=', 'master_kitchen.id')
//                     ->where('kitchen_common.cart_id', $CId)
//                     ->where('cart_items.deleted_flag', '0')
//                     ->get();
    
     return response()->json([
        'responseCode' => '200',
         'ResponseMsg' => 'Kitchen Data fetched successfully',
        //'data' => $items,
       
    ]);
}

public function getAlltempdetails(Request $request)
{

    $detl = DB::table('details')->get();

    if ($detl->isEmpty()) {

        return response()->json([
            'responseCode' => '201',
            'ResponseMsg' => 'No data found'
        ], 201);
    }

    return response()->json([
        'responseCode' => '200',
        'data' => $detl,
        'ResponseMsg' => 'Temple details data fetched successfully'
    ]);
}

public function kitchenPayments(Request $request)
{

 $bookingId = DB::table('kitchen_booking')->insertGetId([
        'item_id' => $request->input('item_id'),
        'user_id' => $request->input('user_id'),
        
    ]);
   
    
    // $poojaService = DB::table('poojaservices')->where('id',$request->input('pooja_service_id'))->get();
        //  $k= DB::table('items')->where('id', $request->input('item_id'))->first();


    $transactionId = $this->generate_payment_transaction_id($request).$bookingId;

    // Insert pooja payment record
    $paymentId = DB::table('payments')->insertGetId([
        'user_id' => $request->input('user_id'),
        'booking_id'=> $bookingId,
        
        'type' => 'Kitchen',
        'payment_method' => $request->input('payment_method'),
        'name_on_card' => $request->input('name_on_card'),
        'expire_date' => $request->input('expire_date'),
        'card_number' => $request->input('card_number'),
        'cvv' => $request->input('cvv'),
        'devotee_name' => $request->input('devotee_name'),
        'address' => $request->input('address'),
        'city' => $request->input('city'),
        'state' => $request->input('state'),
        'country' => $request->input('country'),
        'zip' => $request->input('zip'),
        'payment_amount' => $request->input('payment_amount'),
        'payment_generate_transaction_id' => $transactionId,

        // Add other relevant payment details here
    ]);

     $bankResponse = $this->bank_response($request);

    // Insert bank response into payment history
    DB::table('payments_history')->insert([
        'payment_id' => $paymentId,
        'bank_response' => json_encode([
            'status' => $bankResponse['status'],
            'bank_transaction_id' => $bankResponse['bank_transaction_id'],
            'key' => $bankResponse['key'],
            'message' => $bankResponse['message'],
        ]),
    ]);

    // Check if bank response status is success
    if ($bankResponse['status'] === 'success') {

        //$bookingId = $request->input('booking_id');
        $kid = DB::table('kitchen_booking')->where('id', $bookingId)->value('item_master_id');
        //DB::table('events')->where('id', $eventid)->decrement('capacity', 1);

         $kId = DB::table('kitchen_booking')->where('id', $bookingId)->value('item_master_id');
        
        // DB::table('poojaservices')->where('id', $poojaServiceId)->decrement('capacity', 1);
        DB::table('kitchen_booking')->where('id', $bookingId)->update([
        'ticket' => $transactionId,
       ]);
       
        DB::table('kitchen_common')->where('user_id', $request->input('user_id'))->update([
        'booking_id' => $bookingId,
        'status' => '2',
       ]);
    }

    return response()->json([
        'responseCode' => '200',
        //'transaction_id' => $transactionId,
        'responseMsg' => 'Item payment recorded successfully',
        'user_id' =>$request->input('user_id'),
        'item_id' =>$request->input('item_id'),
        'booking_id'=>$bookingId,
        'ticket' => $transactionId,
        
    ]);
}

public function kitchenDataAfterPayment(Request $request)
{
    $uId = $request->input('user_id');
    $itId = $request->input('item_id');
    $bId = $request->input('booking_id');
    
    $data = DB::table('kitchen_common')
            ->select('kitchen_common.*','cart_items.*','master_kitchen.*')
            ->join('cart_items', 'kitchen_common.item_id', '=', 'cart_items.item_id')
            ->join('master_kitchen','cart_items.master_item_id', '=', 'master_kitchen.id')
            ->where('kitchen_common.booking_id',$bId)
             ->where('kitchen_common.item_id',$itId)
              ->where('kitchen_common.user_id', $uId)
            ->where('cart_items.deleted_flag','0')
            ->where('kitchen_common.status','2')
            ->get();
            
    return response()->json([
        'responseCode' => '200',
      'responseMsg' => 'Data fetched successfully',
      'data' =>$data,
        
    ]);  
}



	
	


// public function pujaAddToCart(Request $request)
// {
//     $itemId = $request->input('item_id');
//     $puja_service_id = $request->input('puja_service_id');
//     $devottee_name = $request->input('devottee_name');
//     $gotram = $request->input('gotram');
//     $spouse_name = $request->input('spouse_name');
//     $start_date = $request->input('start_date');

//     $familyMemberData = $request->input('family_members');

//     $data = [
//         'description' => 'test',
//     ];

//     $existingItem = DB::table('puja_cart')
//         ->where('item_id', $itemId)
//         ->where('puja_service_id', $puja_service_id)
//         ->first();

//     if ($existingItem) {
//         return response()->json([
//             'responceCode' => '201',
//             'message' => 'Puja Service already added in cart',
//         ]);
//     } else {
//         if (empty($itemId) || $itemId == '0') {
//             DB::table('puja_items')->insert($data);
//             $itemId = DB::getPdo()->lastInsertId();
//         } else {
//             DB::table('puja_items')->where('id', $itemId)->update($data);
//         }

//         $data2 = [
            
//             'puja_service_id' => $puja_service_id,
//             'devottee_name' => $devottee_name,
//             'gotram' => $gotram,
//             'spouse_name' => $spouse_name,
//             'start_date' => $start_date,
//             'family_members' => json_encode($familyMemberData),
//         ];

//         // Check if cart_id is provided
//         $cartId = $request->input('cart_id');
//         if ($cartId) {
//             // If provided, update the cart item
//             DB::table('puja_cart')->where('id', $cartId)->update($data2);
//         } else {
//             // If not provided, insert a new cart item and retrieve the cart_id
//             $cartId = DB::table('puja_cart')->insertGetId($data2);
//         }

//         // Return the response with the cart_id
//         return response()->json([
//             'responceCode' => '200',
//             'message' => 'Data inserted or updated successfully',
//             'item_id' => $itemId,
//             'cart_id' => $cartId
//         ]);
//     }
// }

public function pujaAddToCart(Request $request)
{
    $itemId = $request->input('item_id');
    $puja_service_id = $request->input('puja_service_id');
    $devottee_name = $request->input('devote_name');
    $gotram = $request->input('gothram');
    $spouse_name = $request->input('spouse_name');
    $start_date = $request->input('start_date');
    $amount = $request->input('amount');
    $pd = $request->input('puja_duration');
    //$frequency = $request->input('frequency');

    // Get family members data as an array
    $familyMembers = $request->input('family_member_name');

    $data = [
        'description' => 'test',
    ];

    $existingItem = DB::table('puja_cart')
        ->where('item_id', $itemId)
        ->where('puja_service_id', $puja_service_id)
        ->where('deleted_flag','0')
        ->first();

    if ($existingItem) {
        return response()->json([
            'responceCode' => '201',
            'message' => 'Puja Service already added in cart',
        ]);
    } else {
        // Insert or update puja items
        if (empty($itemId) || $itemId == '0') {
            DB::table('puja_items')->insert($data);
            $itemId = DB::getPdo()->lastInsertId();
        } else {
            DB::table('puja_items')->where('id', $itemId)->update($data);
        }

        $data2 = [
            'item_id' =>$itemId,
            'puja_service_id' => $puja_service_id,
            'devottee_name' => $devottee_name,
            'gotram' => $gotram,
            'spouse_name' => $spouse_name,
            'start_date' => $start_date,
            'add_family_members' => json_encode($familyMembers), // Encode family members array to JSON
            'amount' => $amount,
            'puja_duration' => $pd,
        ];

        // Check if cart_id is provided
        $cartId = $request->input('cart_id');
        if ($cartId) {
            // If provided, update the cart item
            DB::table('puja_cart')->where('id', $cartId)->update($data2);
        } else {
            // If not provided, insert a new cart item and retrieve the cart_id
            $cartId = DB::table('puja_cart')->insertGetId($data2);
        }

        // Return the response with the cart_id
        return response()->json([
            'responseCode' => '200',
            'message' => 'Data inserted or updated successfully',
            'item_id' => $itemId,
            'cart_id' => $cartId
        ]);
    }
}

public function PujaGetCartData(Request $request)
{
    $Id = $request->input('item_id'); 
   $items = DB::table('puja_cart')
            ->select('puja_cart.id AS cart_id','puja_cart.item_id','puja_cart.puja_service_id','puja_cart.devottee_name','puja_cart.amount','puja_cart.gotram','puja_cart.spouse_name','puja_cart.start_date','poojaservices.name_en As pujaService','poojaservices.id As puja_serice_id')
            ->join('poojaservices', 'puja_cart.puja_service_id', '=', 'poojaservices.id')
            ->where('puja_cart.item_id',$Id)
            ->where('puja_cart.deleted_flag','0')
            ->get();
    
     return response()->json([
        'responseCode' => '200',
         'ResponseMsg' => 'Puja Data fetched successfully',
        'data' => $items,
       
    ]);
}

public function PujaitemRemove(Request $request)
{
    $itemId = $request->input('item_id');
    $cartId = $request->input('cart_id');
   // $userId = $request->input('user_id');
   
    if (!empty($cartId)&& !empty($itemId)) {
    DB::table('puja_cart')->where('id',$cartId )->where('item_id',$itemId )->update([
        'deleted_flag' => '1',

        ]);
       
        }elseif(!empty($itemId) && empty($cartId) ){

    DB::table('puja_items')->where('id',$itemId)->update([
        'deleted_flag' => '1',
         ]);

         DB::table('puja_cart')->where('item_id',$itemId)->update([
        'deleted_flag' => '1',
         ]);
        }
            
        

        return response()->json([
        'responceCode' => '200',
        'message' => 'Data Removed successfully',
       
    ]);
}

public function PujaGetCartDataByUserId(Request $request)
{
     // Check if email already exists
    $existingUser = DB::table('users_details')->where('email', $request->input('email'))->first();
   
   
    //$userId =$existingUser->id;

    // if ($existingUser) {
    //     return response()->json([
    //         'responseCode' => '400',
    //         'responseMsg' => 'Email already exists',
    //     ], 400);
    // }
    
    
    
    $Id = $request->input('item_id'); 
   // $CId = $request->input('cart_id'); 
    $UId = $request->input('user_id'); 
    $u = DB::table('pooja_common')->select('user_id')->where('user_id',$UId)->first();
    //print_r($u);exit;
    $itD = DB::table('pooja_common')->select('item_id')->where('item_id',$Id)->first();
     //$eventid = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
     
     if($u && $itD){
         DB::table('pooja_common')->update([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]); 
     }elseif(!$u && !$itD){
  DB::table('pooja_common')->insert([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]);
     }elseif($u && !$itD){
  DB::table('pooja_common')->insert([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]);
     }


     return response()->json([
        'responseCode' => '200',
         'ResponseMsg' => 'Kitchen Data fetched successfully',
      
       
    ]);
}

public function PujaPayments(Request $request)
{


 $bookingId = DB::table('poojabookings')->insertGetId([
        'item_id' => $request->input('item_id'),
        'user_id' => $request->input('user_id'),
        
    ]);
   
    
    // $poojaService = DB::table('poojaservices')->where('id',$request->input('pooja_service_id'))->get();
        //  $k= DB::table('puja_items')->where('id', $request->input('item_id'))->first();


    $transactionId = $this->generate_payment_transaction_id($request).$bookingId;

    // Insert pooja payment record
    $paymentId = DB::table('payments')->insertGetId([
        'user_id' => $request->input('user_id'),
        'booking_id'=> $bookingId,
        
        'type' => 'Puja',
        'payment_method' => $request->input('payment_method'),
        'name_on_card' => $request->input('name_on_card'),
        'expire_date' => $request->input('expire_date'),
        'card_number' => $request->input('card_number'),
        'cvv' => $request->input('cvv'),
        'devotee_name' => $request->input('devotee_name'),
        'address' => $request->input('address'),
        'city' => $request->input('city'),
        'state' => $request->input('state'),
        'country' => $request->input('country'),
        'zip' => $request->input('zip'),
        'payment_amount' => $request->input('payment_amount'),
        'payment_generate_transaction_id' => $transactionId,

        // Add other relevant payment details here
    ]);

     $bankResponse = $this->bank_response($request);

    // Insert bank response into payment history
    DB::table('payments_history')->insert([
        'payment_id' => $paymentId,
        'bank_response' => json_encode([
            'status' => $bankResponse['status'],
            'bank_transaction_id' => $bankResponse['bank_transaction_id'],
            'key' => $bankResponse['key'],
            'message' => $bankResponse['message'],
        ]),
    ]);

    // Check if bank response status is success
    if ($bankResponse['status'] === 'success') {

        //$bookingId = $request->input('booking_id');
        $kid = DB::table('poojabookings')->where('id', $bookingId)->value('pooja_service_id');
        //DB::table('events')->where('id', $eventid)->decrement('capacity', 1);



         $kId = DB::table('poojabookings')->where('id', $bookingId)->value('pooja_service_id');
        
        // DB::table('poojaservices')->where('id', $poojaServiceId)->decrement('capacity', 1);
        DB::table('poojabookings')->where('id', $bookingId)->update([
        'ticket' => $transactionId,
        'user_id' =>$request->input('user_id'),
       ]);
       
        DB::table('pooja_common')->where('item_id',$request->input('item_id'))->where('user_id', $request->input('user_id'))->update([
        'booking_id' => $bookingId,
        'status' => '2',
       ]);
    }

    return response()->json([
        'responseCode' => '200',
        //'transaction_id' => $transactionId,
        'responseMsg' => 'Item payment recorded successfully',
        'user_id' =>$request->input('user_id'),
        'item_id' =>$request->input('item_id'),
        'booking_id'=>$bookingId,
        'ticket' => $transactionId,
        
    ]);
}

public function PujaDataAfterPayment(Request $request)
{
    $uId = $request->input('user_id');
    $itId = $request->input('item_id');
    $bId = $request->input('booking_id');
    
    $data = DB::table('pooja_common')
    ->select(
        'pooja_common.item_id','pooja_common.user_id','pooja_common.user_id','pooja_common.status',
        'poojaservices.name_en AS puja_service_name','poojaservices.description_en AS description','poojaservices.images',
        'puja_cart.devottee_name','puja_cart.gotram','puja_cart.spouse_name', 'puja_cart.add_family_members','puja_cart.start_date','puja_cart.amount','puja_cart.puja_duration',
        'pooja_common.id as pooja_common_id',
        'poojaservices.id as poojaservices_id',
        'puja_cart.id as puja_cart_id'
    )
    ->join('puja_cart', 'pooja_common.item_id', '=', 'puja_cart.item_id')
    ->join('poojaservices', 'puja_cart.puja_service_id', '=', 'poojaservices.id')
    ->where('pooja_common.booking_id', $bId)
    ->where('pooja_common.item_id', $itId)
    ->where('pooja_common.user_id', $uId)
    ->where('puja_cart.deleted_flag', '0')
    ->where('pooja_common.status', '2')
    ->get();

            
    return response()->json([
        'responseCode' => '200',
      'responseMsg' => 'Data fetched successfully',
      'data' =>$data,
       
        
    ]);  
}

public function EventAddToCart(Request $request)
{
    // Retrieve input values
    $itemId = $request->input('item_id');
    $event_id = $request->input('event_id');
    $devotee_name = $request->input('devottee_name');
    $gotram = $request->input('gotram');
    $amount = $request->input('amount');
    $spouse_name = $request->input('spouse_name');
    $start_date = $request->input('start_date');
 
    // Get family members data as an array
    $familyMembers = $request->input('family_member_name');
 
    // Prepare data for event_item table
    $eventData = [
        'description' => 'test',
    ];
 
    try {
        // Check if the event is already in the cart
        $existingItem = DB::table('events_cart')
            ->where('item_id', $itemId)
            ->where('event_id', $event_id)
            ->where('deleted_flag', '0')
            ->first();
 
        if ($existingItem) {
            return response()->json([
                'responseCode' => '201',
                'message' => 'Event already added in cart',
            ]);
        }
 
        // Insert or update event_item
        if (empty($itemId) || $itemId == '0') {
            DB::table('event_items')->insert($eventData);
            $itemId = DB::getPdo()->lastInsertId();
        } else {
            DB::table('event_items')->where('id', $itemId)->update($eventData);
        }
 
        // Prepare data for event_cart table
        $cartData = [
            'item_id' => $itemId,
            'event_id' => $event_id,
            'devotee_name' => $devotee_name,
            'gotram' => $gotram,
            'amount' => $amount,
            'spouse_name' => $spouse_name,
            'start_date' => $start_date,
           
            // Encode family members array to JSON
            'family_member_name' => json_encode($familyMembers),
        ];
 
        // Check if cart_id is provided
        $cartId = $request->input('cart_id');
        if ($cartId) {
            // If provided, update the cart item
            DB::table('events_cart')->where('id', $cartId)->update($cartData);
        } else {
            // If not provided, insert a new cart item and retrieve the cart_id
            $cartId = DB::table('events_cart')->insertGetId($cartData);
        }
 
        // Return the response with the cart_id
        return response()->json([
            'responseCode' => '200',
            'message' => 'Data inserted or updated successfully',
            'item_id' => $itemId,
            'cart_id' => $cartId
        ]);
 
    } catch (\Exception $e) {
        // Handle exceptions and return a proper response
        return response()->json([
            'responseCode' => '500',
            'message' => 'An error occurred: ' . $e->getMessage(),
        ], 500);
    }
}


public function EventGetCartData(Request $request)
{
    $itemId = $request->input('item_id');
 
    // Validate input
    if (!$itemId) {
        return response()->json([
            'responseCode' => '400',
            'ResponseMsg' => 'Item ID is required',
        ], 400);
    }
 
    $items = DB::table('events_cart')
        ->select(
            'events_cart.id AS cart_id',
            'events_cart.item_id',
            'events_cart.event_id',
            'events_cart.devotee_name',
            'events_cart.amount',
            'events_cart.gotram',
            'events_cart.spouse_name',
            'events_cart.start_date',
            'events.event_name_en AS events',
            'events.id AS event_id'
        )
        ->join('events', 'events_cart.event_id', '=', 'events.id') // Corrected the join table and column name
        ->where('events_cart.item_id', $itemId)
        ->where('events_cart.deleted_flag', '0')
        ->get();
 
    return response()->json([
        'responseCode' => '200',
        'ResponseMsg' => 'Event Data fetched successfully',
        'data' => $items,
    ]);
}

public function EventItemRemove(Request $request)
{
    $itemId = $request->input('item_id');
    $cartId = $request->input('cart_id');
 
    // Validate input
    if (empty($itemId)) {
        return response()->json([
            'responseCode' => '400',
            'message' => 'Item ID is required',
        ], 400);
    }
 
    // Update the deleted_flag to 1 for the given cart item
    if (!empty($cartId)) {
        DB::table('events_cart')
            ->where('id', $cartId)
            ->where('item_id', $itemId)
            ->update(['deleted_flag' => '1']);
    } else {
        // Update the deleted_flag to 1 for the event item and all its associated cart items
        DB::table('event_items')
            ->where('id', $itemId)
            ->update(['deleted_flag' => '1']);
       
        DB::table('events_cart')
            ->where('item_id', $itemId)
            ->update(['deleted_flag' => '1']);
    }
 
    return response()->json([
        'responseCode' => '200',
        'message' => 'Data removed successfully',
    ]);
}



public function eventGetCartDataByUserId(Request $request)
{
     // Check if email already exists
    $existingUser = DB::table('users_details')->where('email', $request->input('email'))->first();
   
   
    //$userId =$existingUser->id;

    // if ($existingUser) {
    //     return response()->json([
    //         'responseCode' => '400',
    //         'responseMsg' => 'Email already exists',
    //     ], 400);
    // }
    
    
    
    $Id = $request->input('item_id'); 
   // $CId = $request->input('cart_id'); 
    $UId = $request->input('user_id'); 
    $u = DB::table('event_common')->select('user_id')->where('user_id',$UId)->first();
    //print_r($u);exit;
    $itD = DB::table('event_common')->select('item_id')->where('item_id',$Id)->first();
     //$eventid = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
     
     if($u && $itD){
         DB::table('event_common')->update([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]); 
     }elseif(!$u && !$itD){
  DB::table('event_common')->insert([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]);
     }elseif($u && !$itD){
  DB::table('event_common')->insert([
    'user_id'=>$UId,
   // 'cart_id'=>$CId,
    'item_id'=>$Id
    ]);
     }


     return response()->json([
        'responseCode' => '200',
         'ResponseMsg' => 'Event Data fetched successfully',
      
       
    ]);
}

public function EventsPayment(Request $request)
{


 $bookingId = DB::table('event_bookings')->insertGetId([
        'item_id' => $request->input('item_id'),
        'user_id' => $request->input('user_id'),
        
    ]);
   
    
    // $poojaService = DB::table('events')->where('id',$request->input('even_id'))->get();
        //  $k= DB::table('puja_items')->where('id', $request->input('item_id'))->first();


    $transactionId = $this->generate_payment_transaction_id($request).$bookingId;

    // Insert pooja payment record
    $paymentId = DB::table('payments')->insertGetId([
        'user_id' => $request->input('user_id'),
        'booking_id'=> $bookingId,
        
        'type' => 'Event',
        'payment_method' => $request->input('payment_method'),
        'name_on_card' => $request->input('name_on_card'),
        'expire_date' => $request->input('expire_date'),
        'card_number' => $request->input('card_number'),
        'cvv' => $request->input('cvv'),
        'devotee_name' => $request->input('devotee_name'),
        'address' => $request->input('address'),
        'city' => $request->input('city'),
        'state' => $request->input('state'),
        'country' => $request->input('country'),
        'zip' => $request->input('zip'),
        'payment_amount' => $request->input('payment_amount'),
        'payment_generate_transaction_id' => $transactionId,

        // Add other relevant payment details here
    ]);

     $bankResponse = $this->bank_response($request);

    // Insert bank response into payment history
    DB::table('payments_history')->insert([
        'payment_id' => $paymentId,
        'bank_response' => json_encode([
            'status' => $bankResponse['status'],
            'bank_transaction_id' => $bankResponse['bank_transaction_id'],
            'key' => $bankResponse['key'],
            'message' => $bankResponse['message'],
        ]),
    ]);

    // Check if bank response status is success
    if ($bankResponse['status'] === 'success') {

        //$bookingId = $request->input('booking_id');
        $kid = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
        //DB::table('events')->where('id', $eventid)->decrement('capacity', 1);



         $kId = DB::table('event_bookings')->where('id', $bookingId)->value('event_id');
        
        // DB::table('poojaservices')->where('id', $poojaServiceId)->decrement('capacity', 1);
        DB::table('event_bookings')->where('id', $bookingId)->update([
        'ticket' => $transactionId,
        'user_id' =>$request->input('user_id'),
       ]);
       
        DB::table('event_common')->where('item_id',$request->input('item_id'))->where('user_id', $request->input('user_id'))->update([
        'booking_id' => $bookingId,
        'status' => '2',
       ]);
    }

    return response()->json([
        'responseCode' => '200',
        //'transaction_id' => $transactionId,
        'responseMsg' => 'Item payment recorded successfully',
        'user_id' =>$request->input('user_id'),
        'item_id' =>$request->input('item_id'),
        'booking_id'=>$bookingId,
        'ticket' => $transactionId,
        
    ]);
}

public function EventDataAfterPayment(Request $request)
{
    $uId = $request->input('user_id');
    $itId = $request->input('item_id');
    $bId = $request->input('booking_id');
    
    $data = DB::table('event_common')
    ->select(
        'event_common.item_id','event_common.user_id','event_common.user_id','event_common.status',
        'events.event_name_en AS event_name','events.description_en AS description','events.event_img',
        'events_cart.devotee_name','events_cart.gotram','events_cart.spouse_name', 'events_cart.family_member_name','events_cart.start_date','events_cart.amount','events_cart.puja_duration',
        'event_common.id as pooja_common_id',
        'events.id as event_id',
        'events_cart.id as events_cart_id'
    )
    ->join('events_cart', 'event_common.item_id', '=', 'events_cart.item_id')
    ->join('events', 'events_cart.event_id', '=', 'events.id')
    ->where('event_common.booking_id', $bId)
    ->where('event_common.item_id', $itId)
    ->where('event_common.user_id', $uId)
    ->where('events_cart.deleted_flag', '0')
    ->where('event_common.status', '2')
    ->get();

            
    return response()->json([
        'responseCode' => '200',
      'responseMsg' => 'Data fetched successfully',
      'data' =>$data,
       
        
    ]);  
}



}
