<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;
use Illuminate\Support\Arr;


class MeetingReportsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
      if (request()->has('filter', 'keyword')){ // == true && request()->keyword = ) {
        // dd('foo detected');
        $keyword = request()->keyword;
        $filter = request()->filter;
        if ($filter == 'Location') {
          $keyword = Models\Country::where('en_short_name', 'LIKE', $keyword)->get();
        }
        $clients = Models\Client::with('report_info')->where($filter, $keyword)
            ->orderBy('name', 'ASC')->paginate(1);
      }
      $clients = Models\Client::with('report_info')->orderBy('name', 'ASC')->paginate(1);
      
      $data = [
        'page_title' => 'Meeting Report',
        'columns' => ['Name' => 'Client Name',  'Location' => 'Client Location'],
        'clients' => $clients
      ];
      // dd($clients[0]);
      return view('report.dashboardreport', $data);
    }
    public function search()
    {
      dd(request()->has('filter', 'keyword'));
      dd(request()->all());

      $clients = Models\Client::with('report_info')->orderBy('name', 'ASC')->paginate(1);
      
      $data = [
        'page_title' => 'Meeting Report',
        'columns' => ['Name' => 'Client Name',  'Location' => 'Client Location'],
        'clients' => $clients
      ];
      // dd($clients[0]);
      return view('report.dashboardreport', $data);
    }
    public function indexBKTwo()
    {
      $clients = Models\Client::with('report_info')->get();
      dd($clients);
      $meeting_report_arr = new Models\MeetingReport;
      $table_columns = \DB::select(\DB::raw("show full columns from meeting_reports"));
      $exclude_arr = [
          'updated_at', 'id','created_at'
      ];
      $columns = [];
      $queries = [];
      foreach ($table_columns as $key) {
        if ($key->Field == 'auth_user_id') {
          $columns[$key->Field] = 'Account Manager';
        }
        else{
          $columns[$key->Field] = ucwords(str_replace('_', ' ', $key->Field));  
        }
      }
      foreach ($columns as $col) {
          if (request('filter') == $col) {
              $filter = request('filter');
              $keyword = request('keyword');
              $table_arr = ['staff_id', 'payment_type'];
              if (in_array($col, $table_arr)) {
                  $key = $this->get_filter_ids($filter, $keyword);
                  if (!empty($key)) {
                      $keyword = $key;
                  }
              }
              $meeting_report_arr = $meeting_report_arr->where($col, 'like', '%'.$keyword.'%');
              $queries[$col] = request('keyword');
          }
      }
      /*
      if (session('current_user.designation') == 'administrator') {
        $meeting_report_arr = $meeting_report_arr->with('client_info', 'auth_user_info', 'sam_comment_info')->orderBy('created_at', 'DESC')->paginate(40)->appends($queries);
      }
      else{
        $meeting_report_arr = $meeting_report_arr->with('client_info', 'auth_user_info', 'sam_comment_info')
          ->where('auth_user_id', session('current_user.id'))
          ->orderBy('created_at', 'DESC')->paginate(40)->appends($queries);
      }
      */
      $meeting_report_arr = $meeting_report_arr->with('client_info', 'auth_user_info', 'sam_comment_info')->orderBy('created_at', 'DESC')->paginate(40)->appends($queries);
      
      $payment_type = [ 1 => 'Prepaid', 2 => 'Postpaid'];
      $data = [
          'page_title' => 'Meeting Report',
          'columns' => Arr::except($columns, $exclude_arr),
          'meeting_report_arr' => $meeting_report_arr,
          'payment_type' => $payment_type
      ];
      return view('report.index', $data);
    }

    public function indexBK()
    {
        $meeting_report_arr = new Models\MeetingReport;
        $table_columns = \DB::select(\DB::raw("show full columns from meeting_reports"));
        $exclude_arr = [
            'updated_at', 'id','created_at'
        ];
        $columns = [];
        $queries = [];
        foreach ($table_columns as $key) {
          if ($key->Field == 'auth_user_id') {
            $columns[$key->Field] = 'Account Manager';
          }
          else{
            $columns[$key->Field] = ucwords(str_replace('_', ' ', $key->Field));  
          }
        }
        foreach ($columns as $col) {
            if (request('filter') == $col) {
                $filter = request('filter');
                $keyword = request('keyword');
                $table_arr = ['staff_id', 'payment_type'];
                if (in_array($col, $table_arr)) {
                    $key = $this->get_filter_ids($filter, $keyword);
                    if (!empty($key)) {
                        $keyword = $key;
                    }
                }
                $meeting_report_arr = $meeting_report_arr->where($col, 'like', '%'.$keyword.'%');
                $queries[$col] = request('keyword');
            }
        }
        if (session('current_user.designation') == 'administrator') {
          $meeting_report_arr = $meeting_report_arr->with('client_info', 'auth_user_info', 'sam_comment_info')->orderBy('created_at', 'DESC')->paginate(40)->appends($queries);
        }
        else{
          $meeting_report_arr = $meeting_report_arr->with('client_info', 'auth_user_info', 'sam_comment_info')
            ->where('auth_user_id', session('current_user.id'))
            ->orderBy('created_at', 'DESC')->paginate(40)->appends($queries);
        }
        
        $payment_type = [ 1 => 'Prepaid', 2 => 'Postpaid'];
        $data = [
            'page_title' => 'Meeting Report',
            'columns' => Arr::except($columns, $exclude_arr),
            'meeting_report_arr' => $meeting_report_arr,
            'payment_type' => $payment_type
        ];
        return view('report.index', $data);
    }
    public function showDetails($id = '')
    {
      // dump(session('current_user'));
        $selected_user = '';
        $meeting_report_arr = new Models\MeetingReport;
        $current_user = session('current_user.id');
        
        if (session('current_user.designation') == 'administrator') {
          $meeting_report_arr = $meeting_report_arr->with('client_info', 'auth_user_info', 'sam_comment_info')->orderBy('created_at', 'DESC')->paginate(20);
        }
        else{
          $meeting_report_arr = $meeting_report_arr->with('client_info', 'auth_user_info', 'sam_comment_info')->where('auth_user_id', $current_user)->orderBy('created_at', 'DESC')->paginate(20);
        }

        if ($id !== '') {
          //->where('auth_user_id', $current_user)
          $main_discussion = Models\MeetingReport::with('client_info', 'auth_user_info')->where('id', $id)->first();
        }
        else{
          if (session('current_user.designation') == 'administrator') {
            $main_discussion = Models\MeetingReport::with('client_info', 'auth_user_info')->get()->last();
          }
          else{
            $main_discussion = Models\MeetingReport::with('client_info', 'auth_user_info')->where('auth_user_id', $current_user)->get()->last();  
          }
          
        }
        // dump($current_user);
        //$main_discussion = Models\MeetingReport::with('client_info', 'auth_user_info')->where('auth_user_id', $current_user)->get()->last();
        // dd($main_discussion);
        // \Log::info('foo bar in the app');
        if (!$main_discussion) {
          return redirect(url('reports'));
        } 
        $payment_type = [ 1 => 'Prepaid', 2 => 'Postpaid'];
        $data = [
          'page_title' => 'Meeting Report',
          'main_discussion' => $main_discussion,
          'meeting_report_arr' => $meeting_report_arr,
          'payment_type' => $payment_type
        ];

        return view('report.details', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {   
        $clients = Models\Client::pluck('name','id');
        $service = Models\Service::pluck('name','name');
        $payment_type = Models\PaymentType::pluck('name', 'id');
        $payment_status = ['paid' => 'Paid', 'unpaid' => 'Unpaid'];

        $data = [
            'page_title' => 'Create Meeting Report',
            'service' => $service,
            'clients' => $clients,
            'payment_type' => $payment_type,
            'payment_status' => $payment_status
        ];

        return view('report.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([
            'client' => 'required',
            'service' => 'required',
            'contact_person' => 'required',
            'email' => 'required',
            'discussion' => 'required',
            'payment_type' => 'required',
            'current_balance' => 'required|numeric',
            'payment_status' => 'required',
            'next_follow_up_date' => 'required',
            'last_follow_up_date' => 'required' 
        ]);
        // dd($request->all());

        $the_report = $request->except('_token');
        $the_report['auth_user_id'] = session('current_user.id');

        $savereport = Models\MeetingReport::create($the_report);

        Session::flash('success_message', 'Report successfully added');
        return redirect(url('dashboard'));
    
    }

    public function store_sam_comment(Request $request){

      $comment = Models\SamComment::create(
          [
            'report_id' => $request->report_id, 
            'created_by_id' => $request->created_by_id,
            'message' => $request->message
          ]
      );

      return response()->json(['code' => 1, 'msg' => $comment]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
      //return redirect()->back()->withErrors(array("This section is under development. Kindly use the dashboard to view details of the reports"))->withInput();
      $meetingreport = Models\MeetingReport::with('client_info', 'auth_user_info')->where('id', $id)->first();
      $data = [
        'page_title' => 'Report Details',
        'showreport' => $meetingreport
      ];
      return view('report.show', $data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $report_arr = Models\MeetingReport::find($id);
        $clients = Models\Client::pluck('name','id');
        $service = Models\Service::pluck('name','type');
        $payment_type = Models\PaymentType::pluck('name', 'id');
        $payment_status = ['paid' => 'Paid', 'unpaid' => 'Unpaid'];

        $data = [
            'page_title' => 'Edit Meeting Report',
            'report_arr' => $report_arr,
            'service' => $service,
            'clients' => $clients,
            'payment_type' => $payment_type,
            'payment_status' => $payment_status
        ];

        return view('report.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'client' => 'required',
            'service' => 'required',
            'contact_person' => 'required',
            'email' => 'required',
            'discussion' => 'required',
            'payment_type' => 'required',
            'current_balance' => 'required',
            'payment_status' => 'required', 
        ]);
        $report_update = Models\MeetingReport::find($id);
        $report_update->client = $request->client;
        $report_update->service = $request->service;
        $report_update->contact_person = $request->contact_person;
        $report_update->email = $request->email;
        $report_update->discussion = $request->discussion;
        $report_update->payment_type = $request->payment_type;
        $report_update->current_balance = $request->current_balance;
        $report_update->payment_status = $request->payment_status;

        $report_update->auth_user_id = session('current_user.id');

        $result = $report_update->save();

        Session::flash('success_message', 'Report successfully Updated');
        return redirect(url('reports'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = Models\MeetingReport::destroy($id);
        if (request()->ajax()) {
            $result_arr = ['code' => 1];
            return response()->json($result_arr);
        }
        Session::flash('success_message', 'Report successfully deleted!');
        return redirect(route('reports.index'));
    }


    public function get_filter_ids($filter, $keyword)
    {
        switch ($filter) {
            case 'client':
              $id = Models\Client::where('name', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
            case 'service':
              $id = Models\MeetingReport::where('service', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
            case 'contact_person':
              $id = Models\MeetingReport::where('contact_person', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
            case 'email':
              $id = Models\MeetingReport::where('email', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
              case 'discussion':
              $id = Models\MeetingReport::where('discussion', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
              case 'payment_type':
              $id = Models\PaymentType::where('name', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
              case 'current_balance':
              $id = Models\MeetingReport::where('current_balance', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
            case 'payment_status':
              $id = Models\MeetingReport::where('payment_status', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              $the_id = $step[0]->id;
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
            case 'sam_comment':
              $id = Models\MeetingReport::where('sam_comment', 'like', "%$keyword%")->get(['id']);
              if ($id->isEmpty()) {
                return '';
              }
              $step = json_decode($id);
              return (count($step) > 0 ) ? $step[0]->id : "";
              break;
            default:
              return '';
              break;
        }
    }
}
