<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Bd_leads;
use App\Models\Call_tracker;
use App\Models\CallTracker;
use App\Models\Call_tracker_type;
use App\Models\Country;
use App\Models\Lead_history;
use App\Models\Payment_slice;
use App\Models\Source;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Imports\BdLeadsImport;
use App\Models\LeadManagement;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Customer;
use App\Models\Order;
use App\Models\WebhookHistory;
use App\Models\Lead;
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
use Carbon\Carbon;
class WebhookController extends Controller
{
    public function stripePaymentUpdate(Request $request)
        {
            $SECRET_TOKEN = "b7f3d2a9c4e81f56a1c93e7d8f21b0cd";

            // Read JSON body (Stripe sends JSON)
            $postData = $request->all();
            // dd($request->all());
            // -----------------------------
            // 🔐 Token validation
            // -----------------------------
            // if (!isset($postData['token']) || $postData['token'] !== $SECRET_TOKEN) {
            //     return response()->json([
            //         'status'  => 'error',
            //         'message' => 'Invalid token'
            //     ], 401);
            // }

            // -----------------------------
            // 🟢 Valid token — Save webhook data
            // -----------------------------
             $charge   = $postData['data']['object'] ?? null;
            \DB::table('webhook_history')->insert([
                'webhook_payload' => json_encode($postData),
                'webhook_name'    => 'Stripe',
                'user_id'         => $postData['user_id'] ?? null,
                'api_response'    => null,
                'created_at'      => now(),
                'type' => $postData['type'],
                'charge_id' => $charge['id'],
            ]);
            
             if ($charge) {
                $chargeId   = $charge['id']; 
                $riskScore  = $charge['outcome']['risk_score'] ?? null;
                $last4      = $charge['payment_method_details']['card']['last4'] ?? null;

                // -----------------------------
                // ✔ UPDATE payment_slice TABLE
                // -----------------------------
                DB::table('payment_slice')
                    ->where('transaction_id', $chargeId)
                    ->update([
                        'risk_score'  => $riskScore,
                        'card_number' => $last4,

                    ]);
            }
            return response()->json([
                'status'   => 'success',
                'received' => $postData
            ]);
        }
        public function createMetaLead(Request $request)
        {
            // Pabbly sends data as form POST (application/x-www-form-urlencoded)
            $postData = $request->all();
            // // 2. Secret token validation (optional but recommended if coming from Google Sheets)
            // $SECRET_TOKEN = "your_secure_token_12345";
            // if (!isset($postData['token']) || $postData['token'] !== $SECRET_TOKEN) {
            //     return response()->json([
            //         'status'  => 'error',
            //         'message' => 'Invalid token'
            //     ], 401);
            // }

            // 3. Extract and sanitize data
            $name = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $postData['name'] ?? '');
            $email = $postData['email']     ?? '';
            $phone = $postData['phone']     ?? '';
             $password  = md5('user123');
             $website = $postData['website'] ?? ''; 
             $country = $postData['country'] ?? '';
            // // Strip 'p:' if it exists
            // $phone = str_replace('p:', '', $phone);

            // Check if email already exists — skip insert if it does
            if (!empty($email) && Customer::where('email', $email)->exists()) {
                return response()->json([
                    'status'  => 'skipped',
                    'message' => 'Lead already exists with this email: ' . $email
                ]);
            }
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            // 4. Insert into 'users' table using Customer model
            $customer = Customer::create([
                'cust_name'     => $name,
                'email'         => $email,
                'phone'         => $phone,
                'password'     => $password,
                'web_sort_name' => $website,
                'status'       => 1,
                'customer_password_md5_decode' => 'user123',
                'lead_source'   => 'FB/Insta Ad Lead',     
                'promotion_status' => 0,  
                'country' => $country,
                'promotion_status'             => 0,
                'activate'                     => 0,
                'storecredit'                  => 0,
                'image'                        => '',
                'city'                         => '',
                'address'                      => '',
                'link'                         => '',
                'verify'                       => 0,
                'view'                         => 0,
                'rwards_point'                 => 0,
                'online'                       => 0,
                'ip_address'                   => $ipAddress,
                'customer_type'                => 0,
                'vendor_view'                  => 0,
                'vendor_cust_deleted_status'   => 0,
                'customer_from'                => 0,
                'other_info'                   => '',
                'auto_mail_send'               => 0,
                'payment_getway_token'         => '',
                'alternate_phone'              => '',
                'alternate_email'              => '',
                'email_verify'                 => 0,
                'phone_verify'                 => 0,
                'assign_to'                    => 0,
                'refered_by'                   => 0,
                'whatsapp_status'              => 0,
                'qualification'                => '',
                'college'                      => '',
                'coupon'                       => '',
                'course'                       => '',
                'zendesk_ticket_id'            => 0,                    
                'stage'    => 'Registered',

            ]);
             LeadManagement::create([
            'name'    => $name,
            'email'   => $email,
            'phone'   => $phone,
            'country' => $country,
            'website' => $website,
            'source'  => 'FB/Insta Ad Lead',
            'cust_id' => $customer->id,
            'order_id' => 0,
            'rcb_id' => 0,
            'last_activity_source'=> '',
            'last_activity_by'=>0,
            'view'=>0,
            'is_converted'=>0,
            'followup_status'=>0,
            'is_deleted'=>0,
            'is_delete'=>0,



        ]);
            if ($customer) {
                return response()->json([
                    'status'   => 'success',
                    'message'  => 'Lead created successfully',
                    'user_id'  => $customer->id
                ]);
            }

            return response()->json([
                'status'   => 'error',
                'message'  => 'Failed to create lead'
            ], 500);
        } 
        public function wp_message_read(Request $request)
    {
        $data = $request->all();
        $phone =  $data['userPhone'];
        $phoneUtil = PhoneNumberUtil::getInstance();

        try {
            $numberProto = $phoneUtil->parse($phone, null);

            $countryCode = $numberProto->getCountryCode(); // 92
            $nationalNumber = $numberProto->getNationalNumber(); // 3706110530

            $formatted = '+' . $countryCode . '-' . $nationalNumber;

        } catch (\Exception $e) {
            $formatted = $phone;
        }

        \DB::table('webhook_history')->insert([
            'webhook_payload' => json_encode($data),
            'webhook_name' => 'whatsapp',
            //'user_id' => $data['user_id'] ?? null,
            //   'api_response' => $formatted,
            'created_at' => now(),
            'type' => $formatted,
            //  'charge_id' => $data['charge_id'],
        ]);

        // $email = $data['userEmail'];
        Customer::where('phone', $formatted)
            ->update(['whatsapp_enabled' => 1]);
        dd(1);
    }
}