<?php

    
namespace App\Http\Controllers\API;

use App\Http\Controllers\API\JsonController as JsonController;
use Illuminate\Http\Request;
use App\User;
use App\Account;
use App\Transection;
use Illuminate\Support\Facades\Auth;

    
class SMSController extends JsonController{
    
    public function perseSMS(Request $request){
        $input = $request->getContent();

        //$SMSArray = json_decode($input, true);
        $SMSObj = json_decode($input, true);
        $SMSArray = $SMSObj['sms'];

        
        $persedSMS = array();
        foreach ($SMSArray as $sms) {
            $txn=$this->extractTransectionFromSMS($sms);
            $data = $txn;
            if($data['success']){
                $data["perseStatus"]=1; 

                if(!$data['transectionDate']) $data['transectionDate']=date("d-m-Y");
                if(empty($data['transectionName'])) $data['transectionName']='Transection';

                if($txn['type']=='checkbalance')$this->AddTransectionBalance($data); 

                if($txn['type']=='txnwithbalance'){
                    if($data['balance']!=0){
                        $this->updateBalance($txn['smsId'], $data['accountId'], $data['balance'], true); //calculated balance
                        $data['balance'] = Account::find($data['accountId'])->balance;
                    } else $this->updateBalance($txn['smsId'], $data['accountId'], $data['balance'], false); //exact balance
                }
                if($txn['type']=='txn'){
                    $this->addTransection($data); 
                    $this->updateBalance($txn['smsId'], $data['accountId'], $data['balance'], true); //calculated balance
                    $data['balance'] = Account::find($data['accountId'])->balance;
                    
                }
            }
            array_push($persedSMS, $data);
        }
        $json['persedSMS']=$persedSMS;

        $userid=Auth::user()->id;
        $accounts=\DB::select(config('global.accountsSQL'), [$userid]);
        $json['accounts'] =  $accounts;

        $mgs='Persed successfully';

        return $this->sendResponse($json, $mgs);
        
         
    }
    public function addTransection($input) { 
        $input['userId']= Auth::user()->id;
        $insertid = Transection::create($input)->id;//DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);     
    }
    public function AddTransectionBalance($input) { 
        $data['smsId']=$input['smsId'];
        $data['userId']= Auth::user()->id;
        $data['accountId']= $input['accountId'];
        $data['transectionName']= $input['type'];
        $data['transectionDate']= $input['transectionDate'];
        $data['amount']= $input['balance'];
        $insertid = Transection::create($data)->id;//DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
        $this->updateBalance($input['smsId'], $input['accountId'], $input['balance'], false);
    }
    public function updateBalance($smsId, $accountId, $amount, $addition) { 
        $record=Account::find($accountId);
        if($addition)$newbalance['balance'] = $record->balance+$amount;
        else $newbalance['balance'] = $amount;
        $record->update($newbalance); 
        
    }
    
    
    
