<?php

namespace App\Http\Controllers;

use Config;

use App\Customer;
use App\Media;
use Illuminate\Http\Request;
use App\Services\CustomerService;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Twilio\Rest\Client;

use Carbon\Carbon;

class CustomersController extends Controller
{
    private $customer_ic;
    public function __construct()
    {
        $this->middleware('auth');
        $this->customerService = New CustomerService();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    
    public function index()
    {
        $search = false;
        $api_url = config('api.url');
        $auth_user = Auth::user();
        $idtype = 'nokp';
        $cawangan_info = Http::get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
        $bank = Http::get(config('api.url') . '/api/bank')->json();
        return view('customers.index',compact('search','cawangan_info','bank','api_url','idtype'));
    }

    public function info(Request $request){
        $auth_user = Auth::user();
        $api_url = config('api.url');
        $cawangan_info = Http::get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
        $customers_info = Http::get(config('api.url') . '/api/customers/'. Session::get('noic'))->json();
        if($customers_info){
            $customer_info = $customers_info[0];
        }else{
            $customer_info = $customers_info;
        }

        $bakilelong = Http::get(config('api.url') . '/api/bakilelong/cawangan/' . $auth_user['cawangan'] . '/' . Session::get('noic') . '/baki')->json();
        $rugilelong = Http::get(config('api.url') . '/api/bakilelong/cawangan/' . $auth_user['cawangan'] . '/' . Session::get('noic') . '/rugi')->json();
        
        $request->session()->forget('page_reload');
        $request->session()->forget('norujukan');
        return view('customers.info',compact('cawangan_info','api_url','customer_info','bakilelong','rugilelong'));
    }

    public function search(Request $request){
        // dd($request->all());
        $noic = $request->noic;
        $idtype = $request->customerIDType;
        Session::put('noic', $noic);
        $api_url = config('api.url');
        $auth_user = Auth::user();
        $cawangan_info = Http::get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
        $bank = Http::get(config('api.url') . '/api/bank')->json();
        $customers_info = Http::get(config('api.url') . '/api/customers/'. $noic)->json();

        if($customers_info){
            $customer_info = $customers_info[0];
        }else{
            $customer_info = $customers_info;
        }
        $request->session()->forget('page_reload');
        $request->session()->forget('norujukan');

        $search = true;
        if($customer_info){
            Session::put('customer_info',$customer_info);
            return redirect()->route('customer_info')->with( ['customer_info' => $customer_info,'cawangan_info'=>$cawangan_info,'api_url'=>$api_url]);
        }else{
            return view('customers.index',compact('customer_info','search','noic','cawangan_info','bank','api_url','idtype'));
        }
    }

    //Cari By IC No
    public function cari(Request $request)
    {
        $api_url = config('api.url');
        $customers_info = Http::get(config('api.url') . '/api/customers/'. $request->icno)->json();

        if(sizeof($customers_info) > 0)
            return $customers_info[0];
        else
            return "no-data";
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        // dd($request);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if($request->idtype == 'nokp'){
            $nokpbaru = $request->noic;
            $nokplama = '';
        }elseif($request->idtype == 'passport'){
            $nokpbaru = '';
            $nokplama = $request->noic;
        }
        if($request->warganegara){
            $warganegara = 'Y';
        }else{
            $warganegara = 'N';
        }
        if($request->bumiputera){
            $bumiputera = 'Y';
        }else{
            $bumiputera = 'N';
        }
        if($request->jantina == 'Lelaki'){
            $jantina = 'L';
        }elseif($request->jantina == 'Perempuan'){
            $jantina = 'P';
        }
        $split_date = explode('/',$request->tarikh_lahir);

        $tarikh_lahir = $split_date[2].'-'.$split_date[1].'-'.$split_date[0];
        $tarikhlahir = Carbon::parse($tarikh_lahir);
        $auth_user = Auth::user();
        $latest_customer = Http::get(config('api.url') . '/api/customers/latest/' . $auth_user['cawangan'])->json();
        
        if($latest_customer == null){
            $nosiri_latest = 1;
        }
        else{
            $nosiri_latest = $latest_customer['nosiri']+1;
        }
        
        $count = sprintf("%08d", $nosiri_latest);

        $no_pelanggan = $request->bangsa . substr($request->noic,6,2).'-'.$count;
        $detail_poskod = Http::get(config('api.url') . '/api/poskod/' . $request->poskod)->json();

        $customer_info = Http::post(config('api.url') . '/api/customers/create/'. $auth_user['cawangan'],[
            'kodcaw' => $auth_user['cawangan'],
            'nopelanggan' => $no_pelanggan,
            'nokpbaru' => $nokpbaru,
            'nokplama' => $nokplama,
            'nama' => $request->name,
            't_lahir' => $tarikhlahir->toDateString(),
            'jantina' => $jantina,
            'alamat' => $request->alamat,
            'poskod' => $request->poskod,
            'koddaerah' => $detail_poskod['koddaerah'],
            'kodnegeri' => $detail_poskod['kodnegeri'],
            'telefon' => $request->main_phone,
            'bumiputra' => $bumiputera,
            'warganegara' => $warganegara,
            'bangsa' => $request->bangsa,
            'kodugama' => $request->agama,
            'kodbank' => $request->bank_name,
            'noakaun' => $request->no_akaun,
            'teller' => $auth_user['name'],
            'telefon2' => $request->alternate_phone,
            'nosiri' => $nosiri_latest,
            'nota'=>$request->nota,
            'kodkerja'=>$request->pekerjaan,
            'tujuangadai'=>$request->tujuan_gadai,
        ]);
        
        Session::put('customer_info',$customer_info);
        return redirect()->route('customer_info')->with( ['customer_info' => $customer_info] );
    }

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

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function destroy(Customer $customer)
    {
        //
    }

