<?php

namespace App\DataTables;

use App\Log;
use App\Tools\SmsTools;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Yajra\Datatables\Html\Builder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Html\Editor\Editor;

class SmsLog24DataTable extends DataTable
{

    public function dataTable($query)
    {
        return datatables()
            ->query($query)
            ->addColumn('msisdn', function ($row) {
                // Check if ref_id is marked as masked
                if (isset($row->refid) && $row->refid == 'masked') {
                    return $this->maskPhoneNumber($row->msisdn);
                }
                return $row->msisdn;
            })
            ->addColumn('message', function ($row) {

                $user = $this->request()->session()->get('dynamic_user');

                if ($user && $user->group_id == 3) {
                    return ' ';
                }

                // stanbicgh: use only SmsTools::hash_currency_amount so OTP/password are hashed
                // but amounts (USD, GHS, AED, GBP) and Help/Queries numbers stay visible.
                if (strtolower(\auth()->user()->username) == 'stanbicgh') {
                    if (strpos(strtolower($row->message), 'your mobile banking pin is') !== false) {
                        return SmsTools::hash_currency_amount($this->hashingVourcherNumber($row->message));
                    }
                    if (strpos(strtolower($row->message), 'the pin') !== false
                        || strpos(strtolower($row->message), 'voucher number') !== false) {
                        return SmsTools::hash_currency_amount($row->message);
                    }
                    // OTP and all other messages: single hashing pass (no length-based pre-hash)
                    return SmsTools::hash_currency_amount($row->message);
                }

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

    public function query()
    {
        $user = Auth::user();
        $_today = \Carbon\Carbon::today()->toDateString();
        $query = DB::table('logs')->where('user_id', $user->id)
            ->where('submit_date', '>', $_today)
            ->orderBy('submit_date', 'desc');
        return $this->applyScopes($query);
    }

    public function html()
    {
        return $this->builder()
            ->setTableId('test-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom('Bfrtip')
            ->orderBy(1)
            ->buttons(
                Button::make('export'),
                Button::make('print'),
                Button::make('reset'),
                Button::make('reload')
            );
    }

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

    protected function filename()
    {
        return 'log_24h_' . time();
    }

    /**
     * Masks the last 5 digits of a phone number with asterisks
     *
     * @param string $phoneNumber
     * @return string
     */
    private function maskPhoneNumber($phoneNumber)
    {
        if (empty($phoneNumber)) {
            return $phoneNumber;
        }

        $length = strlen($phoneNumber);

        // If phone number is 5 digits or less, mask all digits
        if ($length <= 5) {
            return str_repeat('*', $length);
        }

        // Mask the last 5 digits
        $visiblePart = substr($phoneNumber, 0, $length - 5);
        $maskedPart = str_repeat('*', 5);

        return $visiblePart . $maskedPart;
    }

    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);
    }
}