<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Models\Banner;
use App\Models\Product;
use App\Models\UserAddress;
use App\Models\OrderDetails;
use App\Models\Orders;
use App\Models\PaymentDetails;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use DB;
use Illuminate\Support\Str;
use Carbon\Carbon; 
use Mail;
use PDF;

class HomeController extends Controller
{
    
    public function add_address(Request $request)
    {
        // dd($request->all());
        
        $check_address = UserAddress::where('user_id', $request->user_id)->first();
        if($check_address)
        {
            $address               = UserAddress::find($check_address->id);
        }
        else
        {
            $address               = new UserAddress();
        }
        $address->user_id      = $request->user_id;
        $address->name         = $request->name;
        $address->email        = $request->email;
        $address->phone        = $request->phone;
        $address->address      = $request->address;
        $address->city         = $request->city;
        $address->state        = $request->state;
        $address->country      = "India";
        $address->pincode      = $request->pincode;
        $address->landmark     = $request->landmark;
        $address->save();
        
        if($address)
        {
            return response()->json(['result' => true, 'message' => 'Address has been added successfully!', 'address_id' => $address->id]);
        }
        else
        {
            return response()->json(['result' => false, 'message' => 'Something Wrong']);
        }
        
    }
    
    public function update_address(Request $request)
    {
        // dd($request->all());
        
        $address               = UserAddress::find($request->address_id);
        $address->user_id      = $request->user_id;
        $address->name         = $request->name;
        $address->email        = $request->email;
        $address->phone        = $request->phone;
        $address->address      = $request->address;
        $address->city         = $request->city;
        $address->state        = $request->state;
        $address->country      = "India";
        $address->pincode      = $request->pincode;
        $address->landmark     = $request->landmark;
        $address->save();
        
        if($address)
        {
            return response()->json(['result' => true, 'message' => 'Address has been Updated successfully!']);
        }
        else
        {
            return response()->json(['result' => false, 'message' => 'Something Wrong']);
        }
        
    }
    
    public function getAddress(Request $request) 
    {
        $address = UserAddress::where('user_id', $request->user_id)->first();
        
        $AddressDetails = [
                'id'                => $address->id,
                'user_id'           => $address->user_id,
                'name'              => $address->name,
                'email'             => $address->email,
                'phone'             => $address->phone,
                'address'           => $address->address,
                'city'              => $address->city,
                'state'             => $address->state,
                'country'           => "India",
                'landmark'          => $address->landmark,
                'pincode'           => $address->pincode,
                'country_name'      => "India",
                'state_name'        => $address->state_details->name,
                'city_name'         => $address->city,
            ];
        // dd($AddressDetails);
        if($AddressDetails)
        {
            return response()->json(['result' => true, 'address' => $AddressDetails]);
        }
        else
        {
            return response()->json(['result' => false, 'message' => 'No Address Found']);
        }
        
    }
    
    public function checkout(Request $request)
    {
        
        $cart = Session::get('cart', []);
        $product_type = [];
        // foreach($cart as $key => $value)
        // {
        //     if($value->product_type)
        //     {
        //         $product_type = $value->product_type;
        //     }
            
        // }
        // dd();
        $total_amount = total_cart_amount($cart);
        
        $data['cart'] = $cart;
        $data['amount'] = $total_amount;
        $data['product_type'] = reset($cart)['product_type'];
        
        if($data){
            return response()->json(['result' => true, 'message' => $data]);
        } else {
            return response()->json(['result' => false, 'message' => 'No data']);
        }
        
    }
    