    public function getOTP(Request $request){
        $auth_user = Auth::user();
        $expired = Carbon::now();
        $expired = new Carbon();
        $expired = $expired->addHours(24); 
        
        $nokp = $request->noic_otp;
        $customer = Http::get(config('api.url'). '/api/customers/'.$nokp)->json();
        $recipient = '+6'.$customer[0]['telefon'];
        //pembinaan token
        function token($length) {
            $characters = array(
                "A","B","C","D","E","F","G","H","J","K","L","M",
                "N","P","Q","R","S","T","U","V","W","X","Y","Z",
                "a","b","c","d","e","f","g","h","i","j","k","m",
                "n","o","p","q","r","s","t","u","v","w","x","y","z",
                "1","2","3","4","5","6","7","8","9");
            if ($length < 0 || $length > count($characters)) return null;
            shuffle($characters);
            return implode("", array_slice($characters, 0, $length));
        }

        $otp_token = Http::get(config('api.url') . '/api/otp/' . $nokp) ->json();
        $otp_token_used = Http::get(config('api.url') . '/api/otp/used/' . $nokp) ->json();

        if (is_array($otp_token) || is_object($otp_token)){
            if($otp_token){
                return response(['error' => "OTP Akaun Telah Di Jana"]);
            }else{
                if (is_array($otp_token_used) || is_object($otp_token_used)){
                    if($otp_token_used){
                        return response(['error' => "Pelanggan Sudah Mendaftar Pada Customer Portal"]);
                    }else{
                        $random = token(6);
    
                        $otp_baru = Http::post(config('api.url'). '/api/otp/generateotp/' . $nokp,[
                            'otptoken' => $random,
                            'expired' => $expired,
                            'kodcaw' => $auth_user['cawangan']
                        ]);
                        $message = "Your TAC code is " . $random;
                        $this->sendWhatsAppMessage($message, $recipient);
                        return response()->json(['otp'=>$random]);
                    }
                }else{
                    $random = token(6);
        
                    $otp_baru = Http::post(config('api.url'). '/api/otp/generateotp/' . $nokp,[
                        'otptoken' => $random,
                        'expired' => $expired,
                        'kodcaw' => $auth_user['cawangan']
                    ]);
                    $message = "Your TAC code is " . $random;
                    $this->sendWhatsAppMessage($message, $recipient);
                    return response()->json(['otp'=>$random]);
                }
            }
        }else{
            if (is_array($otp_token_used) || is_object($otp_token_used)){
                if($otp_token_used){
                    return response(['error' => "Pelanggan Sudah Mendaftar Pada Customer Portal"]);
                }else{
                    $random = token(6);

                    $otp_baru = Http::post(config('api.url'). '/api/otp/generateotp/' . $nokp,[
                        'otptoken' => $random,
                        'expired' => $expired,
                        'kodcaw' => $auth_user['cawangan']
                    ]);
                    $message = "Your TAC code is " . $random;
                    $this->sendWhatsAppMessage($message, $recipient);
                    return response()->json(['otp'=>$random]);
                }
            }else{
                $random = token(6);
    
                $otp_baru = Http::post(config('api.url'). '/api/otp/generateotp/' . $nokp,[
                    'otptoken' => $random,
                    'expired' => $expired,
                    'kodcaw' => $auth_user['cawangan']
                ]);
                $message = "Your TAC code is " . $random;
                $this->sendWhatsAppMessage($message, $recipient);
                return response()->json(['otp'=>$random]);
            }
        }
    }

    public function listenToReplies(Request $request)
    {
        $from = $request->input('From');

        $message = "Someone send you a message on whatsapp";

        $this->sendWhatsAppMessage($message, $from);

        return;
    }

    public function sendWhatsAppMessage(string $message, string $recipient)
    {
        $twilio_whatsapp_number = getenv('TWILIO_WHATSAPP_NUMBER');
        $account_sid = getenv("TWILIO_SID");
        $auth_token = getenv("TWILIO_AUTH_TOKEN");
        $from = "whatsapp:".$twilio_whatsapp_number;
        $to = "whatsapp:".$recipient;

        $client = new Client($account_sid, $auth_token);
        return $client->messages->create($to, array('from' => $from, 'body' => $message));
    }

}
