<?php

class PaymentsController extends \BaseController
{
    /**
     * Display a listing of the resource.
     * GET /payments
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     * GET /payments/create
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     * POST /payments
     *
     * @return Response
     */
    public function store()
    {
        //
    }

    /**
     * Display the specified resource.
     * GET /payments/{id}
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     * GET /payments/{id}/edit
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $payment = Payment::paymentReceipt($id);
        $paymentDate = new Carbon\Carbon($payment->fee_date);
        $pDate = $paymentDate->format('d/m/Y');
        return View::make('installments.inc.form_payment', [
            'payment' => $payment,
            'type' => 1,
            'currentDate' => $pDate
        ]);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function editPaymentAll($id)
    {
        $payment = Payment::paymentReceipt($id);
        $currentPayments = $payment->amount;
        $installment = Installment::find($payment->installment_id);
        $termPaid = Payment::paidTime($payment->installment_id);
        $remainPrincipal = $installment->getRemainPrinciple($termPaid);
        $interest = $payment->interest;
        $minAmount = $remainPrincipal + $interest + $payment->principal;
        $totalInterest = $installment->getRate3Moths($termPaid) + $interest;
        $totalPayment = ($minAmount + $totalInterest + $interest);
        $paymentDate = $payment->p_date ? new Carbon\Carbon($payment->p_date) : new Carbon\Carbon($payment->fee_date);
        $pDate = $paymentDate->format('d/m/Y');
        //return ['total' => $totalPayment, 'min' => $minAmount];
        return View::make('installments.inc.form_payment_all', [
            'payment' => $payment,
            'totalPayment' => $totalPayment,
            'minAmount' => $minAmount,
            'remainPrincipal' => $remainPrincipal,
            'type' => 1,
            'currentDate' => $pDate
        ]);
    }

    /**
     * Update the specified resource in storage.
     * PUT /payments/{id}
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        // Get User Input and Validation
        $data = Input::all();
        $payment = Payment::find($id);
        $rules = [
           'receipt_id' => 'required|unique:receipt_incomes,receipt_id,' . $payment->receipt_id,
           'payment_name' => 'required',
           'recieve_amount' => 'required'
        ];

        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()
            ], 400);
        }
        if ($data['recieve_amount'] < $data['payment_amount']) {
            return Response::json([
                'success' => false,
                'errors' => ['recieve_amount' => trans('installments.total_payment_amount', ['attribute' => money($data['payment_amount'])])]
            ], 400);
        }

        // Start Database Transaction
        DB::beginTransaction();
        try {
            $paymentDate = Carbon\Carbon::createFromFormat('d/m/Y', $data['payment_date']);
            $data['payment_date'] = $paymentDate;
            $data['p_amount'] = $data['payment_amount'];
            $receiptId = ReceiptIncome::updateReceipt($data, $payment->receipt_id);

            // find and update existing payment
            $payment->fee_date = $paymentDate;
            $payment->is_paid = true;
            $payment->late_day = $payment->lateDay();
            $payment->fee_late = $data['late_amount'];

            $data['desc'] = 'ប្រាក់បង់ប្រចាំខែ ប័ណ្ណចំណូលលេខ' . $data['receipt_id'];
            Profit::updateIncome($data, $receiptId);

            $installment = Installment::find($payment->installment_id);
            $paidTime = Payment::where('is_paid', true)->where('installment_id', $payment->installment_id)->count();
            if ($paidTime == $installment->duration) {
                $installment->paid_off_date = Carbon\Carbon::now();
                $installment->status = 'completed';
            } else {
                $installment->status = 'proccessing';
            }
            if ($payment->save() && $installment->save()) {
                DB::commit();
                return ['error' => false, 'message' => trans('installments.msg.payment_success')];
            }
        } catch (Exception $e) {
            DB::rollback();
            return [
                'error' => true,
                'message' => 'installments.msg.fail_payment',
                'error_mesage' => $e->getMessage()
            ];
        }
    }

    public function updateReturnAll($id)
    {
        $data = Input::all();
        $payment = Payment::find($id);
        $rules = [
            'receipt_id' => 'required|unique:receipt_incomes,receipt_id,' . $payment->receipt_id,
            'payment_name' => 'required',
            'recieve_amount' => 'required',
            'payment_date' => 'required'
        ];

        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return Response::json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()
            ], 400);
        }
        if ($data['recieve_amount'] < $data['min_amount']) {
            return Response::json([
                'success' => false,
                'errors' => ['recieve_amount' => trans('installments.total_payment_amount', ['attribute' => money($data['min_amount'])])]
            ], 400);
        }
        DB::beginTransaction();
        try {
            $paymentDate = Carbon\Carbon::createFromFormat('d/m/Y', $data['payment_date']);
            // create new receipt income for new payment
            $paymentAmount = $data['recieve_amount'];
            $data['payment_date'] = $paymentDate;
            $data['p_amount'] = $paymentAmount;
            $receiptId = ReceiptIncome::updateReceipt($data, $payment->receipt_id);

            // find and update existing payment
            $payment->fee_date = $paymentDate;
            $payment->is_paid = true;
            //check late number of late day and calculate total amount of fee
            $payment->late_day = $payment->lateDay();
            $payment->fee_late = $data['late_amount'];
            $payment->is_paid_all = true;
            $payment->receipt_id = $receiptId;

            $data['desc'] = 'ប្រាក់បង់ផ្តាច់ ប័ណ្ណចំណូលលេខ' . $data['receipt_id'];
            $data['payment_amount'] = $data['recieve_amount'];
            Profit::updateIncome($data, $receiptId);

            $installment = Installment::find($payment->installment_id);
            $installment->status = 'completed';
            $installment->paid_off_date = $paymentDate;
            $installment->paid_off_amount = $paymentAmount;
            if ($payment->save() && $installment->save()) {
                DB::commit();
                return [
                    'error' => false,
                    'message' => trans('installments.msg.payment_success'),
                    'title' => trans('installments.msg.title')
                ];
            }
        } catch (Exception $e) {
            DB::rollback();
            return [
                'error' => true,
                'message' => trans('installments.msg.fail_payment'),
                'title' => trans('installments.msg.title'),
                'error_msg' => $e->getMessage()
            ];
        }
    }

    /**
     * Remove the specified resource from storage.
     * DELETE /payments/{id}
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $payment = Payment::find($id);
            $receiptIncome = ReceiptIncome::find($payment->receipt_id);
            $income = Profit::where('type', 'income')->where('receipt_id', $receiptIncome->id)->first();
            $principal = Profit::where('type', 'principal')->where('receipt_id', $receiptIncome->id)->first();
            if ($payment->is_paid_all) {
                $installment = Installment::find($payment->installment_id);
                $installment->status = 'proccessing';
                $installment->paid_off_date = null;
                $installment->paid_off_amount = null;
                $installment->save();
            }
            if ($receiptIncome->delete() && $income->delete()) {
                if ($principal) {
                    $principal->delete();
                }
                $payment->is_paid = 0;
                $payment->is_paid_all = 0;
                $payment->fee_date = null;
                $payment->late_day = null;
                $payment->fee_late = null;
                $payment->receipt_id = null;
                $payment->save();
                DB::commit();
                return ['error' => false, 'message' => 'Successfully to delete payment'];
            }
        } catch (Exception $e) {
            DB::rollback();
            return ['error' => true, 'message' => trans('messages.fail_to_delete'), 'error_message' => $e->getMessage()];
        }
    }

    /**
     * Display payment history
     */
    public function paymentHistory($id)
    {
        $receipt = ReceiptIncome::join('users', 'users.id', '=', 'receipt_incomes.user_id')
                              ->join('payments', 'payments.receipt_id', '=', 'receipt_incomes.id')
                              ->select(
                                'users.first_name',
                                'users.last_name',
                                'receipt_incomes.*',
                                'payments.late_day',
                                'payments.fee_late'
                                )
                              ->where('payments.id', $id)->first();
        return View::make('installments.inc.table_payment_history', ['receipt' => $receipt]);
    }

    /**
     * Get Payment By Installment today
     *
     * @return view
     */
    public function paymentToday()
    {
        $payments = Payment::installmentCustomer()
                        ->installmentNotComplete()
                        ->paymentToday()->selectFields()->get();
        return View::make('installments.payments_today', [
            'payments' => $payments
        ]);
    }

    /**
     * Get before payment
     */
    public function beforePayment()
    {
        $beforePayments = Payment::beforePayment();
        return View::make('installments.before_payment')
                    ->with('latePayments', $beforePayments);
    }

    /**
     * Get late payments
     *
     * @return view
     */
    public function getLatePayments()
    {
        $latePayments = Payment::latePayment();
        return View::make('installments.late')->with('latePayments', $latePayments);
    }
}
