<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use App\User;
use App\YesPin;
use Illuminate\Http\Request;
use App\Http\Requests\StoreUsersRequest;
use App\Http\Requests\UpdateUsersRequest;
use Yajra\Datatables\Datatables;
use Mail;
use Session;
class CustomersController extends Controller
{
     public function index()
     {
        if(!empty(Session::get('customer_logged_id'))){
            $customer = \App\Customer::where([
                ['id','=', Session::get('customer_logged_id')],
            ])->first();
            if(!isset($customer->id)){
                return redirect()->route('customer.login')->with('error','User not found.');
            }
        }else{
            return redirect()->route('customer.login')->with('error','Please login to access.');
        }
        $siteTitle = "Customers";
        
        $relations = [
            'projects' => \App\Project::select(\DB::raw("CONCAT(name) AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
            'siteTitle' => $siteTitle,
            'customer' => $customer
          ];
        return view('customers.index', $relations);
     }

     public function anyData(Request $request)
     {
        if(!empty(Session::get('customer_logged_id'))){
            $customer = \App\Customer::where([
                ['id','=', Session::get('customer_logged_id')],
            ])->first();
            if(!isset($customer->id)){
                return redirect()->route('customer.login')->with('error','User not found.');
            }
        }else{
            return redirect()->route('customer.login')->with('error','Please login to access.');
        }

        $query = \App\Deal::select(
          'deals.*', 
          'users.full_name as full_name', 
          'users.username as username', 
          'customers.full_name as c_full_name', 
          'customers.username as c_username',
          'plots.status as p_status',
          'plots.area as p_area',
          'plots.dimension as p_dimension',
        )
        ->join('users', 'users.id', '=', 'deals.associate_id')
        ->join('customers', 'customers.id', '=', 'deals.customer_id')
        ->join('plots', 'plots.id', '=', 'deals.plot_id')
        ->join('projects', 'projects.id', '=', 'plots.project_id')
        ->join('sectors', 'sectors.id', '=', 'plots.sector_id')
        ->join('blocks', 'blocks.id', '=', 'plots.block_id')
        ->where('deals.customer_id', '=', $customer->id);
        if (is_numeric($request->input("plot_id")) && $request->input("plot_id") >  0) {
            $query = $query->where('deals.plot_id', $request->input("plot_id"));
        }
        if (is_numeric($request->input("project_id")) && $request->input("project_id") >  0) {
            $query = $query->where('plots.project_id', $request->input("project_id"));
        }
        if (is_numeric($request->input("sector_id")) && $request->input("sector_id") >  0) {
            $query = $query->where('plots.sector_id', $request->input("sector_id"));
        }
        if (is_numeric($request->input("block_id")) && $request->input("block_id") >  0) {
            $query = $query->where('plots.block_id', $request->input("block_id"));
        }
      return Datatables::of($query)
         ->addColumn('action',
         '<a class="btn btn-success btn-sm" href="{{ url(\'/customer/deals/details/\'.$id) }}">'
         .'  <span class="ladda-label">Payment Status</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</a>'
       )
        ->editColumn('created_at', function(\App\Deal $YesIncome) {
                    return date('Y-m-d H:i:s', strtotime($YesIncome->created_at));
        })
       ->make(true);
     }

    public function pendingBookingAnyData(Request $request)
     {
        if(!empty(Session::get('customer_logged_id'))){
            $customer = \App\Customer::where([
                ['id','=', Session::get('customer_logged_id')],
            ])->first();
            if(!isset($customer->id)){
                return redirect()->route('customer.login')->with('error','User not found.');
            }
        }else{
            return redirect()->route('customer.login')->with('error','Please login to access.');
        }

        $query = \App\Deal::select(
          'deals.*', 
          'users.full_name as full_name', 
          'users.username as username', 
          'plots.status as p_status',
          'plots.area as p_area',
          'plots.dimension as p_dimension',
        )
        ->join('users', 'users.id', '=', 'deals.associate_id')
        ->join('plots', 'plots.id', '=', 'deals.plot_id')
        ->join('projects', 'projects.id', '=', 'plots.project_id')
        ->join('sectors', 'sectors.id', '=', 'plots.sector_id')
        ->join('blocks', 'blocks.id', '=', 'plots.block_id')
        ->where([['deals.customer_id', '=', $customer->id], ['plots.status', '=', 'onhold']]);
        if (is_numeric($request->input("plot_id")) && $request->input("plot_id") >  0) {
            $query = $query->where('deals.plot_id', $request->input("plot_id"));
        }
        if (is_numeric($request->input("project_id")) && $request->input("project_id") >  0) {
            $query = $query->where('plots.project_id', $request->input("project_id"));
        }
        if (is_numeric($request->input("sector_id")) && $request->input("sector_id") >  0) {
            $query = $query->where('plots.sector_id', $request->input("sector_id"));
        }
        if (is_numeric($request->input("block_id")) && $request->input("block_id") >  0) {
            $query = $query->where('plots.block_id', $request->input("block_id"));
        }
      return Datatables::of($query)
      ->editColumn('created_at', function(\App\Deal $YesIncome) {
                    return date('Y-m-d H:i:s', strtotime($YesIncome->created_at));
        })

       ->make(true);
     }

    public function dealDetails($deal_id)
    {

        if(!empty(Session::get('customer_logged_id'))){
            $customer = \App\Customer::where([
                ['id','=', Session::get('customer_logged_id')],
            ])->first();
            if(!isset($customer->id)){
                return redirect()->route('customer.login')->with('error','User not found.');
            }
        }else{
            return redirect()->route('customer.login')->with('error','Please login to access.');
        }

        $deal = \App\Deal::where('id', '=', $deal_id)->first();
        if(isset($deal->id)){
        $relations = [
            'projects' => \App\Project::select(\DB::raw("CONCAT(name, '') AS name_text"), 'id')
            ->get()
            ->pluck('name_text', 'id')->prepend('Please select', ''),
            'plot' => DB::table('plots')->select('plots.*', 'projects.name as projectName', 'sectors.name as sectorName', 'blocks.name as blockName')
                    ->join('projects', 'projects.id', '=', 'plots.project_id')
                    ->join('sectors', 'sectors.id', '=', 'plots.sector_id')
                    ->join('blocks', 'blocks.id', '=', 'plots.block_id')
                    ->where('plots.id', '=', $deal->plot_id)
                    ->first(),
            'invoices' => \App\Invoice::where('deal_id', '=', $deal_id)->orderBy('invoice_no')->get(),
            'payments' => \App\Payment::where('deal_id', '=', $deal_id)->get(),
            'invoice' => \App\Invoice::where([['deal_id', '=', $deal_id],['completed_on','=',NULL]])->orderBy('invoice_no')->first(),
            'payment_methods' => \Config::get('settings.payment_methods'),
            'deal' => $deal,
        ];
        return view('customers.deal_detail', $relations);
     }else{
      return Redirect::back()->with('errormessage', 'Deal not found!');
     }

    }

    /**
     * Show the form for creating new User.
     *
     * @return \Illuminate\Http\Response
     */

    /**
     * Display User.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $relations = [
            'roles' => \App\Role::get()->pluck('title', 'id')->prepend('Please select', ''),
        ];

        $user = \App\Customer::findOrFail($id);

        return view('customers.show', compact('user') + $relations);
    }


    public function login(){
        //dd(Session::get('customer_logged_id'));
        if(!empty(Session::get('customer_logged_id'))){
            return redirect()->route('customer.index');
        }
        return view('customers.login');
    }

    public function doLogin(Request $request){
        $this->validate($request,[
         'username'=>'required',
         'password'=>'required'
        ]);

        $customer = \App\Customer::where([
            ['username','=', $request->username],
            ['mobileno', '=', $request->password]
        ])->first();

        if(isset($customer->id)){
            Session::put('customer_logged_id', $customer->id);
            return redirect()->route('customer.index')->with('message','Logged in successfully.');
        }else{
            return redirect()->route('customer.login')->with('error','Username password do not match.');
        }
    }

    public function logout(){
        //dd(Session::get('customer_logged_id'));
        if(Session::forget('customer_logged_id')){
            return redirect('/index');
        }
        return redirect('/index');
    }

    public function profile(){

        if(!empty(Session::get('customer_logged_id'))){
            $customer = \App\Customer::where([
                ['id','=', Session::get('customer_logged_id')],
            ])->first();
            if(!isset($customer->id)){
                return redirect()->route('customer.login')->with('error','User not found.');
            }
        }else{
            return redirect()->route('customer.login')->with('error','Please login to access.');
        }

        return view('customers.profile', ['customer'=>$customer]);
    }

    public function printReceiptsPrint($id)
    {
        if(!empty(Session::get('customer_logged_id'))){
            $customer = \App\Customer::where([
                ['id','=', Session::get('customer_logged_id')],
            ])->first();
            if(!isset($customer->id)){
                return redirect()->route('customer.login')->with('error','User not found.');
            }
        }else{
            return redirect()->route('customer.login')->with('error','Please login to access.');
        }


        $payment = \App\Payment::where([
            ['id', '=', $id],
            ['status', '=', 1],
            ['customer_id', '=', $customer->id],
            ])->first();
        if(!$payment)
        {   
          return Redirect::back()
                      ->with('errormessage', "Payment not found!.")
                      ->withInput();
        }else{
            $deal = \App\Deal::where('id','=',$payment->deal_id)->first();
            $plot = \App\Plot::where('id','=',$deal->plot_id)->first();
            $project = \App\Project::where('id','=',$plot->project_id)->first();
            $block = \App\Block::where('id','=',$plot->block_id)->first();
            $sector = \App\Sector::where('id','=',$plot->sector_id)->first();
            $associate = \App\User::where('id', '=', $deal->associate_id)->first();
            $paymentPlan = \App\PaymentPlan::where('id', '=', $deal->payment_plan_id)->first();
            return view('customers.printReciept', compact(
              'payment',
              'deal',
              'plot',
              'project',
              'sector',
              'block',
              'customer',
              'paymentPlan',
              'associate'
            ));
        }
    }

}
