<?php

class MortgagePaymentsController extends \BaseController {

    private function inputDate($date)
    {
        return Carbon\Carbon::createFromFormat("d/m/Y", $date);
    }

    public function formPaidInterest($id)
    {
        $payment = MortgagePayment::find($id);
        return View::make("mortgages.print.form_payment", [
            'payment' => $payment
        ]);
    }

	public function formPayment($id)
    {
        $payment = MortgagePayment::find($id);
        $startDate = new Carbon\Carbon($payment->start_date);
        $now = Carbon\Carbon::now();
        $days = $startDate->diffInDays($now);
        $mortgage = Mortgage::find($payment->mortgage_id);
        $totalPayment = $payment->amount;
        if ($days < 15) {
            $totalPayment = $mortgage->totalL15Payment();
        } else {
            // Payment all and interest
            $totalPayment = $mortgage->getTotalPayment();
        }
        return View::make("mortgages.inc.form_payment", [
            'payment' => $payment,
            'total_payment' => $totalPayment
        ]);
    }
    public function paidInterest()
    {
        $data = Input::all();
        $rules = [
            'receipt_id' => 'required|unique:receipt_incomes',
            'payment_name' => 'required',
            'payment_amount'   =>  'required',
            'payment_date' => "required|regex:/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",
        ];

        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  $validator->getMessageBag()->toArray()
            ], 400);
        }
        DB::beginTransaction();
        try {
            $paymentDate = $this->inputDate($data['payment_date']);
            $receipt = new ReceiptIncome;
            $receipt->receipt_id = $data['receipt_id'];
            $receipt->payment_name = $data['payment_name'];
            $receipt->total_amount = $data['payment_amount'];
            $receipt->recieve_amount = $data['payment_amount'];
            $receipt->user_id = Auth::user()->id;
            $receipt->save();
            $paymentId = Input::get("payment_id");
            $payment = MortgagePayment::find($paymentId);
            $payment->fee_date = $paymentDate;
            $payment->is_paid_interest = true;
            $payment->is_paid = true;
            $payment->note = Input::get("note");
            $payment->receipt_id = $receipt->id;
            $nextEndDate = new \Carbon\Carbon($payment->payment_date);
            $eDate = $nextEndDate->addMonth();
            $mortgagePayment = MortgagePayment::create([
                'mortgage_id' => $payment->mortgage_id,
                'payment_date' => $eDate,
                'amount' => $payment->amount,
                'principal' => $payment->principal,
                'interest'  => $payment->interest,
                'fee_date' => null
            ]);
            $income = Profit::create([
                'amount' => $data['payment_amount'],
                'type' => 'income',
                'user_id' => Auth::user()->id,
                'description' => "ប្រាក់ចំណូលពីការបង់ការប្រាក់បញ្ចាំ",
                'receipt_id' => $receipt->id,
                'created_at' => $paymentDate,
                'updated_at' => $paymentDate
            ]);
            $mortgage = Mortgage::find($payment->mortgage_id);
            $mortgage->status = "progressing";
            $mortgage->save();
            $payment->save();
            DB::commit();
            return ['error' => false, 'message' => trans("messages.success-to-create")];
        } catch(Exception $e) {
            DB::rollback();
            return ['error' => true, 'message' => trans("messages.fail-to-create"), 'errors' => $e->getMessage()];
        }
    }

    /**
     * Total Payment
     */
    public function totalPayment()
    {
        $data = Input::all();
        $rules = [
            'receipt_id' => 'required|unique:receipt_incomes',
            'payment_name' => 'required',
            'payment_date' => "required|regex:/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",
            'payment_amount'   =>  'required'
        ];

        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success'   =>  false,
                'errors'    =>  $validator->getMessageBag()->toArray()
            ], 400);
        }
        DB::beginTransaction();
        try {
            $paymentDate = $this->inputDate($data['payment_date']);
            $totalPayment = $data['payment_amount'];
            $receipt = new ReceiptIncome;
            $receipt->receipt_id = $data['receipt_id'];
            $receipt->payment_name = $data['payment_name'];
            $receipt->total_amount = $totalPayment;
            $receipt->recieve_amount = $totalPayment;
            $receipt->user_id = Auth::user()->id;
            $receipt->save();
            $paymentId = Input::get("payment_id");
            $payment = MortgagePayment::find($paymentId);
            $payment->fee_date = $paymentDate;
            $payment->is_paid = true;
            $payment->receipt_id = $receipt->id;
            $payment->note = $data['note'];
            $mortgage = Mortgage::find($payment->mortgage_id);
            $mortgage->status = "completed";
            $mortgage->paid_off_date = Carbon\Carbon::now();
            $mortgage->total_payment = $totalPayment;
            $income = Profit::create([
                'amount' => $data['payment_amount'],
                'type' => 'income',
                'user_id' => Auth::user()->id,
                'description' => "ប្រាក់ចំណូលពីការបង់ប្រាក់បញ្ចាំទាំងដើមទាំងការ",
                'receipt_id' => $receipt->id,
                'created_at' => $paymentDate,
                'updated_at' => $paymentDate
            ]);
            $p = new Profit();
            $p->amount = $mortgage->getPrice();
            $p->type = "principal";
            $p->user_id = Auth::user()->id;
            $p->description = "ប្រាក់ដើមទទួលបានពីការបង់បង់បញ្ចាំ";
            $p->mortgage_id = $mortgage->id;
            $p->save();
            $mortgage->save();
            $payment->save();
            DB::commit();
            return ['error' => false, 'message' => trans("messages.success-to-create")];
        } catch(Exception $e) {
            DB::rollback();
            return ['error' => true, 'message' => trans("messages.fail-to-create"), 'errors' => $e->getMessage()];
        }
    }

    public function paymentHistory($id)
    {
        $receipt = ReceiptIncome::join('users', 'users.id', '=', 'receipt_incomes.user_id')
            ->join('mortgage_payments as payments', 'payments.receipt_id', '=', 'receipt_incomes.id')
            ->select('users.first_name', 'users.last_name', 'receipt_incomes.*', 'payments.note')
            ->where('payments.id', $id)->first();
        return View::make('mortgages.inc.table_payment_history', ['receipt' => $receipt]);
    }

    public function noReturn($id)
    {
        $payment = MortgagePayment::find($id);
        $payment->fee_date = \Carbon\Carbon::now();
        $payment->save();
        $mortgage = Mortgage::find($payment->mortgage_id);
        $mortgage->paid_off_date = \Carbon\Carbon::now();
        $mortgage->status = "completed";
        $mortgage->is_expired = true;
        if ($mortgage->save()) return ['error' => false, 'message' => trans('messages.success-to-create')];
        return ['error' => true, 'message' => "Error Confirm Product"];
    }

    public function beforePayments()
    {
        $payments = mort_before_payments()->get();
        return View::make("mortgages.before_payments", [
            'payments' => $payments
        ]);
    }

    public function todayPayments()
    {
        $payments = mort_today_payments()->get();
        return View::make("mortgages.today_payments", [
           'payments' => $payments
        ]);
    }

    public function latePayments()
    {
        $payments = mort_late_payments()->get();
        return View::make("mortgages.late_payments", [
            'payments' => $payments
        ]);

    }
}