<?php

use App\Contract;
use App\CashboxTransaction;
use App\CashReceipt;
// Get transactions of contract payments.
$transactions = array();
if (isset($contractId) && $contractId != 0) {
    $paymentReceipts = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contractId)->get();
    foreach ($paymentReceipts as $paymentReceipt) {
        // Get the transaction.
        $transaction = CashboxTransaction::find($paymentReceipt->TransactionId);
        array_push($transactions, $transaction);
    }
}
?>
@foreach($transactions as $transaction)
	<tr id='transaction-{{ $transaction->Id }}'><td>{{ $transaction->DateTime }}</td><td>Pago a Contrato.</td><td>{{ $transaction->Amount }}</td></tr>
@endforeach
use App\Client;
use App\Institution;
use App\CashReceipt;
use App\Transport;
use App\Branch;
// Get the sale.
$creditDue = Sale::find($sale['Id']);
// Get the branch.
$branch = Branch::find($creditDue->BranchId);
// Get the creditor.
$creditor = null;
if ($sale->CreditorType == 1) {
    $creditor = Client::find($sale->CreditorId);
} else {
    $creditor = Institution::find($sale->CreditorId);
}
// Get the transport request.
$paymentCollection = Transport::find($transport['Id']);
$payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $sale->Id)->get();
$totalDue = $creditDue->Value + $creditDue->Tax;
foreach ($payments as $payment) {
    $totalDue -= $payment->Value;
}
?>
<p>{{ $creditor->Name }},</p>
<p>Les enviamos el siguiente correo para dejarles saber que el {{ $transport->Date }} estaremos llegando a recoger el pago de la factura numero {{ $sale->Id }}. El total pendiente es de C$ {{ $totalDue }}.</p>
<p>Si por algun motivo no podra pagar ese dia puede reprogramar nuestra visita respondiendo a este correo de la siguiente manera:</p>
<p>Reprogramar:{{ date('Y-m-d', strtotime("+5 days")) }}</p>
<p>Se despide cordialmente,</p>
<p>Aergia AI (Inteligencia Artificial)</p>
<p>{{ $branch->Name }}</p>
function contractStateTitle($contract)
{
    // Check what state it's in.
    if ($contract->State == 'late') {
        // Get today's date.
        $today = date_create(date('Y-m-d'));
        // Get the contract Payments.
        $contractPayments = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contract->Id)->get();
        // 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;
        }
        return 'Este cliente esta en mora y debe $' . ($expectedPayment - $realPayment) . '!';
    } else {
        if ($contract->State == 'good') {
            return 'Los pagos van al dia!';
        } else {
            if ($contract->State == 'cancelled') {
                return 'Este contrato ha sido cancelado.';
            } else {
                if ($contract->State == 'progress') {
                    return 'Este contrato esta en proceso de ser usado por el cliente.';
                } else {
                    if ($contract->State == 'finalized') {
                        return 'Este contrato ya ha sido completado.';
                    } else {
                        return 'Este contrato ha sido pagado pero no ha sido usado por el cliente.';
                    }
                }
            }
        }
    }
    $paymentReceipts = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contract->Id)->get();
    foreach ($paymentReceipts as $paymentReceipt) {
        $contract->Debt -= $paymentReceipt->Value;
    }
    if ($contract->Debt < 0) {
        return 0;
    }
    return round($contract->Debt, 2);
}
 /**
  * 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);
 }
 /**
  * Function that deletes Transaction.
  *
  * @return Response
  */
 public function deleteAuthenticated()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('id' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'La identification de la transaccion es necesaria!';
         return response()->json($response);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         $response['state'] = 'No Autorizado';
         $response['error'] = 'Usuario no autorizado!';
         return response()->json($response);
     }
     // Verify the user first.
     $userToVerify = User::where('Username', '=', Input::get('username'))->first();
     if (!$userToVerify) {
         $response['state'] = 'Error';
         $response['error'] = 'Este usuario no existe!';
         return response()->json($response);
     }
     if (Auth::validate(array('Username' => Input::get('username'), 'password' => Input::get('password') . $userToVerify->Salt, 'Type' => 1))) {
         // If user was verified make sure user has permission to withdraw money.
         $permissions = json_decode(UserLevel::find($userToVerify->UserLevel)->Permissions);
         if ($permissions->permissions->cashbox->delete->can != "true") {
             $response['state'] = 'Error';
             $response['d'] = $permissions->permissions->cashbox->delete->can;
             $response['error'] = 'Este usuario no tiene permitido eliminar transacciones!';
             return response()->json($response);
         }
     } else {
         $response['state'] = 'Error';
         $response['error'] = 'Usuario o contraseña incorrectos!';
         return response()->json($response);
     }
     // Get transaction Data.
     $transaction = CashboxTransaction::find(Input::get('id'));
     if (!$transaction) {
         $response['state'] = 'Fail';
         $response['error'] = 'Esta transaccion no existe!';
         return response()->json($response);
     }
     // Get cashbox.
     $cashbox = Cashbox::find($transaction->CashboxId);
     // Get worker.
     $worker = Worker::find(User::find($cashbox->UserId)->TypeId);
     if ($transaction->Type == 1 || $transaction->Type == 8) {
         // Get sale.
         $sale = Sale::where('TransactionId', '=', $transaction->Id)->first();
         // Get items in sale.
         $items = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
         // Loop trough sales breakdown and add products and materials back to stock.
         foreach ($items as $item) {
             $product = Stock::where('Code', '=', $item->Code)->where('BranchId', '=', $sale->BranchId)->first();
             if (!$product) {
                 $service = Service::where('Code', '=', $item->Code)->where('BranchId', '=', $sale->BranchId)->first();
                 // Get materials.
                 $materials = json_decode($service->Materials);
                 foreach ($materials as $material => $quantity) {
                     // Update Stock.
                     $product = Stock::where('Code', '=', $material)->where('BranchId', '=', $sale->BranchId)->first();
                     $product->AverageCost = ($product->AverageCost * $product->Quantity + $product->Cost * $quantity) / ($product->Quantity + $quantity);
                     $product->Quantity += $quantity;
                     $product->save();
                 }
             } else {
                 // Update product.
                 $product->AverageCost = ($product->AverageCost * $product->Quantity + $item->Cost * $item->Quantity) / ($product->Quantity + $item->Quantity);
                 $product->Quantity += $item->Quantity;
                 $product->save();
             }
             // Delete item.
             $item->delete();
         }
         // Now delete sale and trasaction.
         $sale->delete();
         $transaction->delete();
         // Now return transaction data.
         $response['state'] = 'Success';
         $response['message'] = 'Transaccion eliminada!';
         return response()->json($response);
     } else {
         if ($transaction->Type == 7) {
             // Get the cash receipt.
             $receipt = CashReceipt::where('TransactionId', '=', $transaction->Id)->first();
             // Get the contract.
             $contract = Contract::find($receipt->TypeId);
             // Now delete receipt.
             $receipt->delete();
             // Delete transaction.
             $transaction->delete();
             // If contract is not in late state then that means we might need to update the state.
             if ($contract->State != 'late') {
                 // Get today's date.
                 $today = date_create(date('Y-m-d'));
                 // Get the contract Payments.
                 $contractPayments = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contract->Id)->get();
                 // 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 = 'late';
                     $contract->save();
                 }
             }
             // Now return transaction data.
             $response['state'] = 'Success';
             $response['message'] = 'Pago a contrato eliminado!';
             return response()->json($response);
         } else {
             if ($transaction->Type == 9) {
                 // If it's a reservation get the reservation with this transaction Id.
                 $reservation = Reservation::where('TransactionId', '=', $transaction->Id)->first();
                 $reservation->State = 'deleted';
                 $reservation->save();
                 // Now delete transaction.
                 $transaction->delete();
                 // Now return transaction data.
                 $response['state'] = 'Success';
                 $response['message'] = 'Deposito y reservacion eliminados!';
                 return response()->json($response);
             } else {
                 // Check if this is a payment for a provider bill.
                 if ($transaction->Type == 2) {
                     // Get the provider bill information.
                     $providerBillPayment = ProviderBillPayment::where('TransactionId', '=', $transaction->Id)->first();
                     // Get the provider bill and provider.
                     $providerBill = ProviderBill::find($providerBillPayment->ProviderBillId);
                     // Check if bill has credit.
                     if ($providerBill->Credit) {
                         // Set as unpaid (No way you can delete a payment and still stay paid -.-).
                         $providerBill->State = 1;
                         $providerBill->save();
                         // Delete payment.
                         $providerBillPayment->delete();
                         $response['message'] = 'Transaccion eliminada!';
                     } else {
                         // Get sale breakdown.
                         $items = ProviderBillBreakdown::where('ProviderBillId', '=', $providerBill->Id)->get();
                         $response['items'] = $items;
                         // Get the branch of the current worker.
                         $branchId = Worker::find(Auth::user()->TypeId)->BranchId;
                         // Loop through them and update stock.
                         foreach ($items as $item) {
                             // Get product.
                             $product = Stock::where('Code', '=', $item->Code)->where('BranchId', '=', $branchId)->first();
                             // Update it.
                             $totalAfter = $product->Quantity - $item->Quantity;
                             $product->AverageCost = ($product->AverageCost * $product->Quantity - $item->CurrentCost * $item->Quantity) / $totalAfter;
                             $product->Quantity -= $item->Quantity;
                             $product->save();
                             //Delete breakdown.
                             $item->delete();
                         }
                         // Delete transaction, bill, and billpayment.
                         $response['message'] = 'Transaccion eliminada! Al ser el unico pago de una factura de contado se ha eliminado tambien la factura del Proveedor y retirado los productos del Inventario.';
                         $providerBill->delete();
                         $providerBillPayment->delete();
                         $transaction->delete();
                     }
                     // Return what we have.
                     $response['state'] = 'Success';
                 } else {
                     // No special action needed just delete it.
                     $transaction->delete();
                     $response['message'] = 'Transaccion eliminada!';
                     $response['state'] = 'Success';
                 }
                 return response()->json($response);
             }
         }
     }
 }