<?php

class EMILoanController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /emiloan
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /emiloan/create
	 *
	 * @return Response
	 */
	public function create()
	{
		$installment = new Installment;
        return View::make("loan_customers.inc.emi_form", [
            'installment'   => $installment
        ]);
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /emiloan
	 *
	 * @return Response
	 */
	public function store()
	{
		$data = Input::except(['_token', 'submit']);
        $rules = [
           'type_of_product' => 'required',
           'product_name' => 'required',
           'model' => 'required',
           'imie' => 'required|unique:installments,imie',
           'rate' =>  "required",
           'total_price'  =>  "required",
           'duration'     =>  "required",
           'in_date'    =>  "required",
        ];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  $validator->getMessageBag()->toArray()
            ], 400);
        }
        if ($data['deposit'] > $data['total_price']) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  ['deposit' => trans('installments.deposit_error') ]
            ], 400);
        }
        $success = false;
        DB::beginTransaction();
        try {
            $data['user_id'] = Auth::user()->id;
            if (!empty($data['in_date'])) {
            $data['in_date']  = Carbon\Carbon::createFromFormat("d/m/Y", $data['in_date']);
            } else {
                $data['in_date'] = null;
            }
            // return ['error' => true, 'message' => $data];
            $data['loan_type'] = "emi";
            $installment = EmiInstallment::create($data);
            $profit = Profit::addExpense($installment);
            $loanAmount = $installment->getPriciple();
            $remainAmount = $loanAmount;
            $total = $installment->getTotalPayment();
            $totalPrinciple = 0.0;
            $totalRate = 0.0;
            $totalPayment = 0;
            for ($i=1; $i <= $installment->duration ; $i++) {
                $monthlyRate = $i == $installment->getDuration() ? $installment->emiPayment() - $remainAmount : round($remainAmount * $installment->getEMIRate(), 2) + 0.05;
                $amount = $i == 1 ? $installment->firstMonth() :$installment->emiPayment();
                $totalPayment += $amount;
                $debt = $total - $totalPayment;
                $principle = $amount - $monthlyRate;
                if ($i== $installment->getDuration()) {
                    $principle = $remainAmount;
                    $remainAmount = 0;
                } else {
                    $remainAmount -= $principle;
                }
                $payment = Payment::create([
                    'installment_id'   =>  $installment->id,
                    'payment_date'   =>  add_loan_months($installment->in_date, $i),
                    'amount'   => $amount,
                    'term_id' => $i,
                    'interest'	=>	$monthlyRate,
                    'principal'	=>	$principle,
                    'balance'	=>	$remainAmount,
                    'debt'      =>  $i == $installment->getDuration() ? 0 : $debt
                ]);
                if ($payment) {
                    $success = true;
                }
            }
            if ($success) {
                DB::commit();
                return [
                    'error' => false, 
                    'message' => trans('messages.success-to-create'), 
                    'title' => trans('installments.msg.title')
                ];
            }
        } catch (Exception $e) {
            $success = false;
            DB::rollback();
            return ['error' => true, 'message' => $e->getMessage()];
        }
	}

	/**
	 * Display the specified resource.
	 * GET /emiloan/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
        $installment = EmiInstallment::byId($id);
        if (empty($installment)) return Redirect::route('installments.index');
        if ($installment->loan_type == "normal") return Redirect::route("installmentss.show", $installment->id);
        $numberOfM = Payment::where('installment_id', $id)->where('is_paid', false)->count();
        $termPaid = Payment::paidTime($id);
        $payments = Payment::where('installment_id', $id)->get();
        $payOffDay = Payment::orderBy('payment_date', 'DESC')->where('installment_id', $id)->first();
        return View::make('installments.show_tab', compact('installment'))
                    ->with('termPaid', $termPaid)
                    ->withPayments($payments)
                    ->with('numbers', $numberOfM)
                    ->with('payOffDay', $payOffDay);
	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /emiloan/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$installment = Installment::find($id);
        return View::make("loan_customers.inc.emi_form", [
            'installment'   => $installment
        ]);
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /emiloan/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$data = Input::except(['_token', 'submit']);
        $installment = Installment::find($id);
        $rules = [
           'type_of_product' => 'required',
           'product_name' => 'required',
           'model' => 'required',
           'imie' => 'required|unique:installments,imie,'. $installment->id,
           'rate' =>  "required",
           'total_price'  =>  "required",
           'duration'     =>  "required",
           'in_date'  =>  "required"
        ];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  $validator->getMessageBag()->toArray()
            ], 400);
        }
        if ($data['deposit'] > $data['total_price']) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  ['deposit' => trans('installments.deposit_error') ]
            ], 400);
        }
        $success = false;
        DB::beginTransaction();
        try {
        if ($installment->total_price != $data['total_price']
            || $installment->rate != $data['rate']
            || $installment->deposit != $data['deposit']
            || $installment->duration != $data['duration']
            || $installment->in_date != $data['in_date']
        ) {
            if (!empty($data['in_date'])) {
              $data['in_date']  = Carbon\Carbon::createFromFormat("d/m/Y", $data['in_date']);
            } else {
              $data['in_date'] = null;
            }
            $payments = Payment::where('installment_id', $id)->delete();
            $installment->update($data);
            $installment = EmiInstallment::find($id);
            $profit = Profit::addExpense($installment);
            $loanAmount = $installment->getPriciple();
            $remainAmount = $loanAmount;
            $total = $installment->getTotalPayment();
            $totalPrinciple = 0.0;
            $totalRate = 0.0;
            $totalPayment = 0;
            for ($i=1; $i <= $installment->duration ; $i++) {
                $monthlyRate = $i == $installment->getDuration() ? $installment->emiPayment() - $remainAmount : round($remainAmount * $installment->getEMIRate(), 2) + 0.05;
                $amount = $i == 1 ? $installment->firstMonth() :$installment->emiPayment();
                $totalPayment += $amount;
                $debt = $total - $totalPayment;
                $principle = $amount - $monthlyRate;
                if ($i== $installment->getDuration()) {
                    $principle = $remainAmount;
                    $remainAmount = 0;
                } else {
                    $remainAmount -= $principle;
                }
                $payment = Payment::create([
                    'installment_id'   =>  $installment->id,
                    'payment_date'   =>  add_loan_months($installment->in_date, $i),
                    'amount'   => $amount,
                    'term_id' => $i,
                    'interest'  =>  $monthlyRate,
                    'principal' =>  $principle,
                    'balance'   =>  $remainAmount,
                    'debt'      => $i == $installment->getDuration() ? 0 : $debt
                ]);
                if ($payment) {
                    $success = true;
                }
            }
            if ($success) {
                DB::commit();
                return [
                    'error' => false,
                    'message' =>  trans('messages.success-to-update')
                ];
            }

        } else {
            if (!empty($data['in_date'])) {
                $data['in_date']  = Carbon\Carbon::createFromFormat("d/m/Y", $data['in_date']);
            } else {
                $data['in_date'] = null;
            }
            $updated = $installment->update($data);
            $profit = Profit::addExpense($updated);
            DB::commit();
            return [
                'error' => false,
                'message' =>  trans('messages.success-to-update')
            ];
        }

        } catch (Exception $e) {
            DB::rollback();
            return [
                'error' => true, 
                'message' => trans('messages.fail-to-update'),
                'error_msg' => $e->getMessage()
            ];
        }
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /emiloan/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
    }
    
    public function printEMILoan($id)
    {
        $installment = EmiInstallment::byId($id);
        if (empty($installment)) return Redirect::route('installments.index');
        $numberOfM = Payment::where('installment_id', $id)->where('is_paid', false)->count();
        $termPaid = Payment::paidTime($id);
        $payments = Payment::where('installment_id', $id)->get();
        $payOffDay = Payment::orderBy('payment_date', 'DESC')->where('installment_id', $id)->first();
        $firstPayDate = Payment::orderBy("payment_date", "ASC")->where("installment_id", $id)->first();
        return View::make("installments.inc.emi_print", [
            "installment"   =>  $installment,
            "payments"      =>  $payments,
            'firstPayDate'  =>  $firstPayDate,
            'payOffDay'     =>  $payOffDay
        ]);
    }

    /**
     * 
     */
    public function paidAllEMILoan($id)
    {
        $payment = Payment::find($id);
        $installment = Installment::find($payment->installment_id);
        $termPaid = Payment::paidTime($payment->installment_id);
        $totalPayment = ($installment->getRemainPrinciple($termPaid) +$installment->getRate3Moths($termPaid));
        return View::make('installments.inc.emi_form_payment_all', [
            'payment' =>  $payment, 
            'totalPayment'  => $totalPayment,
        ]);
    }

}