    public function extractTransectionFromSMS($sms) { 
        $json["smsId"] = $sms['date'];
        $transections=\DB::select(config('global.existTransectionsCheckSQL'), [$json['smsId'], Auth::user()->id]);
        if (count($transections)<1) {
            //['Transection already exist !'];
            $str=trim($sms['message']);
            $sstr=strtolower($sms['message']);

            $subject = $sstr;
            $pattern = '/\*\d+|\*\d+ |\*\d+/';
            preg_match_all($pattern, $subject, $matches);
            if(!empty($matches[0][0]))$account_last_digit=substr(str_replace('*', '', $matches[0][0]),-4);
            if(!empty($matches[0][1]))$account_last_digit=substr(str_replace('*', '', $matches[0][1]),-4);

            
            $subject = $sstr;
            $pattern = '/\d+-\d+-\d+|\d+\.\d+\.\d+/';
            preg_match($pattern, $subject, $matches);
            if(!empty($matches[0]))$transectionDate=$matches[0]; 


            $subject = str_replace(array(',','-'), '', $sstr);
            $pattern = '/bdt\d+.\d{2}|bdt \d+.\d{2}|tk\d+.\d{2}|tk \d+.\d{2}|\d+.\d{2}bdt\d+|\d+.\d{2} bdt|\d+.\d{2}tk|\d+.\d{2} tk|bdt\d+|tk\d+|bdt \d+|tk \d+/';
            preg_match_all($pattern, $subject, $matches);
            if(!empty($matches[0][0]) && !empty($matches[0][1])){
                $amount = str_replace(array('bdt','tk',' '), array(''), $matches[0][0]); 
                if(strpos($sstr, 'debit') !== false && strpos($sstr, '-'.$amount) !== false){
                    //
                }else if(strpos($sstr, 'debit') !== false){
                    $amount='-'.$amount;
                } else if(strpos($sstr, 'credit') !== false && strpos($sstr, '-'.$amount) !== false){
                    $amount='-'.$amount;
                }
                
                $balance = str_replace(array('bdt','tk',' '), array(''), $matches[0][1]);
                if(strpos($sstr, '-'.$balance) !== false)$balance='-'.$balance;
                $json["type"] = "txnwithbalance";
            }else if(preg_match('/balance/',$sstr) && empty($matches[0][1]) && !empty($matches[0][0])){
                $balance = str_replace(array('bdt','tk',' '), array(''), $matches[0][0]); 
                if(strpos($sstr, '-'.$balance) !== false)$balance='-'.$balance;
                $json["type"] = "checkbalance";
            }else if(!empty($matches[0][0])){
                $amount = str_replace(array('bdt','tk',' '), array(''), $matches[0][0]); 
                if(strpos($sstr, 'debit') !== false && strpos($sstr, '-'.$amount) !== false){
                    //
                }else if(strpos($sstr, 'debit') !== false){
                    $amount='-'.$amount;
                } else if(strpos($sstr, 'credit') !== false && strpos($sstr, '-'.$amount) !== false){
                    $amount='-'.$amount;
                }
                
                $json["type"] = "txn";
            }


            $subject = $sstr;
            $pattern = '/(\(.*\))/';
            preg_match($pattern, $subject, $matches);
            if(!empty($matches[0]))$transectionName=str_replace(array('(',  ')',  ',',  ';',  'trn.type: '), array('','',''), $matches[0]);
            else{
                $pattern = '/(over .*on)/';
                preg_match($pattern, $subject, $matches);
                if(!empty($matches[0]))$transectionName=$matches[0];
                else if(strpos($sstr, 'withdrawn') !== false){              
                    $transectionName = 'Cash Withdrawal';
                }
            } 
            
            
            $json["accountNo"]= $account_last_digit;
            $json['amount']=number_format((float)$amount, 2, '.', '');
            $json["balance"]=number_format((float)$balance, 2, '.', '');
            $json["transectionName"] = ucwords($transectionName);
            $json["transectionDate"] = $transectionDate;
            
           
            if(is_numeric($account_last_digit)){
                $json["success"] = true;
                $json["accountNo"]= $account_last_digit;

                $records=\DB::select(config('global.accountIdFromNoSQL'), [$json["accountNo"], Auth::user()->id]);
                $json["accountId"]= $records[0]->accountId;

                if($records){
                    $banks=\DB::select(config('global.bankNameFromIdSQL'), [$records[0]->bankId]);
                    $json["bankName"]= $banks[0]->bankName;
                }else{
                    $json["perseStatus"]=2; 
                    $json["success"] = false;
                    $json["message"] = $account_last_digit." account not exist for this user !";
                }       
            }else{
                $json["perseStatus"]=2; 
                $json["success"] = false;
                $json["message"] = "Couldn't recognize the message !";
            }
        }else{
                $json["perseStatus"]=2; 
                $json["success"] = false;
                $json["message"] = "Exist !";
        }
        return $json;

    }
    
}