<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\InstallmentRequest;
use App\Installment;
use Illuminate\Contracts\Encryption\DecryptException;
use Crypt;
use App\Booking;


class InstallmentController extends Controller
{
  public function storeInstallment(InstallmentRequest $request)
  {
   try
   {
        
        $form_collect = $request->input();


        $form_collect['booking_id']  = decrypt($form_collect['booking_id']);

        $installment = new Installment;


        if($installment->storePlan($form_collect))
        {

           $booking = new Booking;

           $booking = $booking->getBookingById($form_collect['booking_id']);

           if(isset($booking->id))
           {
              $amount = array_sum($form_collect['amount']);

              parent::setLogMessage('Installment plan '.number_format($amount).' has been created against '.$booking->ms.' ('.$booking->plot->plot_id.' '.$booking->plot->block_name.') plot.');
           }

           parent::successMessage('Installment Plan has been created.',parent::getLogMessage());

           if(\Request::ajax())
           {
              return 1;
           }
        }
     }


     catch (DecryptException $e) 
     {

     } 

return back();

}

public function bulkInstallmentRemove(Request $request)
{


    $count = 0;
    $amount = 0;

    try 
    {
        $booking_id = decrypt($request->input('booking_id'));

        $installment = new Installment;

        foreach ($request->installment_list as $rows) 
        {

          $curr_installment = $installment->removeInstallment(decrypt($rows));

          if(isset($curr_installment->id))
          {
              $amount += $curr_installment->amount;
          }


          $count++;
        }

        if($count > 0)
        {
          $booking = new Booking;

          $booking = $booking->getBookingById($booking_id);

          if(isset($booking->id))
          {
              parent::setLogMessage('Installments '.number_format($amount).' has been removed against '.$booking->ms.' ('.$booking->plot->plot_id.' '.$booking->plot->block_name.') plot.');
          }

          parent::successMessage('Instamments has been removed.',parent::getLogMessage());
        }



    }
    catch (DecryptException $e) 
     {

     }
         
        return 0; 
}

public function storeOnetime(InstallmentRequest $request)
{
 try
 {

  $form_collect = $request->input();

  $form_collect['booking_id']  = decrypt($form_collect['booking_id']);


  $amount = array_sum($form_collect['amount']);

  $onetime = new Installment;

  if($onetime->storePlan($form_collect))
  {

    $booking = new Booking;

    $booking = $booking->getBookingById($form_collect['booking_id']);

    if(isset($booking->id))
       {
          parent::setLogMessage('One time payment '.number_format($amount).' has been created against '.$booking->ms.' ('.$booking->plot->plot_id.' '.$booking->plot->block_name.') plot.');
       }
   parent::successMessage('One Time Plan has been created.',parent::getLogMessage());

   if(\Request::ajax())
   {
      return 1;
   }
 }
}


catch (DecryptException $e) 
{
  echo 1;
}

return back();


}

public function updateInstallment(InstallmentRequest $request)
{
  try
  {

    $form_collect = $request->input();

    $form_collect['id']  = decrypt($form_collect['id']);

    $installment = new Installment;

    $curr_installment = $installment->updatePlanById($form_collect);

    if(isset($curr_installment->id))
    {
        $booking = $curr_installment->booking;

        if(isset($booking->id))
        {
            parent::setLogMessage($curr_installment->description.' has been updated against '.$booking->ms.' ('.$booking->plot->plot_id.' '.$booking->plot->block_name.') plot.');
        }

        parent::successMessage('Installment has been updated.',parent::getLogMessage());
   }
 }


 catch (DecryptException $e) 
 {
 }

return back();

}

public function removeInstallment($id)
{
  parent::errorMessage('Installment not found.');

  try 
  {
    $id = decrypt($id);

    $installment = new Installment;

    $curr_installment = $installment->removeInstallment($id);

    if(isset($curr_installment->id))
    {


          $booking = $curr_installment->booking;

          if(isset($booking->id))
          {
              parent::setLogMessage($curr_installment->description.' '.number_format($curr_installment->amount).' has been removed against '.$booking->ms.' ('.$booking->plot->plot_id.' '.$booking->plot->block_name.') plot.');
          }

          parent::successMessage('Installment has been removed.',parent::getLogMessage());
    } 
  } 
  catch (DecryptException $e) 
  {

  }

  return redirect()->back();
}

public function getInstallments($id)
{
  try 
  {
    $id = decrypt($id);

    $installment= new Installment();

    $installments = $installment->getInstallmentByStauts($id,'asc');

    $view = '<option value="'.Crypt::encrypt(0).'">Select Installment</option>';

    foreach($installments as $rows)
    {
      $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->description.'</option>';
    }
    return $view;
  } 
  catch (DecryptException $e) 
  {

  }

  return redirect()->back();   

}

public function getInstallmentAmount($id)
{
  if(\Request::ajax())
  {
   try 
   {
    $id = decrypt($id);


    $installment= new Installment();

    $current_installment = $installment->getInstallmentById($id,['amount','received_amount','booking_id']);    

    $amount = ($current_installment->amount) - ($current_installment->received_amount);

    $user = $current_installment->booking->user;

    $data = array();
    $data['amount'] = $amount;

    $data['user_view'] = '<option value="'.Crypt::encrypt($user->id).'">'.ucfirst($user->name).' '.ucfirst($user->designation).'</option>';
    $data['type'] = $user->type;

    return $data;
  } 
  catch (DecryptException $e) 
  {

  }

}

return redirect()->back();

}

public function intervalInstallment(Request $request)
{
  $form_collect = $request->input();

  parent::errorMessage('Required Validations');

  $validatedData = $request->validate([

           'interval'       => 'required|integer',

           'amount'         => 'required|integer',  
                   
            ]);

  $booking_id = decrypt($form_collect['booking_id']);


  $installment = new Installment();

  $booking_installments = $installment->getInstallmentByType($booking_id,['Installment']);
  if(isset($booking_installments))
  {

  $interval = $form_collect['interval'];
  $installments_count = count($booking_installments);
  

if($interval > 0 && $interval <= $installments_count)
{
  $installment_sum = 0;

  $number = $installments_count/$interval;

  $calculated_sum = $number * $form_collect['amount'];

  $remaining_amount = $installment->verificationPlan($booking_id);

  for($i = $interval-1; $i< $installments_count; $i = $i + $interval)
  {
   $installment_sum += $booking_installments[$i]->amount;

  }
    $amount = $remaining_amount + $installment_sum;
     if($calculated_sum <= $amount)
     {
       for($i = $interval-1; $i< $installments_count; $i = $i + $interval)
       {
         if($booking_installments[$i]->received_amount == 0)
         {
           $booking_installments[$i]->amount = $form_collect['amount'];

           $booking_installments[$i]->update();
          
         }
        
       }
        parent::successMessage('Plan has been updated.');
     }
     else
     {
       parent::errorMessage('Invalid Amount');
     }
  
}
else
{
  parent::errorMessage('Interval must be greater than zero and less than no of installments.');
}

  }
     return redirect()->back();

}
}
