<?php

namespace App\Http\Controllers\API;

# Models
use App\User;
use App\Models\Bit;
use App\Models\AppDetail;
use App\Models\Sessions;
use App\Models\Store;
use App\Models\Day;
use App\Models\StoreGame;
use App\Models\PaymentHistory;

# Other Classes
use DB;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Validator;
use App\Traits\BetTrait;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use thiagoalessio\TesseractOCR\TesseractOCR;
use App\Http\Controllers\API\BaseController as BaseController;

class WhatsappBetController extends BaseController
{
    
    
    use BetTrait;

     #Bind User model
    protected $user;

     #Bind Bit model
    protected $bit;

     #Bind AppDetail model
    protected $appDetail;

     #Bind Sessions model
    protected $session;

     #Bind Store model
    protected $store;

     #Bind Day model
    protected $day;

     #Bind StoreGame model
    protected $storeGame;


    /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                User $user,
                                Store $store,
                                Bit $bit,
                                Sessions $session,
                                Day $day,
                                StoreGame $storeGame,
                                AppDetail $appDetail
                            )
    {
        $this->user  = $user;
        $this->store  = $store;
        $this->bit  = $bit;
        $this->session  = $session;
        $this->day  = $day;
        $this->storeGame  = $storeGame;
        $this->appDetail       = $appDetail;
        
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
         try
        {
           
           
           
           
            return $this->sendResponse(true, 'Result Updated.');

        }catch(\Exception $ex)
        {
            return $this->sendError('Validation Error.', $ex->getMessage()); 
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }
    
    
    public function whatsappWebhook(Request $request)
    {
        
        try{
            
            
            Log::info('whstapp');
        
        DB::beginTransaction();
        $data = $request->all();
        
        $message = strtolower($data['body']); 
        $from = $data['from']; // 919834474552@c.us
        $to = $data['to'];
        $type = $data['type'];
        $timestamp = $data['timestamp'];
            // Log::info($data);
    
    
        $fromnumberwhatsapp = $data['contact'];
            $fromnumber = substr(preg_replace('/\D/', '', $data['contact']), -10);
          
            Log::info($fromnumber);
            Log::info($fromnumberwhatsapp);
            
            // Log::info($fromnumber);
            // Log::info($to);
            // Log::info($type);
            // Log::info($timestamp);
            
            $checkUser = $this->user->where('mobile_number',$fromnumber)->first();
            
            if(!$checkUser){
                $whatsappMessage = "User Not Registered...!";
                $this->sendMessage($whatsappMessage,$fromnumberwhatsapp);
                return;
            }
            
            Log::info($message);
            // Log::info($data);
            
            
            
            if ($type === 'image') {

                $imageUrl = $data['savedPath'];
            
                $client = new \GuzzleHttp\Client();
            
               $response = $client->request('POST', 'https://api.ocr.space/parse/image', [
                    'multipart' => [
                        [
                            'name'     => 'url',
                            'contents' => $imageUrl
                        ],
                        [
                            'name'     => 'apikey',
                            'contents' => 'helloworld'
                        ],
                        [
                            'name'     => 'OCREngine',
                            'contents' => '2'
                        ],
                        [
                            'name'     => 'scale',
                            'contents' => 'true'
                        ],
                        [
                            'name'     => 'isTable',
                            'contents' => 'true'
                        ],
                        [
                            'name'     => 'detectOrientation',
                            'contents' => 'true'
                        ]
                    ]
                ]);
            
            
                $result = json_decode($response->getBody(), true);

                \Log::info($result);
                $text = $result['ParsedResults'][0]['ParsedText'] ?? '';
                
                \Log::info($text);
                
                preg_match_all('/(\d+)\s+(\d+)/', $text, $matches);

                $data = [];
                
                foreach ($matches[1] as $key => $number) {
                    $data[$number] = $matches[2][$key];
                }
                
                \Log::info($data);
            
                return;
            }
            
             // Week Code
            if (preg_match('/\b(week|week)\b(?:\s+(\d{4}-\d{2}-\d{2}))?/i', $message, $matches)) {

                $this->sendMessage("...Wait Checking Lenden", $fromnumberwhatsapp);
                $date = $matches[2] ?? Carbon::now()->subWeek()->format('Y-m-d');
                $dates = [];

                    for ($i = 7; $i >= 1; $i--) {
                        $dates[] = Carbon::now()->subDays($i)->format('Y-m-d');
                    }
                    
            
                // your logic here
                
                $whatsappMessage = "Weekly Lenden\n-------------------\nNR ". $checkUser->commission."%\n-------------------\n";
                $whatsappMessage .= $this->getWeeklyLenden($checkUser->id, $dates);
            
            
                $this->sendMessage($whatsappMessage, $fromnumberwhatsapp,$message);
            
                return;
            }
            
            // Balance Code
            if (preg_match('/\b(bal|balance)\b(?:\s+(\d{4}-\d{2}-\d{2}))?/i', $message, $matches)) {

                $this->sendMessage("...Wait Checking Balance", $fromnumberwhatsapp);
                $date = $matches[2] ?? date('Y-m-d'); // default = today
            
                // your logic here
                
                $whatsappMessage = $date ."\n*********\nNR " . $checkUser->commission . "%\n";
                $whatsappMessage .= $this->getBalanceByDate($checkUser->id, $date);
            
            
                $this->sendMessage($whatsappMessage, $fromnumberwhatsapp,$message);
            
                return;
            }
            // Delete Code
            if (preg_match('/\bdelete\b/i', $message)) {
                

                if (preg_match('/\bdelete\s+(\d+)/i', $message, $matches)) {
                    $session_id = $matches[1];
                    
                       $session = $this->session->where('session_id', $session_id)->where('user_id',$checkUser->id)->first();
                       
                       if($session){
                            $this->deleteSession($session->id,$checkUser->id);
                            $whatsappMessage = "Deleted SuccessFully\nTransaction ID  ".$session->session_id." Deleted";
                             $this->sendMessage($whatsappMessage,$fromnumberwhatsapp);
                            DB::commit();
                           return;
                       }
                       $whatsappMessage = "Transaction ID Invalid";
                       $this->sendMessage($whatsappMessage,$fromnumberwhatsapp,$message);
                    return;
                }
                return;
            }
            
            
            // Bets Get Code
            $betCount = 0;
            $categories = [
                'fm' => [],
                'sp' => [],
                'dp' => [],
                'tp' => [],
                'cp' => [],
                'kp' => [],
                'other' => []
            ];
            
            // 👉 Split message into blocks ending with value
            preg_match_all('/(.*?)(\d+\s*rs|=\s*\d+)/i', $message, $blocks, PREG_SET_ORDER);
            
            foreach ($blocks as $block) {
            
                $textPart = $block[1];
                $valuePart = $block[2];
            
                // 👉 Extract value
                if (preg_match('/(\d+)\s*rs/i', $valuePart, $m)) {
                    $value = $m[1];
                } elseif (preg_match('/=\s*(\d+)/', $valuePart, $m)) {
                    $value = $m[1];
                } else {
                    continue;
                }
            
                // =========================
                // ✅ KEEP YOUR CATEGORY LOGIC SAME (JUST USE $textPart)
                // =========================
            
                preg_match_all('/([\d:;\/\'_*+]+)\s*([a-z]+)/i', $textPart, $matches, PREG_SET_ORDER);
            
                foreach ($matches as $match) {
                    $numbersPart = $match[1];
                    $typeString = strtolower($match[2]);
            
                    preg_match_all('/fm|sp|dp|tp|cp|kp/', $typeString, $typeMatches);
                    $types = $typeMatches[0] ?? [];
            
                    if (empty($types)) continue;
            
                    preg_match_all('/\d+/', $numbersPart, $nums);
            
                    foreach ($nums[0] as $num) {
                        foreach ($types as $type) {
                            $betCount++;
            
                            $categories[$type][] = [
                                'number' => $num,
                                'value' => $value
                            ];
                        }
                    }
                }
            
                // =========================
                // ✅ OTHER LOGIC (same but use $textPart)
                // =========================
            
                $cleanedMessage = preg_replace('/([\d:;\/\'_*+]+)\s*[a-z]+/i', '', $textPart);
            
                preg_match_all('/\d+/', $cleanedMessage, $others);
            
                foreach ($others[0] as $num) {
                    $betCount++;
            
                    $categories['other'][] = [
                        'number' => $num,
                        'value' => $value
                    ];
                }
            }
            
            Log::info(count($categories['fm']));
            
            
            // GET STORE Code

           $messageClean = preg_replace('/[^a-z0-9]/', '', $message);

            $stores = $this->store->where('status', 1)->get();
            
            $bestMatch = null;
            $highestPercent = 0;
            
            foreach ($stores as $store) {
            
                $storeName = strtolower(trim($store->name));
            
                $storeClean = preg_replace('/[^a-z0-9]/', '', $storeName);
            
                /**
                 * EXACT MATCH
                 */
                if ($message === $storeName) {
            
                    $bestMatch = $store;
                    $highestPercent = 100;
            
                    break;
                }
            
                /**
                 * CONTAINS MATCH
                 */
                if (
                    str_contains($message, $storeName) ||
                    str_contains($storeName, $message)
                ) {
            
                    similar_text(
                        $messageClean,
                        $storeClean,
                        $percent
                    );
            
                    $percent += 20;
            
                } else {
            
                    similar_text(
                        $messageClean,
                        $storeClean,
                        $percent
                    );
            
                }
            
                /**
                 * BEST MATCH
                 */
                if ($percent > $highestPercent) {
            
                    $highestPercent = $percent;
                    $bestMatch = $store;
            
                }
            
            }
            
            $market = ($highestPercent >= 50)
                ? $bestMatch
                : null;
            
            if(!$market){
                $bitCheck = $this->bit->where('user_id',$checkUser->id)->orderBy('id','DESC')->first();
                if(!$bitCheck){
                   Log::info("No Market Found");
                   $whatsappMessage = "No Market Found";
                       $this->sendMessage($whatsappMessage,$fromnumberwhatsapp);
                    return;
                }
                $market = $this->store->where('id',$bitCheck->stores_id)->where('status',1)->first();
            }
            
           
            
            if(!$market){
                // Send Message Market Invalid
                Log::info("No Market Found");
                $whatsappMessage = "No Market Found";
                       $this->sendMessage($whatsappMessage,$fromnumberwhatsapp);
                 return;
            }
            
             // Result Code
            if (preg_match('/\bresult\b/i', $message)) {

                $this->sendMessage("...Wait Checking Result", $fromnumberwhatsapp);
                
            
                $date = currentDate();
                // your logic here
                
                $whatsappMessage = $date . "\n" .$market->name . "  ";
                $whatsappMessage = $this->getResult($checkUser->id, $market, $whatsappMessage);
            
            
                $this->sendMessage($whatsappMessage, $fromnumberwhatsapp,$message);
            
                return;
            }
            
            
            // Timeout Code
            
        $t = currentDate();
            $day = date("D", strtotime($t));
            $day_id = $this->day->where('name', 'like',  $day . '%')->first()->id;
            
            $storeGame = $this->storeGame->where('stores_day_id',$day_id)->where('stores_id',$market->id)->first();
            $gameType = null;
            
            $time = null;
            Log::info($market);
            Log::info($day_id);
            Log::info($storeGame);
            $openTime = $storeGame->opent_time;
            $closeTime = $storeGame->close_time;
            if(!timeComapre($openTime)){
                $gameType = "OPEN";
                $time = $openTime;
            }
            
            if(!timeComapre($closeTime) && $gameType == null){
                $gameType = "CLOSE";
                $time = $closeTime;
            }
            
            if(!$gameType){
                // Send TimeOut Error
                Log::info("Timeout");
                $whatsappMessage = "Market Timeout";
                       $this->sendMessage($whatsappMessage,$fromnumberwhatsapp);
                return;
            }
            
         
         
         // Bets Distribution Code
            $allBets = "";
            $totalAmount = 0;
            if($betCount > 0){
                $session_id = null;
                do {
                    // generate 4–8 digit random number
                    $session_id = random_int(1000, 99999999);
                
                } while ($this->session->where('session_id', $session_id)->exists());
                
                if($session_id){
                    $session = $this->session->create([
                                                    'session_id' => $session_id,
                                                    'user_id'   => $checkUser->id,
                                                    ]);
                    
                    
                    if(count($categories['fm']) > 0){
                        foreach($categories['fm'] as $fmkey => $fmvalue){
                            Log::info(strlen((string) $fmvalue['number']));
                           
                            if(strlen((string) $fmvalue['number']) == 3){
                                $allBets = $this->PannaFamilyBet($session->id,$market->id,$gameType,$fmvalue['number'],$fmvalue['value'],$time,$day_id,$checkUser,$allBets);
                                $pannas = $this->PannaFamily($fmvalue['number']);
            
                                if($pannas){
                                    
                                    $totalCount = count($pannas);
                                    $totalAmount += $fmvalue['value']*$totalCount;
                                    
                                }
                            }
                            if(strlen((string) $fmvalue['number']) == 2 && $gameType == "OPEN"){
                                $allBets = $this->JodiFamilyBet($session->id,$market->id,$gameType,$fmvalue['number'],$fmvalue['value'],$time,$day_id,$checkUser,$allBets);
                                $pannas = $this->JodiFamily($fmvalue['number']);
            
                                if($pannas){
                                    
                                    $totalCount = count($pannas);
                                    $totalAmount += $fmvalue['value']*$totalCount;
                                    
                                }
                            }
                        }
                    }
                    
                    if(count($categories['sp']) > 0){
                        foreach($categories['sp'] as $spkey => $spvalue){
                           
                               $allBets = $this->SinglePattiBet($session->id,$market->id,$gameType,$spvalue['number'],$spvalue['value'],$time,$day_id,$checkUser,$allBets);
                               $pannas = $this->PannaSp($spvalue['number']);
            
                                if($pannas){
                                    
                                    $totalCount = count($pannas);
                                    $totalAmount += $spvalue['value']*$totalCount;
                                    
                                }
                            
                        }
                    }
                    
                    if(count($categories['dp']) > 0){
                        foreach($categories['dp'] as $dpkey => $dpvalue){
                           
                               $allBets =  $this->DoublePattiBet($session->id,$market->id,$gameType,$dpvalue['number'],$dpvalue['value'],$time,$day_id,$checkUser,$allBets);
                               $pannas = $this->PannaDp($dpvalue['number']);
            
                                if($pannas){
                                    
                                    $totalCount = count($pannas);
                                    $totalAmount += $dpvalue['value']*$totalCount;
                                    
                                }
                            
                        }
                    }
                    
                    if(count($categories['tp']) > 0){
                        foreach($categories['tp'] as $tpkey => $tpvalue){
                           
                               $allBets =  $this->TriplePattiBet($session->id,$market->id,$gameType,$tpvalue['number'],$tpvalue['value'],$time,$day_id,$checkUser,$allBets);
                               $pannas = $this->PannaTp($tpvalue['number']);
            
                                if($pannas){
                                    
                                    $totalCount = count($pannas);
                                    $totalAmount += $tpvalue['value']*$totalCount;
                                    
                                }
                            
                        }
                    }
                    
                    if(count($categories['cp']) > 0){
                        foreach($categories['cp'] as $cpkey => $cpvalue){
                           
                               $allBets =  $this->CyclePattiBet($session->id,$market->id,$gameType,$cpvalue['number'],$cpvalue['value'],$time,$day_id,$checkUser,$allBets);
                               $pannas = $this->CyclePatti($cpvalue['number']);
            
                                if($pannas){
                                    
                                    $totalCount = count($pannas);
                                    $totalAmount += $cpvalue['value']*$totalCount;
                                    
                                }
                            
                        }
                    }
                    
                    if(count($categories['kp']) > 0){
                        foreach($categories['kp'] as $spkey => $kpvalue){
                           
                               $allBets =  $this->KPPattiBet($session->id,$market->id,$gameType,$kpvalue['number'],$kpvalue['value'],$time,$day_id,$checkUser,$allBets);
                               $pannas = $this->PannaKp($kpvalue['number']);
            
                                if($pannas){
                                    
                                    $totalCount = count($pannas);
                                    $totalAmount += $kpvalue['value']*$totalCount;
                                    
                                }
                            
                        }
                    }
                    
                    
                    if(count($categories['other']) > 0){
                        foreach($categories['other'] as $otherkey => $othervalue){
                            Log::info(strlen((string) $othervalue['number']));
                           
                           if (strlen((string) $othervalue['number']) == 3) {

                                $num = (string) $othervalue['number'];
                            
                                // 1️⃣ All same (AAA)
                                if ($num[0] == $num[1] && $num[1] == $num[2]) {
                                    // all same
                                   $allBets =  $this->TriplePannaBet($session->id,$market->id,$gameType,$othervalue['number'],$othervalue['value'],$time,$day_id,$checkUser,$allBets);
                                   $totalAmount += $othervalue['value'];
                                }
                            
                                // 2️⃣ Two same (ONLY AAB or ABB)
                                elseif (
                                    ($num[0] == $num[1] && $num[1] != $num[2]) || // AAB (339)
                                    ($num[1] == $num[2] && $num[0] != $num[1])    // ABB (556)
                                ) {
                                    // valid two same
                                    $allBets = $this->DoublePannaBet($session->id,$market->id,$gameType,$othervalue['number'],$othervalue['value'],$time,$day_id,$checkUser,$allBets);
                                   $totalAmount += $othervalue['value'];
                                }
                            
                                // 3️⃣ All different (ABC)
                                elseif (
                                    $num[0] != $num[1] &&
                                    $num[1] != $num[2] &&
                                    $num[0] != $num[2]
                                ) {
                                    // all different
                                   $allBets =  $this->SinglePannaBet($session->id,$market->id,$gameType,$othervalue['number'],$othervalue['value'],$time,$day_id,$checkUser,$allBets);
                                   $totalAmount += $othervalue['value'];
                                }
                            
                                // ❌ Ignore ABA like 565, 393
                            }
                            
                            if(strlen((string) $othervalue['number']) == 2 && $gameType == "OPEN"){
                               $allBets =  $this->JodiBet($session->id,$market->id,$gameType,$othervalue['number'],$othervalue['value'],$time,$day_id,$checkUser,$allBets);
                                   $totalAmount += $othervalue['value'];
                            }
                            if(strlen((string) $othervalue['number']) == 1){
                               $allBets =  $this->SingleDigitBet($session->id,$market->id,$gameType,$othervalue['number'],$othervalue['value'],$time,$day_id,$checkUser,$allBets);
                               $totalAmount += $othervalue['value'];
                            }
                        }
                    }
                    
                    
                }
                
                
                $balance = totalAmount($checkUser->id);
                
                // if($totalAmount > $balance){
                //     $whatsappMessage = "Insufficient Balance.";
                //       $this->sendMessage($whatsappMessage,$fromnumberwhatsapp);
                //       DB::rollback();
                //       return;
                // }
                //Send Success Message
                
                $totalMarketBetAmount = Bit::where('stores_id',$market->id)->where('type',$gameType)->where('user_id',$checkUser->id)->sum('amount');
                $grandtotal = Bit::where('user_id',$checkUser->id)->sum('amount');
                
                // $whatsappMessage = "Transaction Successful\n\n"."User Name:- ".$checkUser->name
                //                     ."\nTransaction ID:- ".$session->session_id
                //                     ."\n".$market->name ."(".$gameType.")= Total" . $totalAmount
                //                     ."\nGrand Total:-" . $balance
                //                     . "\n\n" . $allBets;
                             $whatsappMessage =     $market->name."-(".$gameType.") = ".$totalAmount
                                                    ."\n\nTID : =".$session->session_id
                                                    ."\nTotal ".$market->name."-(".$gameType.") = ". $totalMarketBetAmount
                                                    ."\n\nNR ".$checkUser->commission."%"
                                                    ."\nGrand Total : =". abs($grandtotal)
                                                    ."\nNo Limit"
                                                    ."\n1  ===> Transaction Successful✅"
                                                    ."\n\n".$allBets;
                                                    
                                                    
                                                    
                                    
                $this->sendMessage($whatsappMessage,$fromnumberwhatsapp,$message);
                DB::commit();
                
            }
            
            
        
        
        }catch (\Exception $error){
            DB::rollback();
            Log::info($error);
            $this->sendMessage('Server Error...Please Try Again Later....!',$fromnumberwhatsapp);
        }
    }

    

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    
    public function sendMessage($message,$mobile_number,$sentMessage = ""){
        $client = new Client();
            
              $response = $client->request('GET', 
                        'https://node.profcymafoundation.com/api/v1/profcyma-apis/send-text', 
                        [
                            'verify' => false, // ðŸ”´ disables SSL verification
                            'query' => [
                                'apikey'       => 'CqfLldqcwN1rc6UDNoz78ly2Kj6t5Awv9nyoKxMO',
                                'instance_key' => 'bFrkIJ8Gk5GeuQT6',
                                'to_sent'      => $mobile_number,
                                'template_id'  => '427799163675',
                                'message'      => $message,
                            ],
                            'headers' => [
                                'Content-Type' => 'application/x-www-form-urlencoded',
                            ],
                        ]
                    );
                    
                    
                    
                  $message =  "Sent User:-\n" .$mobile_number . "\n" . $sentMessage . "\n\n" . $message ;
                    $response1 = $client->request('GET', 
                        'https://node.profcymafoundation.com/api/v1/profcyma-apis/send-text', 
                        [
                            'verify' => false, // ðŸ”´ disables SSL verification
                            'query' => [
                                'apikey'       => 'CqfLldqcwN1rc6UDNoz78ly2Kj6t5Awv9nyoKxMO',
                                'instance_key' => 'bFrkIJ8Gk5GeuQT6',
                                'to_sent'      => '+918180843636',
                                'template_id'  => '427799163675',
                                'message'      => $message,
                            ],
                            'headers' => [
                                'Content-Type' => 'application/x-www-form-urlencoded',
                            ],
                        ]
                    );
    }
}