<?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 Validator;
use App\Http\Requests\StoreUsersRequest;
use App\Http\Requests\UpdateUsersRequest;
use Yajra\Datatables\Datatables;
use Mail;
use Carbon\Carbon;

class PaymentsController extends Controller
{
    /**
     * Display a listing of User.
     *
     * @return \Illuminate\Http\Response
     */
     public function index()
     {
         $siteTitle = "Payments";
         $user = Auth::user();
         return view('payments.index', compact('user', 'siteTitle'));
     }
     
     public function anyData()
     {
        $user = Auth::user();
         return Datatables::of(\App\Payment::select(
          'payments.*', 
          'users.full_name as full_name', 
          'users.username as username', 
          'customers.full_name as c_full_name', 
          'customers.username as c_username'
        )
          ->join('users', 'users.id', '=', 'payments.associate_id')
          ->join('customers', 'customers.id', '=', 'payments.customer_id')
          ->where('payments.associate_id', '=', $user->id)
        )
         ->addColumn('status_action',
         '<span class="label label-light-{{getPaymentStatusClass($status)}}">'
         .'{{getPaymentStatus($status)}}'
         .'</span>'
         .'on {{$paid_on}}'
       )
       ->rawColumns(['status_action'])
       ->make(true);
     }
    public function store(Request $request)
    {
        $user = Auth::user();
        $invoice_no = 1;
        if($request->invoice_id){
            $validator = Validator::make($request->all(), [
              'invoice_id' => 'required|exists:invoices,id',
              'deal_id' => 'required|exists:deals,id',
              'amount' => 'required|numeric',
              'payment_type' => 'required',
            ]);
            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                $validateCreatePayment = $this->validateCreatePayment($request);
                
                if($validateCreatePayment->valid == false)
                {   
                    return Redirect::back()
                                ->with('errormessage', $validateCreatePayment->message)
                                ->withInput();
                }
                elseif($validateCreatePayment->valid == true)
                {
                    $user = Auth::user();
                    $deal = \App\Deal::where('id','=',$request->deal_id)->first();
                    $customer = \App\Customer::where('id', '=', $deal->customer_id)->first();
                    $associate = \App\User::where('id', '=', $deal->associate_id)->first();
                    $validateCreatePayment = $this->validateCreatePayment($request);
                    $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();
                    $dealName = $plot->name.' : '.$plot->blockName.' : '.$plot->sectorName.' : '.$plot->projectName;
                    $invoice = $this->updatePlotInvoices($deal, $request, $customer, $associate, $plot);
                    
                    $newPayment = \App\Payment::create([
                                    'invoice_id' => $request->invoice_id,
                                    'deal_id' => $request->deal_id,
                                    'plot_id' => $plot->id,
                                    'amount' => $request->amount,
                                    'payment_type' => $request->payment_type,
                                    'bank_name' => $request->bank_name,
                                    'bank_branch' => $request->bank_branch,
                                    'payment_date' => $request->payment_date,
                                    'payment_reference' => $request->payment_reference,
                                    'name' => $dealName,
                                    'paid_on' => NULL,
                                    'associate_id' => $associate->id,
                                    'customer_id' => $customer->id,
                                    'invoice_due_amount' => $validateCreatePayment->invoice_due_amount,
                                    'total_due_amount' => $validateCreatePayment->total_due_amount,
                                    'added_by' => $user->id,
                                    'plot_id' => $deal->plot_id,
                                    'status' => 0,
                                    'comment' => $request->comment,
                                  ]);
                    
                    $invoice_name = $this->getGUIDnoHash($newPayment->id, $deal->id);
                    
                    \App\Payment::where('id', '=', $newPayment->id)->update(['invoice_name'=>$invoice_name]);
                      
                    $wallet = \App\YesUsersWallet::where('user_id', '=', $deal->associate_id)->first();
                    if(!isset($wallet->id)){
                        $wallet =  $this->createBlankWallet($user);
                    }
                      
                    \App\YesUsersWallet::where('id', '=', $wallet->id)->update([
                        'pending_amount' => $wallet->pending_amount + $request->amount,
                    ]);

                    return Redirect::back()->with('message','Payment added successfully!');
                }
            }
        }
    }
    protected function validateCreatePayment($request){
        $validator = new \stdClass();
        $deal = \App\Deal::where('id','=',$request->deal_id)->first();
        $validator->valid = true;
        $validator->message = "";
        $validator->due_amount = 0 ;
        $validator->total_amount_paid = $deal->paid_amount + $request->amount;
        $validator->total_due_amount = $deal->calc_total_amount - $validator->total_amount_paid;
        $validator->invoice_due_amount = 0;
        // if($request->payment_plan == 1){
        //     $key = $request->emi_duration-1;
        //     $emi = $request->emi;
        //     if(!isset($emi[$key])||!isset($request->emi_start_date)){
        //         $validator->valid = false;
        //         $validator->message = "Please fill EMI Start Date and all EMI amount Fields.";
        //     }else{
        //         foreach($request->emi as $amount){
        //             $validator->due_amount = $validator->due_amount + $amount;
        //         }
        //         $validator->due_amount = $validator->due_amount + $request->booking_amount + $request->allotment_amount;
        //     }
        // }
        return $validator;
    }
    
    protected function updatePlotInvoices($deal, $request, $customer, $associate, $plot){
        $deal_types = \Config::get('settings.deal_types');
        $invoice_no = 1;
        $invoices = \App\Invoice::where('deal_id','=',$deal->id)->orderBy('invoice_no')->get();
        $total_amount_paid = $deal->paid_amount + $request->amount;
        $total_due_amount = $deal->calc_total_amount - $total_amount_paid;
        $invoice_due_amount = 0;
        $total_invoice = 0;
        $due_date = NULL;
        \App\Deal::where('id','=',$deal->id)
                ->update([
                  'due_amount' => $total_due_amount,
                  'paid_amount' => $deal->paid_amount + $request->amount,
                ]);
        foreach($invoices as $invoice){
          $total_invoice = $total_invoice + $invoice->amount;
          if($total_invoice <= $total_amount_paid && $invoice->paid_on == NULL){
                $invs = \App\Invoice::where('id','=',$invoice->id)
                ->update([
                  'paid_on' => Carbon::now(),
                  'status' => 1,
                ]);
            }
          }
        }
    protected function getGUIDnoHash($id, $deal_id){
      return 'YES-'.date('Y-m-d-').$deal_id.'-'.$id;
    }
    
 
    /**
     * Show the form for creating new User.
     *
     * @return \Illuminate\Http\Response
     */
    public function addpayments($deal_id)
    {
        $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('payments.create', $relations);
     }else{
      return Redirect::back()->with('errormessage', 'Deal not found!');
     }

    }

    public function printReceipts()
    {
      $user = Auth::user();
      $payments = \App\Payment::where([
        ['status', '=', 1],
        ['associate_id', '=', $user->id],
      ])->get();
      return view('payments.printReciepts', compact('user', 'payments'));
    }
    
    public function printReceiptsPrint($id)
    {
      $user = Auth::user();
      $payment = \App\Payment::where([
        ['id', '=', $id],
        ['status', '=', 1],
        ['associate_id', '=', $user->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();
        $customer = \App\Customer::where('id', '=', $deal->customer_id)->first();
        $associate = \App\User::where('id', '=', $deal->associate_id)->first();
        $paymentPlan = \App\PaymentPlan::where('id', '=', $deal->payment_plan_id)->first();
        return view('payments.printReciept', compact(
          'user',
          'payment',
          'deal',
          'plot',
          'project',
          'sector',
          'block',
          'customer',
          'paymentPlan',
          'associate'
        ));
      }
    }

    public function dueEMIReport()
    {
         $user = Auth::user();
         return view('incomes.dueEMIReport', compact('user'));
    }
    
    public function dueEMIReportAnyData(Request $request)
    {  

        $user = Auth::user();
        $dueEMIReport = $this->getDueEMIReport($user);
        
        $datatables = Datatables::of($dueEMIReport)->addColumn('action',
         '<button class="btn btn-success btn-sm openModal" data-style="zoom-out" data-id="{{ $deal_id }}">'
         .'  <span class="ladda-label">View Deal</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</button>');

        return $datatables->make(true);
    }

    public function getDueEMIReport($user, $limit=NULL){
                //Fix for group by error https://stackoverflow.com/questions/40917189/laravel-syntax-error-or-access-violation-1055-error
                \DB::statement("SET SQL_MODE=''");
                
                $query =  DB::table('invoices')->select(
                    'invoices.*',
                    'customers.full_name as full_name',
                    'customers.username as username'
                    )
                    ->join('customers', 'customers.id', '=', 'invoices.customer_id')
                    ->join('deals', 'deals.id', '=', 'invoices.deal_id')
                    ->where([
                      ['deals.status', '=', 0],
                      ['invoices.status', '=', 0],
                      ['invoices.due_date', '<', Carbon::now()],
                    ])
                    ->groupBy('deals.id')
                    ->orderBy('invoices.due_date', 'asc');
                if($limit != NULL){
                    $query = $query->limit($limit);
                }
                $query = $query->get();
                return $query;
    }

    public function addpaymentsAjax($deal_id)
    {
        $user = Auth::user();
        $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('partials.dealsAjax', $relations);
       }
    }


    protected function createBlankWallet($user){
      $wallet = \App\YesUsersWallet::create([
                      'user_id' => $user->id,
                      'available_amount' =>0,
                      'available_amount_tds'=>0,
                      'approved_amount' =>0,
                      'pending_amount' =>0,
                      'business_amount' =>0,
                      'advance_payment' => 0
                    ]);
      return $wallet;
    }
}
