<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;
use Illuminate\Support\Arr;
use App\Jobs\SendNewUssdClientEmail;
use App\Jobs\SendUssdClientActiveEmail;
use App\Jobs\SendNewNotesEmailAlert;
use App\Jobs\SendOnboardingCompletedEmailAlert;
use App\Jobs\SendShortCodeListToFinance;
use App\Http\Requests;
use Carbon\Carbon;
use App\Libs\PaperLessNgx;
use Spatie\Activitylog\Models\Activity;

class ClientsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(){
        $data = [
            'page_title' => 'Clients',
            'current_user' => session('current_user')
        ];
        return view('client.index-tabulator', $data);
    }
    public function indexInactive(){
        $data = [
            'page_title' => 'Inactive Clients',
            'current_user' => session('current_user')
        ];
        // dd('foo bar');
        return view('client.index-inactive', $data);
    }
    public function indexBak(){
        $client_arr = new Models\Client;
        $client_arr = $client_arr->with('auth_user_info','country_info', 'created_by_info')->orderBy('name', 'ASC')->paginate(10);
        $data = [
            'page_title' => 'Clients',
            'current_user' => session('current_user')
        ];
        return view('client.index-rawjs', $data);
    }
    public function getClientJson(Request $request){
        
        $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->join('flags AS flags', 'flags.country', '=', 'clients.country')
            ->select('clients.id', 'clients.name', 'clients.status','clients.progress_indicator_score', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy', 'flags.url AS theflag')
            ->orderBy('name', 'ASC')
            ->get();
            // ->paginate(15);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->join('flags AS flags', 'flags.country', '=', 'clients.country')
            ->select('clients.id','clients.name', 'clients.status', 'clients.progress_indicator_score','clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy', 'flags.url AS theflag')
            ->whereRaw("clients.name like '%$keyword%' or clients.status like '%$keyword%' OR clients.country like '%$keyword%' OR aumngr.name like '%$keyword%' OR aumodify.name like '%$keyword%' OR clients.progress_indicator_score like '%$keyword%'")
            ->orderBy('name', 'ASC')
            ->get();
            // ->paginate(15);
        }

        return response()->json($client_arr);
    }
    public function getClientJsonRawJs(Request $request){
        #$client_arr = new Models\Client;
        #$client_arr = $client_arr->with('auth_user_info','country_info', 'created_by_info', 'modified_by_info')->orderBy('name', 'ASC')->paginate(20);
        //$this->log_query();
        $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->select('clients.id', 'clients.name', 'clients.status', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy')
            
            ->paginate(10);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->select('clients.id','clients.name', 'clients.status', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy')
            ->whereRaw("clients.name like '%$keyword%' or clients.status like '%$keyword%' OR clients.country like '%$keyword%' OR aumngr.name like '%$keyword%' OR aumodify.name like '%$keyword%'")
            ->paginate(10);
        }
        return response()->json($client_arr);
    }

    public function getInactiveClientJson(Request $request){
        
        $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->join('flags AS flags', 'flags.country', '=', 'clients.country')
            ->select('clients.id', 'clients.name', 'clients.status','clients.progress_indicator_score', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy', 'flags.url AS theflag')
            ->whereRaw("status = 'inactive'")
            ->orderBy('name', 'ASC')
            ->get();
            // ->paginate(15);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->join('flags AS flags', 'flags.country', '=', 'clients.country')
            ->select('clients.id','clients.name', 'clients.status', 'clients.progress_indicator_score','clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy', 'flags.url AS theflag')
            ->whereRaw("status = 'inactive'")
            ->whereRaw("clients.name like '%$keyword%' or clients.status like '%$keyword%' OR clients.country like '%$keyword%' OR aumngr.name like '%$keyword%' OR aumodify.name like '%$keyword%' OR clients.progress_indicator_score like '%$keyword%'")
            ->orderBy('name', 'ASC')
            ->get();
            // ->paginate(15);
        }

        return response()->json($client_arr);
    }
    public function getInacticeClientJsonRawJs(Request $request){
        $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->select('clients.id', 'clients.name', 'clients.status', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy')
            ->whereRaw("status = 'inactive'")
            ->paginate(10);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $client_arr = \DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->select('clients.id','clients.name', 'clients.status', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy')
            // ->where('status', 'inactive')
            ->whereRaw("status = 'inactive'")
            ->whereRaw("clients.name like '%$keyword%' or clients.status like '%$keyword%' OR clients.country like '%$keyword%' OR aumngr.name like '%$keyword%' OR aumodify.name like '%$keyword%'")
            ->paginate(10);
        }
        return response()->json($client_arr);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $countries = Models\Country::pluck('en_short_name','en_short_name');
        $service_type = Models\Service::pluck('name', 'name');
        $payment_type = ['Prepaid' => 'Prepaid', 'Postpaid' => 'Postpaid'];  //Models\PaymentType::pluck('name', 'id');
        $auth_users = Models\SystemUser::pluck('name', 'id');
        $status = ['Live' => 'Live', 'inactive' => 'Inactive', 'Prospective' => 'Prospective', 'Cancelled' => 'Cancelled'];
        $currency = Models\Currency::pluck('name','name');
        $company_types = ['Aggregator/Supplier' => 'Aggregator/Supplier', 'Enterprise' => 'Enterprise', 'Hybrid' => 'Hybrid'];
        $industries = Models\Industry::orderBy('name', 'ASC')->pluck('name', 'name');
        // $industries = Models\Industry::pluck('name', 'name')->orderBy('name', 'ASC');

        $data = [
            'page_title' => 'Create Client',
            'countries' => $countries,
            'service_type' => $service_type,
            'status' => $status,
            'currency' => $currency,
            'auth_users' => $auth_users,
            'payment_type' => $payment_type,
            'company_types' => $company_types,
            'industries' => $industries
        ];

        return view('client.create', $data);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request){
        $request->validate([
            'name' => 'required|unique:clients,name',
            'email' => 'required|email',
            'services' => 'required',
            'country' => 'required',
            'status' => 'required',
            'payment_mode' => 'required',
            'currency' => 'required',
            'company_type' => 'required',
            'industry' => 'required',
            'auth_user_id' => 'required', // account manager
        ]);

        $onboarding_stages = Models\ClientOnboardingMainStage::orderBy('stage_id')->get();
        // dd($onboarding_stages);
        $client_current_stages = [];

        foreach ($onboarding_stages as $value) {
            $client_current_stages[$value->stage] = "PENDING";
        }

        $client_arr = [
          'name' => $request->name,
          'email' => $request->email,
          'country' => $request->country,
          'status' => $request->status,
          'pay_mode' => $request->payment_mode,
          'currency' => $request->currency,
          'auth_user_id' => $request->auth_user_id, // account manager
          'created_by' => session('current_user.id'),
          'last_modified_by' => session('current_user.id'),
          'progress_indicator_score' => 10,
          'progress_indicator' => $onboarding_stages[0]->stage, // 'Agreement Stage', //
          'onboarding_progress_stage' => json_encode($client_current_stages)
        ];
        if ($request->has('notes')) {
            $client_arr['notes'] = $request->notes;
        }
        if ($request->has('services')) {
            $client_arr['services'] = json_encode($request->services);
        }
        if ($request->has('phone')) {
            $client_arr['phone'] = $request->phone;
        }
        if ($request->has('skype_name')) {
            $client_arr['skype_name'] = $request->skype_name;
        }
        if ($request->has('linkedin_name')) {
            $client_arr['linkedin_name'] = $request->linkedin_name;
        }
        if ($request->has('contact_person')) {
            $client_arr['contact_person'] = $request->contact_person;
        }
        if ($request->has('company_type')) {
            $client_arr['company_type'] = $request->company_type;
        }
        if ($request->has('industry')) {
            $client_arr['industry'] = $request->industry;
        }
        if ($request->has('payment_mode')) {
            $client_arr['pay_mode'] = $request->payment_mode;
        }

        $result = Models\Client::create($client_arr);

        //add entries for client_onboarding_progress
        $get_stage_subs_items = Models\ClientOnboardingSubItem::get();
        foreach ($get_stage_subs_items as $value) {
            $progress_arr = [
                'stage_id' => $value->stage_id,
                'client_id' => $result->id,
                'name' => $value->name,
                'status' => 'PENDING'
            ];
            $clients_onboarding_progress = Models\ClientOnboardingProgress::create($progress_arr);
        }

        if (in_array('USSD', $request->services)) {
          \Log::info('ussd client detected');
          $ussd_client_payment_arr = [
            'client_id' => $result->id,
            'last_modified_by_id' => session('current_user.id')
          ];
          $retval = Models\UssdClientPayment::create($ussd_client_payment_arr);
          //TODO send an email to jim/priscilla about new USSD client,
          #dispatch(new SendNewUssdClientEmail($result));
        }
        #save services this has been moved to the main client table
        //$retval = $this->store_services($request->services, $result->id);
        $client_name = $result->name;
        $activity_arr = [
            'type' => 'staff',
            'content' => session('current_user.name') . " added a new client ($client_name) successfully!",
            'user_id' => session('current_user.id'),
            'ip_address' => \Request::ip(),
            'device' => $request->header('User-Agent')
        ];
        $retval = Models\UserActivity::create($activity_arr);
        Session::flash('success_message', 'Client successfully added');
        return redirect(url('clients'));
    }
    public function notesStore(Request $request){
        $request->validate([
            'client_id' => 'required',
            'notes_body' => 'required'
        ]);
        $auth_user = session('current_user');
        $notes_arr = [
          'notes_body' => $request->notes_body,
          'services' => implode(',', $request->services),
          'auth_user_id' => $auth_user['id'],
          'client_id' => $request->client_id
        ];
        if ($request->has('highlight')) {
            $notes_arr['highlight'] = 'YES';
        }

        $result = Models\ClientNote::updateOrCreate(['services' =>  $request->services, 'client_id' => $request->client_id, 'auth_user_id' => $auth_user['id'] ], $notes_arr);
        // dd($result);
        $client = Models\Client::find($request->client_id);
        $notes = Models\ClientNote::with('client_info', 'created_by_info')->find($result->id);
        //todo : send emails
        dispatch(new SendNewNotesEmailAlert($notes));

        if ($result) {
            $data = ['code' => 1, 'msg' => 'Notes successfully added'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") Added a new Note for : " . $client->name;
        $this->logUsersActivity($type = 'staff', $content);
        return response()->json($data, 200);
    }
    public function getSingleNote($id){
        $note = Models\ClientNote::find($id);
        if ($note) {

            $current_date = date_create(date('Y-m-d'));
            // dump($current_date);
            $expiry_date = date_create($note->created_at);
            // dump($expiry_date);
            $diff = date_diff($current_date, $expiry_date);
            $days = $diff->format("%a");
            // dd($days);
            if ($days > 7) {
                return response()->json([ 'code' => 5, 'msg' => 'This Note has been locked for editing']);
            }

            $services_arr = explode(',', $note->services);

            return response()->json([ 'code' => 1, 'result' => $note, 'services_arr' => $services_arr, 'days' => $days]);
        }
        else{
            return response()->json([ 'code' => 3, 'msg' => 'Request could not be handled at this time']);
        }

    }
    public function notesUpdate(Request $request){
        $request->validate([
            'client_id' => 'required',
            'notes_body' => 'required'
        ]);
        $auth_user = session('current_user');
        $note = Models\ClientNote::find($request->note_id);
        $note->notes_body = $request->notes_body;
        $note->services = implode(',', $request->services);

        if ($request->has('highlight')) {
            $note->highlight = 'YES';
        }
        $result = $note->save();

        $notes = Models\ClientNote::with('client_info', 'created_by_info')->find($request->note_id);

        //dispatch(new SendNewNotesEmailAlert($notes));

        if ($result) {
            $data = ['code' => 1, 'msg' => 'Notes successfully updated'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") Updated a Note";
        $this->logUsersActivity($type = 'staff', $content);
        return response()->json($data, 200);
    }
    public function financeStore(Request $request){
        $request->validate([
            'client_id' => 'required',
            'services' => 'required',
            'invoice_number' => 'required',
            'invoice_amount' => 'required|numeric',
            'invoice_date' => 'required',
            'invoice_status' => 'required',
            // 'short_code' => 'sometimes|numeric'
        ]);
        $auth_user = session('current_user');
        
        if ($request->short_code !== null) {
            $check = is_numeric($request->short_code);
            if ($check == false) {
              $data = ['code' => 3, 'msg' => 'Short Code must be a number'];
              return response()->json($data, 200);
            }
        }
        
        $finance_arr = [
          'invoice_number' => $request->invoice_number,
          'invoice_amount' => $request->invoice_amount,
          'invoice_date' => $request->invoice_date,
          'invoice_status' => $request->invoice_status,
          'short_code' => ($request->short_code) ? $request->short_code : "",
          'services' => implode(',', $request->services),
          'user_id' => $auth_user['id'],
          'client_id' => $request->client_id
        ];
        if ($request->has('remarks')) {
            $finance_arr['remarks'] = $request->remarks;
        }
        $client = Models\Client::find($request->client_id);
        $result = Models\ClientPayment::updateOrCreate(['invoice_number' =>  $request->invoice_number, 'client_id' => $request->client_id, ], $finance_arr);
        if ($request->has('short_code')) {
            $short_code_list = Models\ClientShortCode::where('client_id', $request->client_id)->get();
            $client = Models\Client::find($request->client_id);
            $message_body = $auth_user['name'] . " has added a new Short Code ($request->short_code) Payment entry for " . $client->name;
            
            dispatch(new SendShortCodeListToFinance($short_code_list, $message_body, $finance_arr));
        }

        #$payments = Models\ClientPayment::with('client_info', 'created_by_info')->find($result->id);
        if ($result) {
            $data = ['code' => 1, 'msg' => 'Payment Details successfully added'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") Added a payment record for : " . $client->name;
        $this->logUsersActivity($type = 'staff', $content);
        return response()->json($data, 200);
    }
    public function supportFeesStore(Request $request){
        $request->validate([
            'client_id' => 'required',
            'services' => 'required',
            'invoice_number' => 'required',
            // 'invoice_amount' => 'required|numeric',
            'invoice_date' => 'required',
            'status' => 'required',
            'recurring' => 'required'
        ]);
        $auth_user = session('current_user');

        // dd($request->all());
        $support_fees_arr = [
          'invoice_number' => $request->invoice_number,
          'recurring' => $request->recurring,
          'invoice_date' => $request->invoice_date,
          'invoice_status' => $request->status,
          'services' => implode(',', $request->services),
          'user_id' => $auth_user['id'],
          'status' => $request->status,
          'client_id' => $request->client_id
        ];
        if ($request->has('remarks')) {
            $support_fees_arr['remarks'] = $request->remarks;
        }
        $result = Models\ClientSupportFees::create($support_fees_arr);
        $client = Models\Client::find($request->client_id);
        #$payments = Models\ClientPayment::with('client_info', 'created_by_info')->find($result->id);
        if ($result) {
            $data = ['code' => 1, 'msg' => 'Support Fees Details successfully added'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") Added a support fees record for : " . $client->name;
        $this->logUsersActivity($type = 'staff', $content);
        return response()->json($data, 200);
    }
    public function shortcodeStore(Request $request){
        $request->validate([
            'client_id' => 'required',
            'network' => 'required',
            'shortcode' => 'required',
            'code_type' => 'required',
            'toll_free' => 'required',
            'status' => 'required',
            'remarks' => 'required',
            'launch_date' => 'required',
            'expiry_date' => 'required',
            'monthly_fee' => 'sometimes'
        ]);
        // dd($request->all());
        $auth_user = session('current_user');
        #$network = Models\NetworkOps::find($request->network);
        // $mnoCountry = $this->getMNO($request->network);
        // if ($mnoCountry == false) {
        //   $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        //   return response()->json($data, 200);
        // }
        /*
        $networks_raw = [
            'AirtelTigo GH' => 'AirtelTigo GH',
            'MTN GH' => 'MTN GH',
            'Airtel MW' => 'Airtel MW',
            'Airtel Zambia' => 'Airtel Zambia',
            'TNM MW' => 'TNM MW',
            'Airtel MW' => 'Airtel MW',
            'Safaricom Kenya' => 'Safaricom Kenya',
            'Airtel Kenya' => 'Airtel Kenya',
            'Telkom Kenya' => 'Telkom Kenya',
            'Orange Kenya' => 'Orange Kenya'
        ];
        if (stripos($request->network, 'MW') !== false ) {
            $country = 'Malawi';
        }
        elseif (stripos($request->network, 'GH') !== false) {
            $country = 'Ghana';
        }
        elseif (stripos($request->network, 'Zambia') !== false) {
            $country = 'Zambia';
        }
        elseif (stripos($request->network, 'Bots') !== false) {
            $country = 'Botswana';
        }
        elseif (stripos($request->network, 'KE') !== false) {
            $country = 'Kenya';
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
            return response()->json($data, 200);
        }
        */

        $shortcode_arr = [
          'name' => $request->name,
          'client_id' => $request->client_id,
          'network' => $request->network,
          // 'country' => $mnoCountry, //$network->country,
          'shortcode' => $request->shortcode,
          'code_type' => $request->code_type,
          'toll_free' => $request->toll_free,
          'last_updated_by' => $auth_user['id'],
          'launch_date' => $request->launch_date,
          'expiry_date' => $request->expiry_date,
          'status' => $request->status

        ];

        // dd($shortcode_arr);
        if ($request->has('remarks')) {
            $shortcode_arr['remarks'] = $request->remarks;
        }
        if ($request->has('monthly_fee')) {
            $shortcode_arr['monthly_fee'] = $request->monthly_fee;
        }
        
        $result = Models\ClientShortCode::create($shortcode_arr);
        $client = Models\Client::find($request->client_id);
        if ($result) {
            $data = ['code' => 1, 'msg' => 'ShortCode Details successfully added'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") Added new short code for " . $client->name;
        $this->logUsersActivity($type = 'staff', $content);
        return response()->json($data, 200);
    }
    public function financeUpdate(Request $request){
        $request->validate([
            'payment_id' => 'required',
            'client_id' => 'required',
            'services' => 'required',
            'invoice_number' => 'required',
            'invoice_amount' => 'required|numeric',
            'invoice_date' => 'required',
            'invoice_status' => 'required'
        ]);
        
        $auth_user = session('current_user');
        $payment = Models\ClientPayment::findOrFail($request->payment_id);

        $payment->invoice_number = $request->invoice_number;
        $payment->invoice_amount = $request->invoice_amount;
        $payment->invoice_date = $request->invoice_date;
        $payment->invoice_status = $request->invoice_status;
        $payment->short_code = ($request->short_code) ? $request->short_code : "";

        $payment->services = implode(',', $request->services);
        $result = $payment->save();
        $client = Models\Client::find($request->client_id);
        if ($request->has('short_code')) {
            $short_code_list = Models\ClientShortCode::where('client_id', $request->client_id)->get();
            
            $finance_arr = [
              'invoice_number' => $request->invoice_number,
              'invoice_amount' => $request->invoice_amount,
              'invoice_date' => $request->invoice_date,
              'invoice_status' => $request->invoice_status,
              'short_code' => ($request->short_code) ? $request->short_code : "",
              'services' => implode(',', $request->services),
              'user_id' => $auth_user['id'],
              'client_id' => $request->client_id
            ];
            if ($request->has('remarks')) {
                $finance_arr['remarks'] = $request->remarks;
            }
            $message_body = $auth_user['name'] . " has updated a Short Code ($request->short_code) Payment entry for " . $client->name;
            #dispatch(new SendShortCodeListToFinance($short_code_list, $message_body, $finance_arr));
        }
        
        if ($result) {
            $data = ['code' => 1, 'msg' => 'Payment Details successfully updated'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") updated an existing payment record for " . $client->name;
        $this->logUsersActivity($type = 'staff', $content);


        
        return response()->json($data, 200);
    }
    public function shortCodeUpdate(Request $request){
        $request->validate([
            'client_id' => 'required',
            'network' => 'required',
            'shortcode' => 'required',
            'code_type' => 'required',
            'toll_free' => 'required',
            'monthly_fee' => 'sometimes',
            'status' => 'required',
            'remarks' => 'required',
            'launch_date' => 'required',
            'expiry_date' => 'required'
        ]);
        $auth_user = session('current_user');
        $mnoCountry = $this->getMnoCountry($request->network);
        if ($mnoCountry == false) {
          $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
          return response()->json($data, 200);
          // code...
        }
        $shortcode_arr = [
          'name' => $request->name,
          'client_id' => $request->client_id,
          'network' => $request->network,
          'country' => $mnoCountry, //$network->country,
          'shortcode' => $request->shortcode,
          'code_type' => $request->code_type,
          'toll_free' => $request->toll_free,
          'last_updated_by' => $auth_user['id'],
          'launch_date' => $request->launch_date,
          'expiry_date' => $request->expiry_date,
          'status' => $request->status
        ];
        if ($request->has('remarks')) {
            $shortcode_arr['remarks'] = $request->remarks;
        }
        if ($request->has('monthly_fee')) {
            $shortcode_arr['monthly_fee'] = $request->monthly_fee;
        }
        // $payment = Models\ClientShortCode::findOrFail($request->shortcode_id);
        $result = Models\ClientShortCode::where('id', $request->shortcode_id)->update($shortcode_arr);

        if ($result) {
            $data = ['code' => 1, 'msg' => 'Short Code Details successfully updated'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") updated short code enty for " . $request->short_code;
        $this->logUsersActivity($type = 'staff', $content);
        return response()->json($data, 200);
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id){
        $showclient = Models\Client::with('service_info', 'country_flag_info', 'auth_user_info', 'short_code_info')->find($id);
        //$clientModel = new Models\Client;
        /*
        $currentuser = session('current_user.name');
        $user_model = Models\SystemUser::find(session('current_user.id'));
        activity()->performedOn($showclient)
        ->causedBy($user_model)
        ->log($currentuser . ' Opened the page for : ' . $showclient->name . date('Y-m-d H:i:s'));
        */
        // dd(json_decode($showclient->progress_indicators, true));
        /*
        "Initial talks\/ discussions",
        "Agreement Shared",
        "Agreement signed by one party (Click Mobile\/ Client)",
        "The agreement signed by both parties but interconnectivity has yet to begin",
        "Connectivity details pending on Click Mobile side.","Integration initiated"
        ]
        */

        $progress_indicators = Models\ClientIndicator::pluck('name', 'name');
        $service_type = Models\Service::pluck('name', 'id');
        $service_type_names = Models\Service::pluck('name', 'name');
        $show_services = Models\ClientCategory::where('client_id', $id)->get();
        //$networks_raw = ['AirtelTigo GH' => 'AirtelTigo GH','MTN GH' => 'MTN GH', 'Airtel MW' => 'Airtel MW', 'Airtel Zambia' => 'Airtel Zambia', 'TNM MW' => 'TNM MW', 'Airtel MW' => 'Airtel MW'];
        // $networks_raw_two = Models\NetworkOps::pluck('country', 'id');
        // dd($networks_raw_two);
        $country_networks = \DB::table('network_operators')->Select(\DB::raw('id, concat(name, " (", country, ")") AS network'))->orderBy('network')->pluck('network', 'network');
        // $country_networks = \DB::table('network_operators')->Select(\DB::raw('concat(name, " (", country, ")") AS network)')->orderBy('network')->get()->toArray();
        // $country_networks = \DB::table('network_operators')->Select(\DB::raw('concat(name, " (", country, ")") AS network)'))->pluck('network', 'network');
        
        $networks_raw = [
            'AirtelTigo GH' => 'AirtelTigo GH',
            'MTN GH' => 'MTN GH',
            'Airtel MW' => 'Airtel MW',
            'Airtel Zambia' => 'Airtel Zambia',
            'TNM MW' => 'TNM MW',
            'Airtel MW' => 'Airtel MW',
            'Safaricom Kenya' => 'Safaricom Kenya',
            'Airtel Kenya' => 'Airtel Kenya',
            'Telkom Kenya' => 'Telkom Kenya',
            'Orange Kenya' => 'Orange Kenya'
        ];
        // dd($networks_raw);
        //->where('highlight', 'NO')
        $show_notes = Models\ClientNote::with('created_by_info', 'client_info')->where('client_id', $id)->orderBy('created_at', 'DESC')->get()->take(20);
        $show_notes_highlight = Models\ClientNote::with('created_by_info', 'client_info')->where('client_id', $id)->where('highlight', 'YES')->orderBy('created_at', 'DESC')->get()->take(1);

        $voice_codes = Models\ClientShortCode::where('client_id', $id)->where('code_type', 'voice')->get();
        $sms_codes = Models\ClientShortCode::where('client_id', $id)->where('code_type', 'sms')->get();
        $ussd_codes = Models\ClientShortCode::where('client_id', $id)->where('code_type', 'ussd')->get();
        $recent_payments = Models\ClientPayment::where('client_id', $id)->orderBy('id', 'DESC')->get();

        $countries = Models\Country::pluck('en_short_name','en_short_name');
        // dd($countries);
        $networks = Models\NetworkOps::pluck('name', 'id');
        $support_fees = Models\ClientSupportFees::where('client_id', $id)->orderBy('id', 'DESC')->get();

        $showdocuments = Models\ClientFile::where('client_id', $id)->get();
        //$client_sender_ids = Models\SenderId::with('network_info', 'created_by_info')->where('client_id', $id)->orderBy('senderid', 'ASC')->get();
        // dd($showdocuments[0]->name);
        if ($showclient->status == 'Live') {
            $status_bg = "info";
        }
        elseif ($showclient->status == 'Prospective') {
            $status_bg = "warning";
        }
        else{
            $status_bg = "danger";
        }
        // dd($showclient->progress_indicator_score);
        if ($showclient->progress_indicator_score >= 70) {
            $progress_status_bg = "success";
        }
        elseif ($showclient->progress_indicator_score >= 50 &&  $showclient->progress_indicator_score < 70) {
            $progress_status_bg = "warning";
        }
        else{
            $progress_status_bg = "danger";
        }
        // dump($progress_status_bg);

        $renewal_due = 'N/A';
        $highlight_colour = 'none';
        //review this later
        if ($showclient->contract_validity == null || $showclient->contract_validity == '') {
            $renewal_due = "N/A";
        }
        else{
            $expiry_date = Carbon::parse($showclient->contract_validity);
            $current_date = Carbon::parse(date('Y-m-d'));

            $polar = ($expiry_date < $current_date) ? "-" : "+";
            $days = $expiry_date->diffInDays($current_date);
            if($days > 365){
                if ($polar == '-') {
                    $highlight_colour = 'warning';
                    $renewal_due = "Contract expired " . floor($days/365) . " year(s) ago";

                }
                else{
                    $renewal_due = "In " . floor($days/365) . " year(s)";
                }
            }
            elseif($days > 31){
                if ($polar == '-') {
                    $highlight_colour = 'warning';
                    $renewal_due = "Contract expired " . floor($days/31) . " month(s) ago";

                }
                else{
                    $renewal_due = "In " . floor($days/31) . " months";
                }
            }
            else{

                if ($polar == '-') {
                    $highlight_colour = 'warning';
                    $renewal_due = "Contract expired $days days(s) ago";
                }
                else{
                    $renewal_due = "In $days day(s)" ;
                }
            }
        }

        sort($networks_raw);
        $recurring_arr = ['NO' => 'NO', 'Monthly' => 'Monthly', 'Quarterly' => 'Quarterly', 'Semiannual' => 'Semiannual', 'Yearly' => 'Yearly'];
        $sender_id_statuses = ['Pending' => 'Pending', 'Inactive' => 'Inactive', 'Approved' => 'Approved'];
        $data = [
            'page_title' => 'Client Profile',
            'showclient' => $showclient,
            'show_services' => $show_services,
            'service_type' => $service_type,
            'service_type_names' => $service_type_names,
            'show_notes' => $show_notes,
            'show_notes_highlight' => $show_notes_highlight,
            'status_bg' => $status_bg,
            'progress_status_bg' => $progress_status_bg,
            'voice_codes' => $voice_codes,
            'sms_codes' => $sms_codes,
            'ussd_codes' => $ussd_codes,
            'countries' => $countries,
            'networks' => $networks,
            'progress_indicators' => $progress_indicators,
            'networks_raw' => array_combine($networks_raw, $networks_raw),
            'renewal_due' => $renewal_due,
            'recent_payments' => $recent_payments,
            'highlight_colour' => $highlight_colour,
            'showdocuments' => $showdocuments,
            'support_fees' => $support_fees,
            'recurring_arr' => $recurring_arr,
            // 'client_sender_ids' => $client_sender_ids,
            // 'sender_id_statuses' => $sender_id_statuses,
            'country_network_arr' => $country_networks,
            'mnos_arr' => ['' => '-- Select Country first --']
        ];
        // dump($client_sender_ids);
        // foreach ($client_sender_ids as $value) {
        //   dd($value->network_info->name);
        // }
        // dd($data);
        // return view('client.show', $data);
        return view('client.show_accordion', $data);
    }

    public function showReadonly($id){
        //with('short_code_info')->
        $showclient = Models\Client::with('service_info', 'country_info', 'auth_user_info', 'short_code_info')->find($id);
        $service_type = Models\Service::pluck('name', 'id');
        $service_type_names = Models\Service::pluck('name', 'name');
        $show_services = json_decode($showclient->services, true); //Models\ClientCategory::where('client_id', $id)->get();

        //->where('highlight', 'NO')
        $show_notes = Models\ClientNote::with('created_by_info', 'client_info')->where('client_id', $id)->orderBy('id', 'DESC')->get()->take(20);
        $voice_codes = Models\ClientShortCode::where('client_id', $id)->where('code_type', 'voice')->get();
        $sms_codes = Models\ClientShortCode::where('client_id', $id)->where('code_type', 'sms')->get();
        $ussd_codes = Models\ClientShortCode::where('client_id', $id)->where('code_type', 'ussd')->get();
        $recent_payments = Models\ClientPayment::where('client_id', $id)->orderBy('id', 'DESC')->get();
        $countries = Models\Country::pluck('en_short_name','en_short_name');
        $networks = Models\NetworkOps::pluck('name', 'name');
        $all_shortcodes = Models\ClientShortCode::with('client_info', 'client_info', 'update_info')->where('client_id', $id)->orderBy('code_type', 'ASC')->get();
        $showdocuments = Models\ClientFile::where('client_id', $id)->get();

        if ($showclient->status == 'Live') {
            $status_bg = "info";
        }
        elseif ($showclient->status == 'Prospective') {
            $status_bg = "warning";
        }
        else{
            $status_bg = "danger";
        }

        $renewal_due = 'N/A';
        $highlight_colour = 'none';
        //review this later
        if ($showclient->contract_validity == null || $showclient->contract_validity == '') {
            $renewal_due = "N/A";
        }
        else{


            $current_date = date_create(date('Y-m-d'));

            $expiry_date = date_create($showclient->contract_validity);

            $diff = date_diff($current_date, $expiry_date);

            $polar = $diff->format("%R");

            $months = $diff->format("%m");

            $days = $diff->format("%a");
            if ($days < 31) {
                if ($polar == '-') {
                    $highlight_colour = 'warning';
                    $renewal_due = "Contract expired $days days(s) ago";
                }
                else{
                    $renewal_due = "In $days day(s)" ;
                }
            }
            else{

                if ($polar == '-') {
                    $highlight_colour = 'warning';
                    $renewal_due = "Contract expired $months month(s) ago";

                }
                else{
                    $renewal_due = "In $months months";
                }
            }
        }
        $data = [
            'page_title' => 'Client Profile',
            'showclient' => $showclient,
            'show_services' => $show_services,
            'service_type' => $service_type,
            'service_type_names' => $service_type_names,
            'show_notes' => $show_notes,
            'status_bg' => $status_bg,
            'voice_codes' => $voice_codes,
            'sms_codes' => $sms_codes,
            'ussd_codes' => $ussd_codes,
            'countries' => $countries,
            'networks' => $networks,
            'renewal_due' => $renewal_due,
            'recent_payments' => $recent_payments,
            'highlight_colour' => $highlight_colour,
            'all_shortcodes' => $all_shortcodes,
            'showdocuments' => $showdocuments
        ];
        return view('client.show-readonly', $data);
    }
    public function showservices($id){
        $show_services = Models\ClientCategory::where('client_id', $id)->get();
        $data = [
            'page_title' => 'Show Services',
            'show_services' => $show_services
        ];
        return view('client.services', $data);
    }
    public function editservice($id){
        $payment = Models\ClientCategory::find($id);
        $data = [
            'page_title' => 'Show Services',
            'service' => $service
        ];
        return view('client.service-edit', $data);
    }
    public function getPayment($id){
        $payment = Models\ClientPayment::find($id);
        if ($payment) {
            $services_arr = explode(',', $payment->services);

            return response()->json([ 'code' => 1, 'result' => $payment, 'services_arr' => $services_arr]);
        }
        else{
            return response()->json([ 'code' => 3, 'msg' => 'Request could not be handled at this time']);
        }
    }
    public function getShortCodeDetails($id){
        $shortcode = Models\ClientShortCode::with('client_info', 'update_info')->find($id);
        if ($shortcode) {
            $services_arr = Models\Service::pluck('name', 'id');
            return response()->json([ 'code' => 1, 'result' => $shortcode, 'services_arr' => $services_arr]);
        }
        else{
            return response()->json([ 'code' => 3, 'msg' => 'Request could not be handled at this time']);
        }
    }
    public function getShortCodes($type){
        //$auth_users = Models\SystemUser::pluck('name', 'id');
        //todo : separate the short codes into individual pages
        // dd(session('current_user.designation'));
        switch ($type) {
            case 'sms':
                $codes_data = Models\ClientShortCode::with('client_info','client_info', 'update_info')->where('code_type', 'sms')->orderBy('id', 'DESC')->get();
                break;
            case 'ussd':
                $codes_data = Models\ClientShortCode::with('client_info', 'client_info', 'update_info')->where('code_type', 'ussd')->orderBy('id', 'DESC')->get();
                break;
            case 'voice':
                $codes_data = Models\ClientShortCode::with('client_info', 'client_info', 'update_info')->where('code_type', 'voice')->orderBy('id', 'DESC')->get();
                break;
            default:
                // code... show 404
                break;
        }
        // $codes = Models\ClientShortCode::with('update_info')->get();

        $data = [
            'page_title' => 'Client Short Codes',
            'codes_data' => $codes_data,
            'type' => $type
        ];
        // dd($data);
        return view('client.shortcodes', $data);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id){
        $client = Models\Client::find($id);
        $service_type = Models\Service::orderBy('name', 'ASC')->pluck('name', 'name');
        $countries = Models\Country::orderBy('en_short_name', 'ASC')->pluck('en_short_name','en_short_name');

        $payment_type = ['Prepaid' => 'Prepaid', 'Postpaid' => 'Postpaid']; // Models\PaymentType::pluck('name', 'id')->toArray();
        // $status = ['Live' => 'Live', 'inactive' => 'Inactive', 'Prospective' => 'Prospective'];
        $status = ['Live' => 'Live', 'inactive' => 'Inactive', 'Prospective' => 'Prospective', 'Cancelled' => 'Cancelled'];
        $currency = Models\Currency::orderBy('name', 'ASC')->pluck('name', 'name');
        $existing_documents = Models\ClientFile::where('client_id', $id)->get();
        $files = [
          'contract' => 'NO',
          'non_disclosure' => 'NO',
          'technical_doc' => 'NO'
        ];
        foreach ($existing_documents as $value) {
          if ($value->name == 'Contract') {
            $files['contract'] = "YES";
          }
          else if($value->name == 'Non Disclosure'){
            $files['non_disclosure'] = "YES";
          }
          else if($value->name == 'Technical Document'){
            $files['technical_doc'] = "YES";
          }
          else{

          }
        }
        $company_types = ['Aggregator/Supplier' => 'Aggregator/Supplier', 'Enterprise' => 'Enterprise'];
        $auth_users = Models\SystemUser::orderBy('name', 'ASC')->pluck('name', 'id');
        $industries = Models\Industry::orderBy('name', 'ASC')->pluck('name', 'name');
        $message_types_arr = ['International' => 'International', 'Local' => 'Local'];
        $onboarding_sub_items = [];
        $onboarding_sub_items_progress = [];
        $has_pending = false;

        //This should not be false because onboarding_progress_stage is populated during client creation
        $onboarding_progress = json_decode($client->onboarding_progress_stage, 1);
        // dump($client->progress_indicator);
        // dd($onboarding_progress);
        $has_pending = in_array("PENDING", $onboarding_progress);
        if ($client->progress_indicator !== "COMPLETED") {
            $stage_details = Models\ClientOnboardingMainStage::where('stage', $client->progress_indicator)->first();
            // dump($stage_details);
            $onboarding_sub_items_progress = Models\ClientOnboardingProgress::where('stage_id', $stage_details->stage_id)->where('client_id', $id)->where('status', 'COMPLETED')->pluck('name', 'name');
            // dd($onboarding_sub_items_progress);
            $onboarding_sub_items = Models\ClientOnboardingSubItem::where('stage_id', $stage_details->stage_id)->pluck('name', 'name');
        }

        /*
        else{

            $stage_details = Models\ClientOnboardingMainStage::where('stage_id', 1)->first();
             //get sub items
            // dd($stage_details);
            $onboarding_sub_items_progress = Models\ClientOnboardingProgress::where('stage_id', $stage_details->stage_id)->where('client_id', $id)->get();
            $onboarding_sub_items = Models\ClientOnboardingSubItem::where('stage_id', $stage_details->stage_id)->pluck('name', 'id');
        }
        */
        $how_we_got_clients_arr = ['Event : (GCCM) etc' => 'Event : (GCCM) etc', 'Referral' => 'Referral', 'Word of Mouth' => 'Word of Mouth', 'Marketing' => 'Marketing', 'Other' => 'Other'];
        // 'current_services' => json_decode($client->services, true);
        if ($client->support_emails) {
            $support_emails = json_decode($client->support_emails, true);
            $support_emails = array_combine($support_emails, $support_emails);
            $old_support_emails = json_decode($client->support_emails, true);
        }
        else{
            $support_emails = [];
            $old_support_emails = [];
        }
        if ($client->rate_emails) {
            $rate_emails = json_decode($client->rate_emails, true);
            $rate_emails = array_combine($rate_emails, $rate_emails);
            $old_rate_emails = json_decode($client->rate_emails, true);

        }
        else{
            $rate_emails = [];
            $old_rate_emails = [];
        }

        if ($client->support_phones) {
            $support_phones = json_decode($client->support_phones, true);
            $support_phones = array_combine($support_phones, $support_phones);
            $old_support_phones = json_decode($client->support_phones, true);
        }
        else{
            $support_phones = [];
            $old_support_phones = [];
        }

        if ($client->support_skype) {
            $support_skype_arr = json_decode($client->support_skype, true);
            $support_skype_arr = array_combine($support_skype_arr, $support_skype_arr);
            $old_support_skype_arr = json_decode($client->support_skype, true);
        }
        else{
            $support_skype_arr = [];
            $old_support_skype_arr = [];
        }
        if ($client->finance_email) {
            $finance_emails = json_decode($client->finance_email, true);
            $finance_emails = array_combine($finance_emails, $finance_emails);
            $old_finance_emails = json_decode($client->finance_email, true);
        }
        else{
            $finance_emails = [];
            $old_finance_emails = [];
        }

        if ($client->sender_ids) {
            $sender_ids = json_decode($client->sender_ids, true);
            $sender_ids = array_combine($sender_ids, $sender_ids);
            $old_sender_ids = json_decode($client->sender_ids, true);
        }
        else{
            $sender_ids = ['click' => 'click'];
            $old_sender_ids = [];
        }


        if ($client->status == 'Live') {
            $status_bg = "info";
        }
        elseif ($client->status == 'Prospective') {
            $status_bg = "warning";
        }
        else{
            $status_bg = "danger";
        }

        $contract_types = ['Bilateral' => 'Bilateral', 'Unilateral' => 'Unilateral'];
        $connections = ['SMPP' => 'SMPP', 'HTTP' => 'HTTP'];

        $data = [
            'client' => $client,
            'countries' => $countries,
            'service_type' => $service_type->toArray(),
            'payment_type' => $payment_type,
            'status' => $status,
            'auth_users' => $auth_users,
            'currency' => $currency,
            'page_title' => 'Update Client Details',
            'connections_arr' => $connections,
            'status_bg' => $status_bg,
            'sender_ids' => $sender_ids,

            'finance_emails' => $finance_emails,
            'support_emails' => $support_emails,
            'rate_emails' => $rate_emails,
            'support_skype_arr' => $support_skype_arr,
            'support_phones' => $support_phones,

            'old_finance_emails' => $old_finance_emails,
            'old_rate_emails' => $old_rate_emails,
            'old_support_emails' => $old_support_emails,
            'old_support_skype_arr' => $old_support_skype_arr,
            'old_support_phones' => $old_support_phones,

            'company_types' => $company_types,
            'old_sender_ids' => $old_sender_ids,
            'contract_types' => $contract_types,
            'message_types_arr' => $message_types_arr,
            'industries' => $industries,
            'how_we_got_clients_arr' => $how_we_got_clients_arr,
            'current_services' => json_decode($client->services, true),

            'onboarding_sub_items_progress' => $onboarding_sub_items_progress,
            'onboarding_sub_items' => $onboarding_sub_items,
            'current_pending_stage' => $client->progress_indicator,
            'has_pending' => $has_pending,
            'files' => $files
        ];
        // dd($data['onboarding_sub_items_progress']);
        return view('client.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Requests\UpdateClientRequest $request, $id){
        // dd($request->all());
        // \DB::connection()->enableQueryLog();
        $client_update = Models\Client::find($id);
        $paperless = new PaperLessNgx();
        if ($client_update->progress_indicator != 'COMPLETED') {
            $current_pending_stage_details = Models\ClientOnboardingMainStage::where('stage', $request->current_pending_stage)->first();
            $get_stage_subs_items = Models\ClientOnboardingSubItem::where('stage_id', $current_pending_stage_details->stage_id)->get();
            #update the table for onboarding progress
            foreach ($request->onboarding_sub_items_progress as $value) {
                $stage_id = [
                    'stage_id' => $current_pending_stage_details->stage_id, 
                    'client_id' => $id, 
                    'name' => $value 
                ];
                $progress_arr = [
                    'status' => 'COMPLETED'
                ];
                $clients_onboarding_progress = Models\ClientOnboardingProgress::updateOrCreate($stage_id, $progress_arr);
            }

            //update the status of onboarding progress stage in clients
            $get_stage_onboarding_status = Models\ClientOnboardingProgress::where('client_id', $id)->where('stage_id', $current_pending_stage_details->stage_id)->where('status', 'COMPLETED')->get();
            $onboarding_progress_stage = json_decode($client_update->onboarding_progress_stage, true);
            if (count($get_stage_subs_items) == count($get_stage_onboarding_status)) {
                //check if all items have been completed and update
                $onboarding_progress_stage[$current_pending_stage_details->stage] = 'COMPLETED';
            }
            $pending_stage = Arr::where($onboarding_progress_stage, function ($value, $key) {
                return $value == "PENDING";
            });

            #$pending_stage = array_key_first($pending_stage);
            reset($pending_stage);
            $pending_stage = key($pending_stage);
            if ($pending_stage == true) {
                //Pending Exist
                $client_update->progress_indicator = $pending_stage;
            }
            else{
                //No pending detected so render the process completed
                $client_update->progress_indicator = 'COMPLETED';
                //send email here
                $client = Models\Client::with('auth_user_info')->find($id);
                dispatch(new SendOnboardingCompletedEmailAlert($client));
            }
        }
        $existing_documents = Models\ClientFile::where('client_id', $id)->get();
        if ($request->has('document_one') && $request->has('document_one_name')) {
            if ($request->file('document_one')->isValid()) {
                $filename = "erp_" . time() . str_random(4) . "." . $request->document_one->extension();
                $request->document_one->storeAs('client_files', $filename, 'public');
                $document_arr['file_path'] = $filename;
                $client_update->name = $request->name;

                $store_location = "client_files";
                #$top = $paperless->processPaperlessFile($request->document_one_name, $request->document_one_name, $filename, $store_location);

                $document_arr['file_extension'] = $request->document_one->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_one_name;
                $document_arr['created_by'] = session('current_user.id');
                //$document_arr['client_id'] = $id;
                //$document_arr, 
                // $result = Models\ClientNote::updateOrCreate(['services' =>  $request->services, 'client_id' => $request->client_id, 'auth_user_id' => $auth_user['id'] ], $notes_arr);
                $result = Models\ClientFile::updateOrCreate(['client_id' => $id, 'name' => $request->document_one_name], $document_arr);
            }
        }
        if ($request->has('document_two') && $request->has('document_two_name')) {
            if ($request->file('document_two')->isValid()) {
               $filename = "erp_" . time() . str_random(4) . "." . $request->document_two->extension();
                $request->document_two->storeAs('client_files', $filename, 'public');
                $document_arr['file_path'] = $filename;
                $client_update->name = $request->name;
                $store_location = "client_files";
                #$top = $paperless->processPaperlessFile($request->document_two_name, $request->document_two_name, $filename, $store_location);


                $document_arr['file_extension'] = $request->document_two->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_two_name;
                $document_arr['created_by'] = session('current_user.id');
                $document_arr['client_id'] = $id;
                // $result = Models\ClientFile::create($document_arr);
                //$document_arr['client_id'] = $id;
                $result = Models\ClientFile::updateOrCreate(['client_id' => $id,  'name' => $request->document_two_name], $document_arr);
            }
        }
        if ($request->has('document_three') && $request->has('document_three_name')) {
            if ($request->file('document_three')->isValid()) {
               $filename = "erp_" . time() . str_random(4) . "." . $request->document_three->extension();
                $request->document_three->storeAs('client_files', $filename, 'public');
                $document_arr['file_path'] = $filename;
                $client_update->name = $request->name;

                $store_location = "client_files";
                #$top = $paperless->processPaperlessFile($request->document_three_name, $request->document_three_name, $filename, $store_location);

                $document_arr['file_extension'] = $request->document_three->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = $request->document_three_name;
                $document_arr['created_by'] = session('current_user.id');
                $document_arr['client_id'] = $id;
                // $result = Models\ClientFile::create($document_arr);
                //$document_arr['client_id'] = $id;
                $result = Models\ClientFile::updateOrCreate(['client_id' => $id,  'name' => $request->document_three_name], $document_arr);
            }
        }
        if ($request->has('other_document') && $request->has('other_document_name')) {
            if ($request->file('other_document')->isValid()) {
               $filename = "erp_" . time() . str_random(4) . "." . $request->other_document->extension();
                $request->other_document->storeAs('client_files', $filename, 'public');
                $document_arr['file_path'] = $filename;
                $client_update->name = $request->name;

                $store_location = "client_files";
                #$top = $paperless->processPaperlessFile($request->other_document_name, $request->other_document_name, $filename, $store_location);

                $document_arr['file_extension'] = $request->other_document->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = ($request->other_document_name == null) ? 'Other Document' : $request->other_document_name;
                $document_arr['created_by'] = session('current_user.id');
                $document_arr['client_id'] = $id;
                // dd($document_arr);
                $result = Models\ClientFile::updateOrCreate(['client_id' => $id, 'name' => $request->other_document_name], $document_arr);
            }
        }

        $client_update->name = $request->name;
        $client_update->email = $request->email;
        $client_update->phone = $request->phone ?? "";
        $client_update->contact_person = $request->contact_person;
        $client_update->status = $request->status;
        $client_update->pay_mode = $request->payment_mode;
        $client_update->country = $request->country;
        $client_update->currency = $request->currency;
        $client_update->notes = $request->notes;
        $client_update->industry = $request->industry;
        #$client_update->progress_indicators = json_encode($request->onboarding_sub_items_progress);
        if ($client_update->progress_indicator != 'COMPLETED') {
            $client_update->onboarding_progress_stage = json_encode($onboarding_progress_stage);
            // dump(json_encode($onboarding_progress_stage));
            $progress_breakdown = array_count_values($onboarding_progress_stage);
            // dd($progress_breakdown);
            if (array_has($progress_breakdown, ['COMPLETED']) == false) {
                // dd('foo');
                $indicator_score = "0";
            }
            else{
                $indicator_score = ($progress_breakdown['COMPLETED']/count($onboarding_progress_stage)) * 100;
            }
            $indicator_score = number_format($indicator_score);
            $client_update->progress_indicator_score = $indicator_score;
        }
        else{
            //review this manual process :)
            $client_update->progress_indicator_score = 100;
        }
        $client_update->skype_name = $request->skype_name ?? "";
        $client_update->linkedin_name = $request->linkedin_name ?? "";
        $client_update->smpp_username = $request->smpp_username ?? "";

        $client_update->company_type = $request->company_type ?? "";
        $client_update->auth_user_id = $request->auth_user_id ?? "";
        $client_update->contract_type = $request->contract_type ?? "";
        $client_update->contract_validity = $request->contract_validity ?? "";
        $client_update->contract_auto_renew = $request->contract_auto_renew ?? "";
        //$client_update->smpp_details = $request->smpp_details ?? "";
        $client_update->sender_ids = ($request->sender_ids) ? json_encode($request->sender_ids) : "";
        $client_update->connections = ($request->connections) ? json_encode($request->connections) : "";
        $client_update->services = ($request->services) ? json_encode($request->services) : "";
        $client_update->message_types = ($request->message_types) ? json_encode($request->message_types) : "";

        $client_update->finance_email = ($request->finance_email) ? json_encode($request->finance_email) : "";
        $client_update->support_emails = ($request->support_emails) ? json_encode($request->support_emails) : "";
        $client_update->rate_emails = ($request->rate_emails) ? json_encode($request->rate_emails) : "";
        $client_update->support_phones = ($request->support_phones) ? json_encode($request->support_phones) : "";
        $client_update->support_skype = ($request->support_skype) ? json_encode($request->support_skype) : "";

        if ($request->has('how_we_got_client')) {
            if ($request->how_we_got_client == 'Other') {
                $client_update->how_we_got_client = $request->how_we_got_client_other ?? "";
            }
            else{
                $client_update->how_we_got_client = $request->how_we_got_client ?? "";
            }
        }


        $client_update->created_by = session('current_user.id');
        $client_update->last_modified_by = session('current_user.id');

        $result = $client_update->save();

        $activity_arr = [
            'type' => 'staff',
            'content' => session('current_user.name') . " updated ($client_update->name) details successfully!",
            'user_id' => session('current_user.id'),
            'ip_address' => \Request::ip(),
            'device' => $request->header('User-Agent')
        ];
        $retval = Models\UserActivity::create($activity_arr);
        // $queries = \DB::getQueryLog();
        // dd($queries);
        // \Log::info($queries);

        Session::flash('success_message', 'Client successfully Updated');
        return redirect(url('clients', $id));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = Models\Client::destroy($id);
        if (request()->ajax()) {
            $result_arr = ['code' => 1];
            return response()->json($result_arr);
        }
        Session::flash('success_message', 'Client successfully deleted!');
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") Deleted a client with ID $id";
        $this->logUsersActivity($type = 'staff', $content);
        return redirect(route('client.index'));
    }

    public function store_services($services_arr, $client_id){
        foreach ($services_arr as $id) {
            $client_arr = [
                'client_id' => $client_id,
                'category_id' => $id
            ];
            $result = Models\ClientCategory::create($client_arr);
        }
        return true;
    }
    public function update_services($services_arr, $client_id){
        // remove and add  will think of a better approach later
        $result = Models\ClientCategory::where('client_id', $client_id)->delete();

        foreach ($services_arr as $id) {
            $client_arr = [
                'client_id' => $client_id,
                'category_id' => $id
            ];
            $result = Models\ClientCategory::create($client_arr);
        }
        return true;
    }
    public function storeFiles(AddFilesRequest $request){
        $document_arr = $request->except('document');
        if ($request->hasFile('document')) {
           if ($request->file('document')->isValid()) {
                $filename = "erp_" . time() . "." . $request->document->extension();
                $request->document->storeAs('client_files', $filename, 'public');
                $document_arr['document'] = json_encode([$filename]);
            }
        }
        $client = Models\Client::find($request->client_id);
        $document_arr['file_extension'] = $request->document->extension();
        $document_arr['file_reff'] = time() . uniqid();
        $document_arr['last_modified_by'] = session('current_user.id');

        $result = Models\ClientFile::create($document_arr);

        if ($result) {
            $data = ['code' => 1, 'msg' => 'Document successfully uploaded'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        $user_id = session('current_user.id');
        $username = session('current_user.name');
        $content  = "User ID : " . $user_id . " (" . $username . ") Document successfully uploaded for " . $client->name;
        $this->logUsersActivity($type = 'staff', $content);
        return response()->json($data, 200);

    }
    public function getClientFile($id){
        $client_file = Models\ClientFile::with('client_info')->findOrFail($id);
        // dd($client_file);
        //PDF file is stored under project/public/download/info.pdf
        $file = public_path('documents/client_files/') .  $client_file->file_path;

        $headers = [];  //['Content-Type: application/pdf'];
        $filename = $client_file->client_info->name . "_" . $client_file->name;
        $filename = $this->cleanStr($filename);
        $filename = $filename  . "." . $client_file->file_extension;

        // $filename = str_replace(' ', '_', $filename);
        return \Response::download($file, $filename, $headers);
    }
    public function showOnboardingForm($client_id){
        $client = Models\Client::findOrFail($client_id);

        $onboarding_stages = Models\ClientOnboardingProgress::where('client_id', $client_id)->orderBy('stage_id')->get();
       //dd($onboarding_stages);
        $data = [
            'page_title' => 'Clients | Onboarding Checklist',
            'client' => $client,
            'onboarding_stages' => $onboarding_stages
        ];
        return view('client.onboarding_show', $data);
    }
    public function cleanStr($string){
        // Replaces all spaces with hyphens.
        $string = str_replace(' ', '-', $string);

        // Removes special chars.
        $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
        // Replaces multiple hyphens with single one.
        $string = preg_replace('/-+/', '_', $string);

        return $string;
    }

    public function getMNO($id){
        $mno = Models\NetworkOps::find($id);

        return $mno;

    }
    public function getMnoCountry($network){
      $networks_raw = [
          'AirtelTigo GH' => 'AirtelTigo GH',
          'MTN GH' => 'MTN GH',
          'Airtel MW' => 'Airtel MW',
          'Airtel Zambia' => 'Airtel Zambia',
          'TNM MW' => 'TNM MW',
          'Airtel MW' => 'Airtel MW',
          'Safaricom Kenya' => 'Safaricom Kenya',
          'Airtel Kenya' => 'Airtel Kenya',
          'Telkom Kenya' => 'Telkom Kenya',
          'Orange Kenya' => 'Orange Kenya'
      ];
      if (stripos($network, 'MW') !== false ) {
          $country = 'Malawi';
      }
      elseif (stripos($network, 'GH') !== false) {
          $country = 'Ghana';
      }
      elseif (stripos($network, 'Zambia') !== false) {
          $country = 'Zambia';
      }
      elseif (stripos($network, 'Bots') !== false) {
          $country = 'Botswana';
      }
      elseif (stripos($network, 'KE') !== false) {
          $country = 'Kenya';
      }
      else{
          $country = false;
      }
      return $country;
    }
}
