<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;
use Illuminate\Support\Arr;
// use App\Http\Requests;
use App\Http\Requests;
use App\Jobs\NewMnoNotesEmailAlerts;
use App\Libs\PaperLessNgx;
// use Illuminate\Http\Request as Requests;



class NetworkOperatorsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function indexBAK(){
        $network_operators = new Models\NetworkOps;
        $table_columns = \DB::select(\DB::raw("show full columns from network_operators"));
        $exclude_arr = [
            'updated_at', 'id', 'account_manager_id', 'created_at'
        ];
        $columns = [];
        $queries = [];
        foreach ($table_columns as $key) {
          $columns[$key->Field] = $key->Field;
        }
        foreach ($columns as $col) {
            if (request('filter') == $col) {
                $filter = request('filter');
                $keyword = request('keyword');
                $table_arr = ['staff_id'];
                if (in_array($col, $table_arr)) {
                    $key = $this->get_filter_ids($filter, $keyword);
                    if (!empty($key)) {
                        $keyword = $key;
                    }
                }
                $network_operators = $network_operators->where($col, 'like', '%'.$keyword.'%');
                $queries[$col] = request('keyword');
            }
        }

        $network_operators = $network_operators->with('account_manager_info', 'country_info')->orderBy('created_at', 'DESC')->paginate(40)->appends($queries);
        $data = [
            'page_title' => 'Network Operators',
            'columns' => Arr::except($columns, $exclude_arr),
            'network_operators' => $network_operators
        ];