    public function CheckCoupen(Request $request)
    {
        $check_coupen = $request->discount_type;
        $user_details = User::where('uni_number', $check_coupen)->first();
        // $order_details = Orders::where('user_id', $user_details->id)->first();
        
        // if($order_details)
        // {
            
        // }
        // dd($user_details);
        if($user_details)
        {
            $member_check = User::where('admin_id', $check_coupen)->get();
            // dd(count($member_check));
            if(count($member_check) >= 5)
            {
                return response()->json(['result' => false, 'message' => 'User OverLoad']);
            }
            // elseif($user_details->level == 4)
            // {
            //     return response()->json(['result' => false, 'message' => 'Level Over. Please Remove Code']);
            // }
            else
            {
                return response()->json(['result' => true, 'message' => 'Valid Code']);
            }
            
        }
        
        else
        {
            return response()->json(['result' => false, 'message' => 'Invalid Code']);
        }
        
        return response()->json(['result' => false, 'message' => 'Invalid Code']);
    }
    
    public function CheckBusinessPlan(Request $request)
    {
        $check_user_id = $request->user_id;
        
        $user_details = User::where('id', $check_user_id)->first();
        
        if($user_details->admin_id)
        {
            $data['discount_code']           = $user_details->admin_id;
            return response()->json(['result' => false, 'message' => 'Already Admin Added', 'data' => $data]);
        }
        else
        {
            return response()->json(['result' => true, 'message' => 'No Admin Found']);
        }
        
    }
    
    public function DiscountAmount(Request $request)
    {
        $check_coupen   = $request->discount_type;
        $cart           = Session::get('cart', []);
        $total_amount   = total_cart_amount($cart);
        $discount       = discount_calculate($total_amount['discount_amount'], $request->discount_type);
        
        $data['total_amount']           = $total_amount['discount_amount'];
        $data['discount']               = $discount['discount'];
        $data['discount_percentage']    = $discount['discount_per'];
        $data['sub_total']              = $total_amount['discount_amount'] -  $discount['discount'];
        
        // dd($data);
        if($data)
        {
            return response()->json(['result' => true, 'discount' => $data]);
            
        }
        else
        {
            return response()->json(['result' => false, 'message' => 'No Discount']);
        }
        
    }
    
    public function select_address(Request $request)
    {
        // dd($request->all());
        $cart                         = Session::get('cart', []);
        $total_amount                 = total_cart_amount($cart);
        $discount                     = discount_calculate($total_amount['discount_amount'], $request->discount_type);
        $address                      = UserAddress::where('user_id', $request->user_id)->first();
        
        if(isset($request->discount_code))
        {
            $discount_code = $request->discount_code;
        }
        else
        {
            $user_details = User::where('id', $request->user_id)->first();
            $discount_code = $user_details->admin_id;
        }
        
        // Response Data
        $data['cart']                 = $cart;
        $data['amount']               = $total_amount;
        $data['user_id']              = $request->user_id;
        $data['discount_type']        = $request->discount_type;
        $data['discount_amount']      = $discount['discount'];
        $data['discount_percentage']  = $discount['discount_per'];
        $data['discount_code']        = $discount_code;
        $data['address']              = $address;
        
        if($data){
            return response()->json(['result' => true, 'message' => $data]);
        } else {
            return response()->json(['result' => false, 'message' => 'No data']);
        }
        
    }
    
    public function final_step(Request $request)
    {
        // dd($request->user_id);
        session()->put('user_id', $request->user_id);
        $user_details = User::where('id', $request->user_id)->first();
        $user_address_check = UserAddress::where('user_id', $request->user_id)->first();
        $coupen_code = "";
        if($request->discount_type == 2)
        {
            if($request->discount_code)
            {
                $coupen_code = $request->discount_code;
            }
            else
            {
                $coupen_code = $user_details->admin_id;
            }
        }
        
        // dd($user_address_check);
        session()->put('discount_type', $request->discount_type);
        session()->put('discount_code', $coupen_code);
        session()->put('address_id', $request->address_id);
        session()->put('payment_type', $request->payment_type);
        
        $cart           = Session::get('cart', []);
        
        $total_amount   = total_cart_amount($cart);
        $discount       = discount_calculate($total_amount['discount_amount'], $request->discount_type);
            
        // Instamoja Payment Geteway
        try {
            $instamojo = config('services.instamojo');
            // dd($instamojo);
            $payload = array(
                "purpose" => "IMORDER" . Str::random(9),
                "amount" => intval($total_amount['discount_amount'] - $discount['discount']),
                "buyer_name" => $user_address_check->name,
                "email" =>  $user_address_check->email,
                "phone" =>  $user_address_check->phone,
                "send_email" => true,
                "send_sms" => true,
                "redirect_url" => url('/api/instamojopayments/success')
            );
            // dd($payload);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $instamojo['endpoint'].'payment-requests/');
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "X-Api-Key:".$instamojo['api_key'],
                "X-Auth-Token:".$instamojo['auth_token']
            ));
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
            $response = curl_exec($ch);
            curl_close($ch);

