<?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\WhatsappTracker;
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 App\Models\User;
use Carbon\Carbon;
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
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'] ?? '';
        $campaign_id = $postData['campaign_id'] ?? '';
        $ad_id = $postData['ad_id'] ?? '';
        // // 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'];

        // Round Robin RM Assignment
        // $rm_users = User::where('is_rm', 1)->where('status', 1)->orderBy('id', 'asc')->pluck('id')->toArray();
        // $next_rm_id = null;
        // if (!empty($rm_users)) {
        //     $last_customer = Customer::whereNotNull('rm_id')
        //                              ->where('rm_id', '!=', 0)
        //                              ->where('rm_id', '!=', '')
        //                              ->orderBy('id', 'desc')
        //                              ->first();

        //     $next_rm_id = $rm_users[0]; // Default to first RM
        //     if ($last_customer && in_array($last_customer->rm_id, $rm_users)) {
        //         $current_index = array_search($last_customer->rm_id, $rm_users);
        //         if (isset($rm_users[$current_index + 1])) {
        //             $next_rm_id = $rm_users[$current_index + 1];
        //         }
        //     }
        // }

        // 4. Insert into 'users' table using Customer model
        $customer = Customer::create([
            'cust_name' => $name,
            'email' => $email,
            'phone' => $phone,
            'rm_id' => '',
            'password' => $password,
            'web_sort_name' => '',
            'status' => 1,
            'customer_password_md5_decode' => 'user123',
            'lead_source' => 'FB/Insta Ad Lead',
            'promotion_status' => 0,
            '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',
            'campaign_id' => '',
            'ad_id' => '',

        ]);
        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' => $postData,
            ]);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'Failed to create lead'
        ], 500);
    }
    // public function whatsapp_msg_read(Request $request)
    // {
    //     $postData = $request->all();

    //     // Standard Smooch payload extraction
    //     $msgId = $postData['data']['message']['_id'] ?? null;
    //     $convId = $postData['data']['conversation']['_id'] ?? null;
    //     $phone = $postData['data']['destination']['id'] ?? ($postData['data']['appUser']['userId'] ?? null);

    //     // In common.php, notification['_id'] is saved as conversation_id in whatsapp_tracker
    //     $targetId = $msgId ?: $convId;

    //     if ($targetId) {
    //         $query = \DB::table('whatsapp_tracker')->where('conversation_id', $targetId);

    //         if ($phone) {
    //             // Ensure phone number matches (handling possible formatting differences)
    //             $query->where(function ($q) use ($phone) {
    //                 $q->where('phone', $phone)
    //                     ->orWhere('phone', 'like', '%' . $phone);
    //             });
    //         }

    //         $tracker = $query->first();

    //         if ($tracker) {

    //             // Update tracker status (1 = Delivered/Read)
    //             \DB::table('whatsapp_tracker')->where('id', $tracker->id)->update([
    //                 'status' => 1
    //             ]);

    //             // Update user whatsapp_status to 1 (On WhatsApp)
    //             if ($tracker->user_id) {
    //                 \DB::table('users')->where('id', $tracker->user_id)->update([
    //                     'whatsapp_status' => 1
    //                 ]);
    //             }
    //         }
    //     }

    //     return response()->json([
    //         'status' => 'success'
    //     ]);
    // }
    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);
    }
    public function update_last_whatsapp_date(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' => 'last 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(['last_whatsapp_date' => now()]);
        dd(1);
    }
    public function createWhatsappUser(Request $request)
    {
        $data = $request->all();

        // 1. Log webhook payload FIRST so webhook_history records every API hit
        try {
            \DB::table('webhook_history')->insert([
                'webhook_payload' => json_encode($data),
                'webhook_name' => 'create_whatsapp_user',
                'created_at' => now(),
            ]);
        } catch (\Exception $e) {
            // Ignore DB insert failure
        }

        // 2. Extract name (support userFirstName + userLastName)
        $firstName = trim($data['userFirstName'] ?? '');
        $lastName = trim($data['userLastName'] ?? '');
        $name = trim($firstName . ' ' . $lastName);
        if (empty($name)) {
            $name = $data['userName'] ?? $data['cust_name'] ?? $data['name'] ?? 'WhatsApp User';
        }

        // 3. Extract email & phone with fallbacks
        $email = $data['userEmail'] ?? $data['email'] ?? $data['user_email'] ?? null;
        $phone = $data['userPhone'] ?? $data['phone'] ?? $data['user_phone'] ?? $data['mobile'] ?? null;
        $website = $data['website'] ?? $data['web_sort_name'] ?? 'GAH';
        $country = $data['country'] ?? '';
        $source = $data['source'] ?? $data['lead_source'] ?? 'WhatsApp';
        $userMessage = $data['userMessage'] ?? '';

        // 4. Sanitize phone number (clean "null", placeholders like "{user.phone}")
        if (!empty($phone)) {
            $phone = trim($phone);
            if ($phone === 'null' || str_contains($phone, '{') || str_contains($phone, '}')) {
                $phone = null;
            }
        }

        // Fallback: If phone is null, attempt extracting a phone number from userMessage if present
        if (empty($phone) && !empty($userMessage)) {
            if (preg_match('/(?:\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4,6}/', $userMessage, $matches)) {
                $phone = $matches[0];
            }
        }

        // If phone is still null or empty, skip customer creation and return HTTP 200 OK so webhook is acknowledged
        if (empty($phone)) {
            return response()->json([
                'status' => 'skipped',
                'message' => 'Phone number is null or empty. Customer creation skipped.'
            ], 200);
        }

        // 5. Sanitize email: clean "null", unrendered placeholders like "{user. email}" or "{user.email}", or invalid formats
        if (!empty($email)) {
            $email = trim($email);
            if ($email === 'null' || str_contains($email, '{') || str_contains($email, '}') || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $email = null;
            }
        }

        // Format phone number if provided
        $formattedPhone = $phone;
        try {
            $phoneUtil = PhoneNumberUtil::getInstance();
            $numberProto = $phoneUtil->parse($phone, null);
            $countryCode = $numberProto->getCountryCode();
            $nationalNumber = $numberProto->getNationalNumber();
            $formattedPhone = '+' . $countryCode . '-' . $nationalNumber;
        } catch (\Exception $e) {
            $formattedPhone = $phone;
        }

        // Auto-generate fallback email if email is empty or invalid
        if (empty($email)) {
            $nameParts = explode(' ', trim($name));
            $firstLetter = !empty($nameParts[0]) ? strtolower(substr($nameParts[0], 0, 1)) : 'w';
            $cleanPhone = preg_replace('/\D/', '', $formattedPhone ?? $phone);
            $last4Digits = !empty($cleanPhone) ? substr($cleanPhone, -4) : rand(1000, 9999);
            $email = $firstLetter . $last4Digits . '@example.com';
        }

        // Check if customer already exists with valid phone or email
        $existingCustomer = Customer::where(function ($query) use ($email, $phone, $formattedPhone) {
            $hasCondition = false;
            if (!empty($phone)) {
                $query->where('phone', $phone)->orWhere('phone', $formattedPhone);
                $hasCondition = true;
            }
            if (!empty($email) && !str_ends_with($email, '@example.com')) {
                if ($hasCondition) {
                    $query->orWhere('email', $email);
                } else {
                    $query->where('email', $email);
                }
            }
        })->first();

        if ($existingCustomer) {
            return response()->json([
                'status' => 'exists',
                'message' => 'Customer already exists with this phone or email',
                'user_id' => $existingCustomer->id,
                'customer' => $existingCustomer
            ]);
        }

        // Create new customer if not found
        $ipAddress = $request->ip();
        $password = md5('user123');

        $customer = Customer::create([
            'cust_name' => $name,
            'email' => $email,
            'phone' => $formattedPhone ?? $phone,
            'password' => $password,
            'customer_password_md5_decode' => 'user123',
            'web_sort_name' => $website,
            'status' => 1,
            'lead_source' => $source,
            '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' => $userMessage,
            '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' => 1,
            'whatsapp_enabled' => 1,
            'qualification' => '',
            'college' => '',
            'coupon' => '',
            'course' => '',
            'zendesk_ticket_id' => 0,
            'stage' => 'Registered',
        ]);

        if ($customer) {
            LeadManagement::create([
                'name' => $name,
                'email' => $email,
                'phone' => $formattedPhone ?? $phone,
                'country' => $country,
                'website' => $website,
                'source' => $source,
                '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,
            ]);

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

        return response()->json([
            'status' => 'error',
            'message' => 'Failed to create customer'
        ], 500);
    }
}