/**
  * Function that gets the client's credit information.
  *
  * @return Response
  */
 public function creditDebtPayment()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('formData' => 'required', 'debt' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'Informacion incompleta!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Get the user's cashbox.
     $cashbox = Cashbox::where('Close', '=', null)->where('UserId', '=', Auth::user()->Id)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'Debe abrir la caja para realizar este pago!';
         return response()->json($response);
     }
     // Get the debt we are paying.
     $debt = Sale::find(Input::get('debt'));
     $totalDebt = $debt->Value + $debt->Tax;
     // Check to see if there have been any previous payments.
     $pastPaymentTotal = 0;
     $payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $debt->Id)->get();
     foreach ($payments as $payment) {
         $pastPaymentTotal += $payment->Value;
     }
     // Check if we are paying too much money.
     if (Input::get('formData')['cdpAmount'] > $totalDebt - $pastPaymentTotal) {
         $response['state'] = 'Error';
         $response['error'] = 'Esta pagando mas del valor pendiente de la factura!';
         return response()->json($response);
     }
     // Realizar pago.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 8, 'Amount' => Input::get('formData')['cdpAmount'], 'Reason' => 'Pago a Deuda de Credito'));
     $payment = CashReceipt::create(array('TransactionId' => $transaction->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Reason' => 'Pago a Deuda de Credito', 'Value' => Input::get('formData')['cdpAmount'], 'Type' => 2, 'TypeId' => $debt->Id));
     if (Input::get('formData')['cdpAmount'] == $totalDebt - $pastPaymentTotal) {
         $debt->Cancelled = true;
         $debt->save();
     }
     $response['state'] = 'Success';
     $response['message'] = 'Pago realizado exitosamente!';
     $response['payment'] = $payment;
     return response()->json($response);
 }
 /**
  * Function that makes a payment to the defined contract.
  *
  * @return Response
  */
 public function contractPayment()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('id' => 'required', 'cash' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'No se recibieron los datos necesarios!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Get user's cashbox.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta, por lo tanto no se puede realizar el pago al contrato!';
         return response()->json($response);
     }
     // Get the contract information.
     $contract = Contract::find(Input::get('id'));
     // Get current configuration.
     $config = Configuration::find(0);
     // Now make the payment.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 7, 'Amount' => Input::get('cash'), 'Reason' => 'Pago a Contrato.'));
     // Type = 1 when it's a contract payment.
     $cashReceipt = CashReceipt::create(array('TransactionId' => $transaction->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Reason' => 'Pago a Contrato.', 'Value' => Input::get('cash') / $config->Dollar, 'Type' => 1, 'TypeId' => $contract->Id));
     // Now let's check if it the contract's state was late and if it was let's see if we have to update it.
     $contractPayments = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contract->Id)->get();
     if ($contract->State == 'late') {
         // Get today's date.
         $today = date_create(date('Y-m-d'));
         // Get the amount of time that has passed since contract has been created.
         $time = date_diff($today, date_create($contract->StartDate));
         // Check how many intervals have passed.
         $passedIntervals = 0;
         if ($contract->QuotaInterval == 'mensuales') {
             $passedIntervals = floor($time->format('%m'));
         } else {
             if ($contract->QuotaInterval == 'quincenales') {
                 /* 1 Month has an average of 4.34524 weeks*/
                 $passedIntervals = floor($time->format('%a') / 7) / 4.34524;
                 $decimal = $passedIntervals - floor($passedIntervals);
                 if ($decimal >= 0.5) {
                     $passedIntervals = floor($passedIntervals) * 2 + 1;
                 } else {
                     $passedIntervals = floor($passedIntervals) * 2;
                 }
             } else {
                 if ($contract->QuotaInterval == 'semanales') {
                     $passedIntervals = floor($time->format('%a') / 7);
                 }
             }
         }
         // Now finally get the expected payment.
         $expectedPayment = $passedIntervals * $contract->Quota;
         // If it is over the Debt of the contract reset it to contract value.
         if ($expectedPayment > $contract->Debt) {
             $expectedPayment = $contract->Debt;
         }
         // Calculate real payments.
         $realPayment = 0;
         foreach ($contractPayments as $contractPayment) {
             $realPayment += $contractPayment->Value;
         }
         if ($realPayment >= $expectedPayment) {
             $contract->State = 'good';
             $contract->save();
         }
     }
     // Check if we have finished paying contract.
     $debt = $contract->Debt;
     foreach ($contractPayments as $contractPayment) {
         $debt -= $contractPayment->Value;
     }
     if ($debt <= 0) {
         $contract->State = 'paid';
         $contract->save();
     }
     $response['receipt'] = $cashReceipt->Id;
     $response['state'] = 'Success';
     // Return response.
     return response()->json($response);
 }