            $response = json_decode($response, true);
            // dd($response);
            if ($response['success'] == true) {
                $payment_request = $response['payment_request'];
                return response()->json(['result' => true, 'payment_request' => $payment_request], 200);
                
                exit();
            } else {
                \Log::info($response);
                // dd($response['message']['email'][1]);
                if(isset($response['message']['email'][1]) && $response['message']['email'][1])
                {
                    $error = $response['message']['email'][1];
                }
                if(isset($response['message']['amount'][0]) && $response['message']['amount'][0])
                {
                    $error = $response['message']['amount'][0];
                }
                return response()->json(['result' => false, 'message' => $error]);
            }
        }catch (Exception $e) {
            \Log::info($e->getMessage());
            return response()->json(['result' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        
    }
    
    public function InstaSuccess(Request $request)
    {
        // dd("hi");
        $data = $request->all();
        dd($data);
        return response()->json(['result' => true, 'message' => $data], 200);
        
        // dd($request->all());
    }
    
    public function order_view(Request $request)
    {
        $orders = Orders::where('user_id', $request->user_id)->get();
        $baseImageUrl = url('public/product');
        
        if($orders->isNotEmpty()) {
            $data = [];
            
            foreach ($orders as $banner) {
                
                if ($banner->orderitems) {
                    foreach ($banner->orderitems as $key => $value) {
                        $image_details = [
                                'image'                => $baseImageUrl . '/' . $value->thumbnail_image,
                            ];
                    }
                    $banner->multiple_image =  $image_details;
                }

            }
            
            return response()->json([
                'result' => true,
                'order' => $orders
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => 'No data'
            ]);
        }
        
    }
    
    public function order_details(Request $request)
    {
        $orderId = $request->order_id;
        
        $order = Orders::find($orderId);
        // dd($product);
        if ($order) {
            
            $baseImageUrl = url('public/product');
            
            foreach ($order->orderitems as $key => $value) {
                $image_details = [
                        'product_name'      => $value->product_name,
                        'original_amount'   => $value->original_amount,
                        'discount_amount'   => $value->discount_amount,
                        'quantity'          => $value->quantity,
                        'include_product'   => $value->include_product,
                        'thumbnail_image'   => url('public/product').'/'.$value->thumbnail_image,
                    ];
                    
                $total_item[] = $image_details;
            }
                
            
            $orderDetails = [
                'id'                     => $order->id,
                'order_id'               => $order->order_id,
                'total_original_amount'  => $order->total_original_amount,
                'total_discount_amount'  => $order->total_discount_amount,
                'discount_type'          => $order->discount_type,
                'discount_amount'        => $order->discount_amount,
                'status'                 => $order->status,
                'order_type'             => "cod",
                'order_date'             => date('d-m-Y', strtotime($order->created_at)),
                'order_item'             => $total_item,
            ];
            // dd($orderDetails);
            return response()->json([
                'result' => true,
                'order_details' => $orderDetails
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'message' => 'Order not found'
            ]);
        }
    }
    
    public function ViewProfile(Request $request)
    {
        $user_id = $request->user_id;
        
        $user_details = User::where('id', $user_id)->first();
        
        if($user_details)
        {
            $userDetails = [
                'name'          => $user_details->name,
                'email'         => $user_details->email,
                'phone'         => $user_details->phone,
                'refer_number'  => $user_details->uni_number,
                'bank_ifsc'     => $user_details->bank_ifsc,
                'bank_name'     => $user_details->bank_name,
                'account_number' => $user_details->account_number,
                'wallet_amount' => $user_details->wallet_amount ?? '0',
            ];
            
            return response()->json([
                'result' => true,
                'user_details' => $userDetails
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'message' => 'User not found'
            ]);
        }
    }
    
    
    public function BankUpdate(Request $request)
    {
        $user_id = $request->user_id;
        
        $user = User::find($user_id);
        $user->bank_ifsc = $request->bank_ifsc;
        $user->bank_name = $request->bank_name;
        $user->account_number = $request->account_number;
        if($user->save())
        {
            return response()->json([
                'result' => true,
                'message' => 'Bank Details Update Successfully'
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'message' => 'Something Wrong'
            ]);
        }
        
    }
    
    public function change_password(Request $request)
    {
        // dd($request->all());
        $validate = Validator::make($request->all(), [
            'password'      => 'required|confirmed'
        ]);

        if($validate->fails()){
            return response()->json([
                'status' => 'failed',
                'message' => 'Validation Error!',
                'data' => $validate->errors(),
            ], 403);  
        }
        
        $password            = Hash::make($request->password);
        
        $user = User::find($request->user_id);
        $user->password = $password;
        if($user->save())
        {
            return response()->json([
                'result' => true,
                'message' => 'Password Update Successfully'
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'message' => 'Something Wrong'
            ]);
        }
    }
    
    public function wallet(Request $request)
    {
        $user_id = $request->user_id;
        
        $user_details = User::where('id', $user_id)->first();
        $baseImageUrl = url('public/transaction');
        
        if($user_details)
        {
            
            $total_earn_amount = 0;
            $total_with_amount = 0;
            $payment_details   = [];
            foreach($user_details->payment_details as $key => $value)
            {
                $total_earn_amount += $value->discount; 
                
                $paymentDetails = [
                    'order_id'         => $value->refer_id,
                    'earn_percentage'  => $value->discount_per,
                    'earn_amount'      => number_format($value->discount, 2),
                ];
                
                $payment_details[] = $paymentDetails;
                
            }
            $transaction_history = [];
            foreach($user_details->transaction_history as $key => $value1)
            {
                $total_with_amount += $value1->amount;
                
                $transactionHistory = [
                    'amount'            => number_format($value1->amount, 2),
                    'reference_number'  => $value1->reference_number,
                    'proof_image'       => $baseImageUrl . '/' . $value1->proof_image,
                ];
                
                $transaction_history[] = $transactionHistory;
                
            }
            if($user_details->wallet_amount)
            {
                $wallet_amount = number_format($user_details->wallet_amount, 2);
            }
            else
            {
                $wallet_amount = 0;
            }
            
            $userDetails = [
                'total_earn_amount'   => $total_earn_amount,
                'total_with_amount'   => $total_with_amount,
                'wallet_amount'       => $wallet_amount,
                'payment_details'     => $payment_details,
                'transaction_history' => $transaction_history,
            ];
            
            return response()->json([
                'result' => true,
                'wallet_details' => $userDetails
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'message' => 'User not found'
            ]);
        }
        
    }
    
    public function invoice_download(Request $request)
    {
        // dd($id);
        $id = $request->order_id;
        
        $order_details = Orders::where('id', $id)->first();
        
        $product_description = str_replace('#', '', $order_details->order_id);
        PDF::setOptions(['dpi' => 150, 'defaultFont' => 'sans-serif']);

        $pdf = PDF::loadView('invoice', compact('order_details'));
        
        if($pdf)
        {
            $pdfname = $product_description.'.pdf';
        
            $path = 'public/invoice/';
            $pdf->save($path.''. $pdfname);
            
            $invoice_url  = url('/').'/public/invoice/'.$pdfname;
            
            return response()->json([
                'result' => true,
                'invoice_url' => $invoice_url
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'invoice_url' => 'Invoice not found'
            ]);
        }
    }
    
    public function UserChart(Request $request)
    {
        $id = $request->user_id;
        
        $user_details = User::where('id', $id)->first();
        
        if($user_details)
        {
            $down_chck = User::where('admin_id', $user_details->uni_number)->get();
            $transaction_history = [];
            foreach($down_chck as $key => $value1)
            {
                
                $transactionHistory = [
                    'id'            => $value1->id,
                    'name'          => $value1->name,
                    'uni_number'   => $value1->uni_number,
                ];
                
                $transaction_history[] = $transactionHistory;
                
            }
            
            $userDetails = [
                    'user_name'           => $user_details->name,
                    'email'               => $user_details->email,
                    'phone'               => $user_details->phone,
                    'refer_id'            => $user_details->uni_number,
                    'transaction_history' => $transaction_history,
                ];
            
            if($userDetails)
            {
                return response()->json([
                    'result' => true,
                    'userchart' => $userDetails
                ]);
            }
            else
            {
                return response()->json([
                    'result' => false,
                    'userchart' => 'User Not Found'
                ]);
            }
        }
        else
        {
            return response()->json([
                'result' => false,
                'userchart' => 'User Not Found'
            ]);
        }
        
        
    }
    
    public function UserChart1(Request $request)
    {
        $id = $request->user_id;
        $uni_number = $request->uni_number;
        
        $user_details = User::where('id', $id)->first();
        
        
        if($user_details)
        {
            $down_check = User::where('admin_id', $uni_number)->get();
            $transaction_history1 = [];
            
            foreach($down_check as $key => $value2)
            {
                
                $transactionHistory1 = [
                    'id'            => $value2->id,
                    'name'          => $value2->name,
                    'uni_number'    => $value2->uni_number,
                ];
                
                $transaction_history1[] = $transactionHistory1;
                
            }
            
            $userDetails1 = [
                    'user_name'           => $user_details->name,
                    'email'               => $user_details->email,
                    'phone'               => $user_details->phone,
                    'refer_id'            => $user_details->uni_number,
                    'transaction_history1' => $transaction_history1,
                ];
            
            if($userDetails1)
            {
                return response()->json([
                    'result' => true,
                    'userchart1' => $userDetails1
                ]);
            }
            else
            {
                return response()->json([
                    'result' => false,
                    'userchart1' => 'User Not Found'
                ]);
            }
        }
        else
        {
            return response()->json([
                'result' => false,
                'userchart1' => 'User Not Found'
            ]);
        }
        
        
        
    }
    
    public function UserChart2(Request $request)
    {
        
        $id = $request->user_id;
        $uni_number = $request->uni_number;
        
        $user_details = User::where('id', $id)->first();
        
        if($user_details)
        {
            $transactionHistory2 = [];
            $down_check = User::where('admin_id', $uni_number)->get();
            foreach($down_check as $key => $value2)
            {
                
                $transactionHistory2 = [
                    'id'            => $value2->id,
                    'name'          => $value2->name,
                    'uni_number'    => $value2->uni_number,
                ];
                
                $transaction_history2[] = $transactionHistory2;
                
            }
            
            $userDetails2 = [
                    'user_name'           => $user_details->name,
                    'email'               => $user_details->email,
                    'phone'               => $user_details->phone,
                    'refer_id'            => $user_details->uni_number,
                    'transaction_history2' => $transaction_history2,
                ];
            
            if($userDetails2)
            {
                return response()->json([
                    'result' => true,
                    'userchart2' => $userDetails2
                ]);
            }
            else
            {
                return response()->json([
                    'result' => false,
                    'userchart2' => 'User Not Found'
                ]);
            }
        }
        else
        {
            return response()->json([
                'result' => false,
                'userchart2' => 'User Not Found'
            ]);
        }
        
    }
    
    
}
