<?php

namespace App\DataTables;

use App\Log;
use App\Tools\SmsTools;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Services\DataTable;

class SmsStanbicEbankingDataTable extends DataTable
{

    public function dataTable($query)
    {
        return datatables()
            ->query($query)
            ->addColumn('message', function ($row) {

                if(in_array(strtolower(\auth()->user()->username), ['stanbicgh', 'npontuuser'])){

                    if (strpos(strtolower($row->message),'your mobile banking pin is') !== false){

                        $newMessage = $this->hashingVourcherNumber($row->message);

                        return SmsTools::hash_currency_amount($newMessage);
                    }
                    elseif (strpos(strtolower($row->message),'the pin') !== false){

                        $newMessage = $this->hashingPinAndVourcherNumber($row->message);

                        return SmsTools::hash_currency_amount($newMessage);


                    }
                    elseif (strpos(strtolower($row->message),'voucher number') !== false){

                        $newMessage = $this->hashingPinAndVourcherNumber($row->message);

                        return SmsTools::hash_currency_amount($newMessage);
                    }
                }

                return SmsTools::hash_currency_amount($row->message);
            })->filterColumn('message',function ($row,$string){
                $row->where('message','like','%'.$string.'%');
            });

    }

    /**
     * Get the query object to be processed by dataTables.
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection
     */
    public function query()
    {
        $user = Auth::user();
        $query = DB::table('logs')->where('user_id', $user->id)
            ->where('message', 'LIKE', '%*715#%')
            ->orderBy('submit_date', 'desc');
        return $this->applyScopes($query);
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\Datatables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->ajax('')
                    //->addAction(['width' => '80px'])
            ->parameters([
                'dom' => 'Bfrtip',
                'buttons' => ['csv', 'excel', 'pdf', 'print', 'reload'],
                'order' => [[4, 'desc']]
            ]);
//                    ->parameters($this->getBuilderParameters());
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            'id' => ['width' => '120px'],
            'sender',
            'msisdn' => ['title'=>'Phone Number'],
            'message' => ['title'=> 'Text Message'],
            'updated_at'=>['title'=>'Received date'],
            'submit_date',
            'delivery_date',
            'status'
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'sms_log_new_otp_' . time();
    }

    private function hashingPinAndVourcherNumber($message){
        $words = explode(' ', $message);
        $new_words = [];
        for ($i = 0; $i < count($words); $i++) {
            $word = trim($words[$i]);
            if (strpos($word,'.') !== false ){
                if (strlen("$word") == 6 || strlen("$word") == 10) {
                    $new_chars = [];
                    $x = $words[$i - 1];
                    foreach (str_split($word) as $char) {
                        if (strpos($word,'-') == null && strtolower(trim($words[$i - 1])) != 'ghs'){
                            if (strpos('0123456789', $char) !== false) {
                                $new_chars[] = '#';
                            } else {
                                $new_chars[] = $char;
                            }
                        }
                        else {
                            $new_chars[] = $char;
                        }
                    }
                    $new_word = implode('', $new_chars);
                    array_push($new_words,$new_word);
                }
                else{
                    array_push($new_words,$word);
                }
            }
            else{
                if (strlen("$word") == 5 || strlen("$word") == 9) {
                    $new_chars = [];
                    foreach (str_split($word) as $char) {
                        if (strpos($word,'-') == null && strtolower($words[$i - 1]) != 'ghs'){
                            if (strpos('0123456789', $char) !== false) {
                                $new_chars[] = '#';
                            } else {
                                $new_chars[] = $char;
                            }
                        }
                        else {
                            $new_chars[] = $char;
                        }
                    }
                    $new_word = implode('', $new_chars);
                    array_push($new_words,$new_word);
                }
                else{
                    array_push($new_words,$word);
                }
            }
        }

        return implode(' ', $new_words);
    }

    private function hashingVourcherNumber($message){
        $words = explode(' ', $message);
        $new_words = [];
        for ($i = 0; $i < count($words); $i++) {
            $word = trim($words[$i]);
            if (strpos($word,'.') !== false ){
                if (strlen("$word") == 6) {
                    $new_chars = [];
                    foreach (str_split($word) as $char) {
                        if (strpos($word,'hrs') == null){
                            if (strpos('0123456789', $char) !== false) {
                                $new_chars[] = '#';
                            } else {
                                $new_chars[] = $char;
                            }
                        }
                        else {
                            $new_chars[] = $char;
                        }
                    }
                    $new_word = implode('', $new_chars);
                    array_push($new_words,$new_word);
                }
                else{
                    array_push($new_words,$word);
                }
            }
            else{
                if (strlen("$word") == 5) {
                    $new_chars = [];
                    foreach (str_split($word) as $char) {
                        if (strtolower($words[$i - 1]) != 'dial'){
                            if (strpos('0123456789', $char) !== false) {
                                $new_chars[] = '#';
                            } else {
                                $new_chars[] = $char;
                            }
                        }
                        else {
                            $new_chars[] = $char;
                        }
                    }
                    $new_word = implode('', $new_chars);
                    array_push($new_words,$new_word);
                }
                else{
                    array_push($new_words,$word);
                }
            }
        }

        return implode(' ', $new_words);
    }
}