        return view('network_ops.index', $data);
    }
    public function index(){
        //$mno_arr = Models\NetworkOps::get();
        $data = [
            'page_title' => 'Mobile Network Operators',
            'current_user' => session('current_user')
        ];
        // dd($data);
        return view('network_ops.index', $data);
    }
    public function getMnosJson(Request $request){
        //$this->log_query();
        $mno_arr = \DB::table('network_operators')
            ->join('staff_members AS staffam', 'staffam.id', '=', 'network_operators.account_manager_id')
            ->join('staff_members AS staffmodify', 'staffmodify.id', '=', 'network_operators.last_modified_by')
            ->select('network_operators.id', 'staffam.name AS accountManager', 'network_operators.name AS networkName', 'network_operators.country','network_operators.contract_validity', 'network_operators.connection_status',  'staffmodify.name AS modifiedBy')
            ->orderBy('network_operators.name', 'ASC')
            ->paginate(15);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $mno_arr = \DB::table('network_operators')
            ->join('staff_members AS staffam', 'staffam.id', '=', 'network_operators.account_manager_id')
            ->join('staff_members AS staffmodify', 'staffmodify.id', '=', 'network_operators.last_modified_by')
            ->select('network_operators.id', 'staffam.name AS accountManager', 'network_operators.name AS networkName', 'network_operators.country','network_operators.contract_validity', 'network_operators.connection_status',  'staffmodify.name AS modifiedBy')
            ->whereRaw("network_operators.name LIKE '%$keyword%' OR network_operators.connection_status LIKE '%$keyword%' OR network_operators.country LIKE '%$keyword%' OR staffam.name LIKE '%$keyword%' ")
            ->orderBy('network_operators.name', 'ASC')
            ->paginate(15);
        }
        return response()->json($mno_arr);
    }
    public function getCountryNetworks(Request $request){
        $mno_arr = Models\NetworkOps::where('country', $request->country)->pluck('name', 'id');
        // dd(count($mno_arr));
        if (count($mno_arr) == 0) {
            $data = ['code' => '2', 'msg' => 'No MNOs found in the selected country'];
        }
        else{
            $data = ['code' => '1', 'mnos' => $mno_arr,];
        }
        return response()->json($data);
    }

    /**
     * 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');
        $account_manager = Models\SystemUser::pluck('name', 'id');
        $services = Models\Service::pluck('name', 'name');
        $status = ['Active' => 'Active', 'Inactive' => 'Inactive', 'Pending' => 'Pending'];
        $direct_arr = ['Direct' => 'Direct', 'Non Direct' => 'Non Direct'];
        // dd('foo bar');
        $data = [
            'page_title' => 'Create Network Operator',
            'countries'=> $countries,
            'account_manager' => $account_manager,
            'services' => $services,
            'status' => $status,
            'direct_arr' => $direct_arr
        ];
        return view('network_ops.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',
            'direct_status' => 'required',
            'country' => 'required',
            'account_manager_id' => 'required_if:direct_status,Direct',
            'services' => 'required_if:direct_status,Direct',
            'contact_person' => 'required_if:direct_status,Direct',
            'email' => 'required_if:direct_status,Direct',
            'phone' => 'required_if:direct_status,Direct',
            'status' => 'required'
        ]);

        $operator_arr = [
          'name' => $request->name,
          'country' => $request->country,
          'account_manager_id' => $request->account_manager_id,
          'contact_person' => $request->contact_person,
          'connection_status' => $request->status,
          'contact_person_phone' => $request->phone,
          'contact_person_email' => $request->email,
          'last_modified_by' => session('current_user.id')
        ];
        if ($request->has('services')) {
            $operator_arr['services'] = json_encode($request->services);
        }
        if ($request->account_manager_id == false) {
            $operator_arr['account_manager_id'] = session('current_user.id');
        }
        if ($request->has('phone')) {
            $operator_arr['phone'] = $request->phone;
        }
        if ($request->has('skype_name')) {
            $operator_arr['contact_person_skype'] = $request->skype_name;
        }
        if ($request->has('linkedin_name')) {
            $operator_arr['linkedin_name'] = $request->linkedin_name;
        }
        if ($request->has('contact_person')) {
            $operator_arr['contact_person'] = $request->contact_person;
        }
        // dd($operator_arr);
        $saved = Models\NetworkOps::create($operator_arr);
        Session::flash('success_message', 'Network Operator successfully added');
        return redirect(url('mnos'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id){
        //$operator_arr = Models\NetworkOps::findOrFail($id);
        $network_arr = Models\NetworkOps::with('account_manager_info')->findOrFail($id);
        // dd($network_arr);
        $countries = Models\Country::orderBy('en_short_name')->pluck('en_short_name','en_short_name');
        $account_manager = Models\SystemUser::orderBy('name')->pluck('name', 'id');
        $services = Models\Service::orderBy('name')->pluck('name', 'name');
        $connection_types = ['VPN' => 'VPN', 'DIRECT' => 'DIRECT'];
        $ip_addresses = Models\Mnoips::where('mno_id', $id)->get();
        $show_notes =  Models\Mnonote::where('mno_id', $id)->get();
        $showdocuments = Models\MnoFile::where('mno_id', $id)->get();
        $recent_payments = Models\Mnopayment::where('mno_id', $id)->orderBy('id', 'DESC')->get();

        if ($network_arr->support_emails) {
            $support_emails = json_decode($network_arr->support_emails, true);
            $support_emails = array_combine($support_emails, $support_emails);
            $old_support_emails = json_decode($network_arr->support_emails, true);
        }
        else{
            $support_emails = [];
            $old_support_emails = [];
        }
        if ($network_arr->finance_emails) {
            $finance_emails = json_decode($network_arr->finance_emails, true);
            $finance_emails = array_combine($finance_emails, $finance_emails);
            $old_finance_emails = json_decode($network_arr->finance_emails, true);
        }
        else{
            $finance_emails = [];
            $old_finance_emails = [];
        }
        if ($network_arr->support_phones) {
            $support_phones = json_decode($network_arr->support_phones, true);
            $support_phones = array_combine($support_phones, $support_phones);
            $old_support_phones = json_decode($network_arr->support_phones, true);
        }
        else{
            $support_phones = [];
            $old_support_phones = [];
        }

        if ($network_arr->support_skype) {
            $support_skype_arr = json_decode($network_arr->support_skype, true);
            $support_skype_arr = array_combine($support_skype_arr, $support_skype_arr);
            $old_support_skype_arr = json_decode($network_arr->support_skype, true);
        }
        else{
            $support_skype_arr = [];
            $old_support_skype_arr = [];
        }
        $old_connection_type = [];
        if ($network_arr->connection_type) {
            $connection_type = json_decode($network_arr->connection_type, true);
            $connection_type = array_combine($connection_type, $connection_type);
            $old_connection_type = json_decode($network_arr->connection_type, true);
        }
        else{
            $old_connection_type = [];
        }

        if ($network_arr->connection_status == 'Active') {
            $status_bg = "info";
        }
        elseif ($network_arr->connection_status == 'Pending') {
            $status_bg = "warning";
        }
        else{
            $status_bg = "danger";
        }
        $data = [
            'page_title' => 'Network Operator Details',
            'showdocuments' => $showdocuments,
            'mnoshow' => $network_arr,
            'countries'=> $countries,
            'account_manager' => $account_manager,
            'current_services' => json_decode($network_arr->services, true),
            'services' => $services->toArray(),
            'support_emails' => $support_emails,
            'finance_emails' => $finance_emails,
            'support_skype_arr' => $support_skype_arr,
            'support_phones' => $support_phones,
            'old_support_emails' => $old_support_emails,
            'old_finance_emails' => $old_finance_emails,
            'old_support_skype_arr' => $old_support_skype_arr,
            'old_support_phones' => $old_support_phones,
            'status_bg' => $status_bg,
            'connection_types' => $connection_types,
            'old_connection_type' => $old_connection_type,
            'ip_addresses' => $ip_addresses,
            'recent_payments' => [],
            'show_notes' => $show_notes,
            'recent_payments' => $recent_payments
        ];
        // dd($data);

        return view('network_ops.show', $data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id){
        $network_arr = Models\NetworkOps::findOrFail($id);
        $countries = Models\Country::orderBy('en_short_name')->pluck('en_short_name','en_short_name');
        $account_manager = Models\SystemUser::orderBy('name')->pluck('name', 'id');
        $services = Models\Service::orderBy('name')->pluck('name', 'name');
        $connection_types = ['VPN' => 'VPN', 'DIRECT' => 'DIRECT'];
        $ip_addresses = Models\Mnoips::where('mno_id', $id)->get();
        $notes_arr = Models\Mnonote::where('mno_id', $id)->get();
        $recent_payments = Models\Mnopayment::where('mno_id', $id)->orderBy('id', 'DESC')->get();
        $service_type_names = Models\Service::pluck('name', 'name');
        //dd($notes_arr); //with('mno_info')->
        if ($network_arr->support_emails) {
            $support_emails = json_decode($network_arr->support_emails, true);
            $support_emails = array_combine($support_emails, $support_emails);
            $old_support_emails = json_decode($network_arr->support_emails, true);
        }
        else{
            $support_emails = [];
            $old_support_emails = [];
        }
        if ($network_arr->finance_emails) {
            $finance_emails = json_decode($network_arr->finance_emails, true);
            $finance_emails = array_combine($finance_emails, $finance_emails);
            $old_finance_emails = json_decode($network_arr->finance_emails, true);
        }
        else{
            $finance_emails = [];
            $old_finance_emails = [];
        }
        if ($network_arr->support_phones) {
            $support_phones = json_decode($network_arr->support_phones, true);
            $support_phones = array_combine($support_phones, $support_phones);
            $old_support_phones = json_decode($network_arr->support_phones, true);
        }
        else{
            $support_phones = [];
            $old_support_phones = [];
        }

        if ($network_arr->support_skype) {
            $support_skype_arr = json_decode($network_arr->support_skype, true);
            $support_skype_arr = array_combine($support_skype_arr, $support_skype_arr);
            $old_support_skype_arr = json_decode($network_arr->support_skype, true);
        }
        else{
            $support_skype_arr = [];
            $old_support_skype_arr = [];
        }
        $old_connection_type = [];
        if ($network_arr->connection_type) {
            $connection_type = json_decode($network_arr->connection_type, true);
            $connection_type = array_combine($connection_type, $connection_type);
            $old_connection_type = json_decode($network_arr->connection_type, true);
        }
        else{
            $old_connection_type = [];
        }

        if ($network_arr->connection_status == 'Active') {
            $status_bg = "info";
        }
        elseif ($network_arr->connection_status == 'Pending') {
            $status_bg = "warning";
        }
        else{
            $status_bg = "danger";
        }
        $rate_types = ['flat_rate' => 'Flat Rate', 'sliding' => 'Sliding Scale'];
        $data = [
            'page_title' => 'Edit Network Operator',
            'network_arr' => $network_arr,
            'countries'=> $countries,
            'account_manager' => $account_manager,
            'current_services' => json_decode($network_arr->services, true),
            'services' => $services->toArray(),
            'support_emails' => $support_emails,
            'finance_emails' => $finance_emails,
            'support_skype_arr' => $support_skype_arr,
            'support_phones' => $support_phones,
            'old_support_emails' => $old_support_emails,
            'old_finance_emails' => $old_finance_emails,
            'old_support_skype_arr' => $old_support_skype_arr,
            'old_support_phones' => $old_support_phones,
            'status_bg' => $status_bg,
            'connection_types' => $connection_types,
            'old_connection_type' => $old_connection_type,
            'rate_types' => $rate_types,
            'ip_addresses' => $ip_addresses,
            'notes_arr' => $notes_arr,
            'recent_payments' => $recent_payments,
            'service_type_names' => $service_type_names
        ];
        return view('network_ops.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Requests\UpdateMnoRequest $request, $id)
    {   
        if ($request->has('document_one') && isset($request->document_one_name) == false) {
          return redirect()->back()->withErrors(array("You need to add a name for the document to be uploaded !"))->withInput();
        }
        if ($request->has('document_two') && isset($request->document_two_name) == false) {
          return redirect()->back()->withErrors(array("You need to add a name for the document to be uploaded !"))->withInput();
        }
        $operator_update = Models\NetworkOps::find($id);
        $paperless = new PaperLessNgx();
        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('mno_files', $filename, 'public');
                $document_arr['file_path'] = $filename;
                $operator_update->name = $request->name;

                $store_location = "mno_files";
                #$top = $paperless->processPaperlessFile($request->document_one_name, $request->document_one_category, $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['mno_id'] = $id;
                $result = Models\MnoFile::create($document_arr);
            }
        }
        if ($request->has('document_two') && $request->has('document_two_name')) {
            if ($request->file('document_two')->isValid()) {
               $filename = "erp_" . time() . str_random(6) . "." . $request->document_two->extension();
                $request->document_two->storeAs('mno_files', $filename, 'public');
                $document_arr['file_path'] = $filename;
                $operator_update->name = $request->name;

                $store_location = "mno_files";
                #$top = $paperless->processPaperlessFile($request->document_two_name, $request->document_two_category, $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['mno_id'] = $id;
                $result = Models\MnoFile::create($document_arr);
            }
        }
        if ($request->has('sliding_rate_file') && $request->has('sliding_rate_file')) {
            if ($request->file('sliding_rate_file')->isValid()) {
                $filename = "erp_" . time() . "_sliding_rate." . $request->sliding_rate_file->extension();
                $request->sliding_rate_file->storeAs('mno_files', $filename, 'public');
                $document_arr['file_path'] = $filename;
                // $operator_update->name = $request->name;

                $store_location = "mno_files";
                #$top = $paperless->processPaperlessFile("sliding_rate", 'rates', $filename, $store_location);


                $document_arr['file_extension'] = $request->sliding_rate_file->extension();
                $document_arr['file_reff'] = time() . uniqid();
                $document_arr['name'] = "Sliding Scale Rate File";
                $document_arr['created_by'] = session('current_user.id');
                $document_arr['mno_id'] = $id;
                $result = Models\MnoFile::create($document_arr);
                $operator_update->sliding_rate_file = $filename;
            }
        }
        if ($request->rate_type == 'flat_rate') {
          $operator_update->buying_rate = $request->buying_rate;
        }

        $operator_update->name = $request->name;
        $operator_update->country = $request->country;
        $operator_update->account_manager_id = $request->account_manager_id;
        $operator_update->mno_account_manager = $request->mno_account_manager;


        $operator_update->contact_person_email = $request->contact_person_email;
        $operator_update->contact_person_phone = $request->contact_person_phone;
        $operator_update->contact_person = $request->contact_person;
        $operator_update->connection_status = $request->connection_status ?? "";

        $operator_update->technical_support_person = $request->technical_support_person ?? "";
        $operator_update->contact_person_finance = $request->contact_person_finance ?? "";


        $operator_update->contract_validity = $request->contract_validity ?? "";
        $operator_update->contract_auto_renew = $request->contract_auto_renew ?? "";

        $operator_update->connection_type = ($request->connection_type) ? json_encode($request->connection_type) : "";

        $operator_update->contact_person_skype = $request->contact_person_skype ?? "";

        #$operator_update->connections = ($request->connections) ? json_encode($request->connections) : "";
        $operator_update->services = ($request->services) ? json_encode($request->services) : "";
        $operator_update->support_emails = ($request->support_emails) ? json_encode($request->support_emails) : "";
        $operator_update->finance_emails = ($request->finance_emails) ? json_encode($request->finance_emails) : "";
        $operator_update->support_phones = ($request->support_phones) ? json_encode($request->support_phones) : "";
        $operator_update->support_skype = ($request->support_skype) ? json_encode($request->support_skype) : "";

        $operator_update->rate_type = $request->rate_type;
        $result = $operator_update->save();

        Session::flash('success_message', 'Network Operator successfully Updated');
        return redirect(url('mnos'));
    }
    public function ipStore(Request $request) {
        $request->validate([
            'mno_id' => 'required',
            'ip_address' => 'required|ipv4',
            'service' => 'required',
            'port' => 'sometimes|numeric',
            'status' => 'required'
        ]);
        $auth_user = session('current_user');

        $addresses_arr = [
          'ip_address' => $request->ip_address,
          'mno_id' => $request->mno_id,
          'service' => $request->service,
          'port' => $request->port,
          'status' => $request->status,
          'created_by' => $auth_user['id'],
          'last_modified_by' => $auth_user['id']
        ];


        $result = Models\Mnoips::create($addresses_arr);

        if ($result) {
            $data = ['code' => 1, 'msg' => 'IP Address successfully added'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        return response()->json($data, 200);
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function notesStore(Request $request)
    {
        $request->validate([
            'mno_id' => 'required',
            'notes_body' => 'required'
        ]);
        $auth_user = session('current_user');
        //'email' => 'unique:users,email_address'
        $notes_arr = [
          'notes_body' => $request->notes_body,
          'services' => implode(',', $request->services),
          'user_id' => $auth_user['id'],
          'mno_id' => $request->mno_id
        ];
        if ($request->has('highlight')) {
            $notes_arr['highlight'] = 'YES';
        }


        //dd($notes_arr);
        $result = Models\Mnonote::create($notes_arr);

        $notes = Models\Mnonote::with('mno_info', 'created_by_info')->find($result->id);

        //todo : send emails
        dispatch(new NewMnoNotesEmailAlerts($notes));

        if ($result) {
            $data = ['code' => 1, 'msg' => 'Notes successfully added'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        return response()->json($data, 200);
    }
    public function getSingleNote($id)
    {
        $note = Models\Mnonote::find($id);
        if ($note) {

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

            $expiry_date = date_create($note->created_at);

            $diff = date_diff($current_date, $expiry_date);
            $days = $diff->format("%a");
            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 getSinglePayment($id)
    {
        $payment = Models\MnoPayment::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 financeStore(Request $request)
    {
        $request->validate([
            'mno_id' => 'required',
            'services' => 'required',
            'invoice_number' => 'required',
            'invoice_amount' => 'required|numeric',
            'invoice_date' => 'required',
            'invoice_status' => 'required'
        ]);
        $auth_user = session('current_user');


        $finance_arr = [
          'invoice_number' => $request->invoice_number,
          'invoice_amount' => $request->invoice_amount,
          'invoice_date' => $request->invoice_date,
          'invoice_status' => $request->invoice_status,
          'services' => implode(',', $request->services),
          'user_id' => $auth_user['id'],
          'mno_id' => $request->mno_id
        ];
        if ($request->has('remarks')) {
            $finance_arr['remarks'] = $request->remarks;
        }

        $result = Models\Mnopayment::create($finance_arr);
        if ($result) {
            $data = ['code' => 1, 'msg' => 'Payment Details successfully added'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        return response()->json($data, 200);
    }
    public function financeUpdate(Request $request)
    {
        $request->validate([
            'payment_id' => 'required',
            'mno_id' => 'required',
            'services' => 'required',
            'invoice_number' => 'required',
            'invoice_amount' => 'required|numeric',
            'invoice_date' => 'required',
            'invoice_status' => 'required'
        ]);
        $auth_user = session('current_user');
        $payment = Models\Mnopayment::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->services = implode(',', $request->services);
        $result = $payment->save();

        if ($result) {
            $data = ['code' => 1, 'msg' => 'Payment Details successfully updated'];
        }
        else{
            $data = ['code' => 3, 'msg' => 'Your request could not be handled at this time'];
        }
        return response()->json($data, 200);
    }
    public function notesUpdate(Request $request)
    {
        $request->validate([
            'mno_id' => 'required',
            'notes_body' => 'required'
        ]);
        $auth_user = session('current_user');
        $notes_arr = [
          'notes_body' => $request->notes_body,
          'services' => implode(',', $request->services),
          'user_id' => $auth_user['id'],
          'mno_id' => $request->mno_id
        ];
        if ($request->has('highlight')) {
            $notes_arr['highlight'] = 'YES';
        }


        //dd($notes_arr);
        $result = Models\Mnonote::create($notes_arr);

        $notes = Models\Mnonote::with('mno_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'];
        }
        return response()->json($data, 200);
    }
    public function getMnoFile($id)
    {
        $mno_file = Models\MnoFile::with('mno_info')->findOrFail($id);


        $file = public_path('documents/mno_files/') .  $mno_file->file_path;
        $headers = [];  //['Content-Type: application/pdf'];
        $filename = $mno_file->name . "_" . $mno_file->name;
        $filename = $this->cleanStr($filename);
        $filename = $filename  . "." . $mno_file->file_extension;
        return \Response::download($file, $filename, $headers);
    }
    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 destroy($id)
    {
        $result = Models\NetworkOps::destroy($id);
        if (request()->ajax()) {
            $result_arr = ['code' => 1];
            return response()->json($result_arr);
        }
        Session::flash('success_message', 'Network Operator successfully deleted!');
        return redirect(route('mnos.index'));
    }
}
