<?php

class MortgagesController extends \BaseController
{
    /**
     * Path Upload Image
     * @var string
     */
    private $path = 'uploads/mortgages/';

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

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $mortgages = Mortgage::orderBy('start_date', 'desc')->orderBy('id', 'desc');
        $name = Input::get('name');
        $pattern = '%' . $name . '%';
        if (!empty($name)) {
            $mortgages->filterCustomer($pattern);
        }
        if (!empty(Input::get('invoice_id'))) {
            $mortgages->where('id', Input::get('invoice_id'));
        }
        if (!empty(Input::get('status')) && Input::get('status') != 'all') {
            if (Input::get('status') == 'is_expired') {
                $mortgages->where('is_expired', 1);
            } else {
                $mortgages->where('status', Input::get('status'));
            }
        }
        if (!empty(Input::get('start_date')) && !empty(Input::get('end_date'))) {
            $start = new \Carbon\Carbon(Input::get('start_date'));
            $end = new \Carbon\Carbon(Input::get('end_date'));
            $end->addHours(23)->addMinutes(59)->addSeconds(59);

            $mortgages->where(function ($query) use ($start, $end) {
                $query->whereBetween('start_date', [$start, $end])
                    ->orWhereBetween('created_ate', [$start, $end]);
            });
        }
        if (!empty(Input::get('paginate'))) {
            $mortgages = Input::get('paginate') == 'all' ? $mortgages->get() : $mortgages->paginate(Input::get('paginate'));
        } else {
            $mortgages = $mortgages->paginate(10);
        }
        return View::make('mortgages.index', [
            'mortgages' => $mortgages
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $mortgage = new Mortgage();
        return View::make('mortgages.form', [
            'mortgage' => $mortgage
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $data = Input::except(['_token', 'submit']);
        $validator = Validator::make(Input::all(), Mortgage::$rules);
        if ($validator->fails()) {
            return Redirect::back()->withMessage(trans('messages.fail-to-create'))
                ->withInput()->withErrors($validator->messages())
                ->with('messageType', 'danger');
        }
        DB::beginTransaction();
        try {
            $data['start_date'] = $this->inputDate($data['start_date']);
            $data['end_date'] = $this->inputDate($data['end_date']);

            // Create New Mortgage
            $data['user_id'] = Auth::user()->id;
            $data['files'] = [];
            if (Input::hasFile('photo')) {
                foreach (Input::file('photo') as $value) {
                    $file = $value;
                    $filename = $file->getClientOriginalName();
                    $filename = strtolower(str_replace(' ', '_', $filename));
                    $file->move($this->path, $filename);
                    $image = Image::make(sprintf($this->path . '%s', $filename))->resize(500, null, function ($constraint) {
                        $constraint->aspectRatio();
                        $constraint->upsize();
                    })->save();
                    $data['files'][] = $this->path . $filename;
                }
                $data['photo'] = implode(',', $data['files']);
            } else {
                $data['photo'] = $this->path . 'none.jpg';
            }
            $mortgage = Mortgage::create($data);

            // Create New Payment for store and alert
            $mortgagePayment = MortgagePayment::create([
                'mortgage_id' => $mortgage->id,
                'start_date' => $mortgage->start_date,
                'payment_date' => $mortgage->end_date,
                'amount' => $mortgage->getTotalPayment(),
                'principal' => $mortgage->getPrice(),
                'interest' => $mortgage->getTotalInterest()
            ]);
            $expense = Profit::create([
               'amount' => $data['price_out'],
               'type' => 'expense',
               'user_id' => Auth::user()->id,
               'description' => 'ប្រាក់ចំណាយលើបញ្ចាំ',
                'mortgage_id' => $mortgage->id,
                'created_at' => $mortgage->start_date,
                'updated_at' => $mortgage->end_date
            ]);
            DB::commit();
            return Redirect::route('mortgages.show', $mortgage->id)
                ->withMessage(trans('messages.success-to-create'))
                ->with('messageType', 'success');
        } catch (Exception $e) {
            DB::rollback();
            return ['error' => $e->getMessage()];
            return Redirect::back()->withInput()
                ->withMessage(trans('messages.fail-to-create'))
                ->with('messageType', 'danger');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $mortgage = Mortgage::find($id);
        $files = empty($mortgage->photo) ? [] : explode(',', $mortgage->photo);
        $payments = MortgagePayment::where('mortgage_id', $id)->get();
        return View::make('mortgages.show', [
            'mortgage' => $mortgage,
            'payments' => $payments,
            'files' => $files
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $mortgage = Mortgage::find($id);
        return View::make('mortgages.form', [
           'mortgage' => $mortgage
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        $data = Input::all();
        $validator = Validator::make(Input::all(), Mortgage::$rules);
        if ($validator->fails()) {
            return Redirect::back()->withMessage(trans('messages.fail-to-create'))
                ->withInput()->withErrors($validator->messages())
                ->with('messageType', 'danger');
        }
        DB::beginTransaction();
        try {
            $data['start_date'] = $this->inputDate($data['start_date']);
            $data['end_date'] = $this->inputDate($data['end_date']);

            $mortgage = Mortgage::find($id);
            // Create New Mortgage
            $data['user_id'] = Auth::user()->id;
            $data['files'] = [];
            if (Input::hasFile('photo')) {
                foreach (Input::file('photo') as $value) {
                    $file = $value;
                    $filename = $file->getClientOriginalName();
                    $filename = uniqid() . '_' . strtolower(str_replace(' ', '_', $filename));
                    $file->move($this->path, $filename);
                    $image = Image::make(sprintf($this->path . '%s', $filename))->resize(500, null, function ($constraint) {
                        $constraint->aspectRatio();
                        $constraint->upsize();
                    })->save();
                    $data['files'][] = $this->path . $filename;
                }
            } else {
                $data['photo'] = $mortgage->photo;
            }
            $data['photo'] = implode(',', $data['files']);
            $mortgage->update($data);

            // Create New Payment for store and alert
            $mortgagePayment = MortgagePayment::where('mortgage_id', $id)->first();
            $mortgagePayment->start_date = $mortgage->start_date;
            $mortgagePayment->payment_date = $mortgage->end_date;
            $mortgagePayment->amount = $mortgage->getTotalPayment();
            $mortgagePayment->principal = $mortgage->getPrice();
            $mortgagePayment->interest = $mortgage->getTotalInterest();
            $mortgagePayment->save();
            $expense = Profit::where('type', 'expense')->where('mortgage_id', $id)->first();
            $expense->amount = $mortgage->getPrice();
            $expense->created_at = $mortgage->start_date;
            $expense->updated_at = $mortgage->end_date;
            $expense->save();
            DB::commit();
            return Redirect::back()
                ->withMessage(trans('messages.success-to-update'))
                ->with('messageType', 'success');
        } catch (Exception $e) {
            DB::rollback();
            return ['error' => $e->getMessage()];
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $mortgage = Mortgage::find($id);
            $payments = MortgagePayment::where('mortgage_id', $id)->get();
            $expense = Profit::whereIn('type', ['expense', 'principal'])->where('mortgage_id', $id)->delete();
            if (count($payments) > 0) {
                foreach ($payments as $payment) {
                    if ($payment->receipt_id) {
                        $receipt = ReceiptIncome::find($payment->receipt_id);
                        $receipt->delete();
                    }
                    $p = MortgagePayment::find($payment->id);
                    $p->delete();
                }
            }
            $files = explode(',', $mortgage->photo);
            foreach ($files as $f) {
                if ($f != "uploads/mortgages/none.jpg") {
                    File::delete($f);
                }
            }
            if ($mortgage->delete()) {
                DB::commit();
                return Redirect::back()
                    ->withMessage(trans('messages.success-to-create'))
                    ->with('messageType', 'success');
            }
        } catch (Exception $e) {
            DB::rollback();
            return ['error' => $e->getMessage()];
            return Redirect::back()
                ->withMessage(trans('messages.fail-to-create'))
                ->with('messageType', 'danger');
        }
    }

    public function printS($id)
    {
        $mortgage = Mortgage::join('users', 'users.id', '=', 'mortgages.user_id')
                        ->select('users.first_name', 'users.last_name', 'users.username', 'mortgages.*')->find($id);
        $payments = MortgagePayment::where('mortgage_id', $id)->get();
        return View::make('mortgages.print.a4', [
            'mortgage' => $mortgage,
            'payments' => $payments
        ]);
    }

    public function formAddMore($id)
    {
        $mortgage = Mortgage::find($id);
        $price = $mortgage->price;
        $priceOut = $mortgage->price_out;
        $newPrice = $price > $priceOut ? $price - $priceOut : null;
        return View::make('mortgages.inc.form_add_more', [
            'newPrice' => $newPrice,
            'oldInterest' => $mortgage->getTotalInterest(),
            'id' => $id
        ]);
    }

    public function postAddMore($id)
    {
        $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}$/",
            'amount' => 'required',
            'old_interest' => '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']);
            $mortgage = Mortgage::find($id);
            $receipt = new ReceiptIncome;
            $receipt->receipt_id = $data['receipt_id'];
            $receipt->payment_name = $data['payment_name'];
            $receipt->total_amount = $data['old_interest'];
            $receipt->recieve_amount = $data['old_interest'];
            $receipt->user_id = Auth::user()->id;
            $receipt->save();
            $payment = MortgagePayment::where('mortgage_id', $id)->where('is_paid', false)->first();
            $income = Profit::create([
                'amount' => $data['old_interest'],
                'type' => 'income',
                'user_id' => Auth::user()->id,
                'description' => 'ប្រាក់ចំណូលពីការបង់ការប្រាក់បញ្ចាំ',
                'receipt_id' => $receipt->id,
                'created_at' => $paymentDate,
                'updated_at' => $paymentDate
            ]);
            $payment->fee_date = $paymentDate;
            $payment->is_paid_interest = true;
            $payment->is_paid = true;
            $payment->note = $data['note'];
            $payment->receipt_id = $receipt->id;
            $nextEndDate = new \Carbon\Carbon($payment->payment_date);
            $eDate = $nextEndDate->addMonth();
            $payment->save();
            $mortgage->price_out += $data['amount'];
            $mortgage->status = 'progressing';
            $mortgage->save();
            $mortgagePayment = MortgagePayment::create([
                'mortgage_id' => $id,
                'payment_date' => $eDate,
                'amount' => $mortgage->getTotalPayment(),
                'principal' => $mortgage->getPrice(),
                'interest' => $mortgage->getTotalInterest(),
                'fee_date' => null
            ]);
            $expense = Profit::create([
                'amount' => $data['amount'],
                'type' => 'expense',
                'user_id' => Auth::user()->id,
                'description' => 'ប្រាក់ចំណាយលើបញ្ចាំ យកប្រាក់បន្ថែម',
                'mortgage_id' => $mortgage->id,
                'created_at' => $paymentDate,
                'updated_at' => $paymentDate
            ]);
            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 upload($id)
    {
        try {
            $mortgage = Mortgage::find($id);
            $files = explode(',', $mortgage->photo);
            foreach ($files as $f) {
                if ($f != "uploads/mortgages/none.jpg") {
                    File::delete($f);
                }
            }
            $data['files'] = [];
            $files = Input::file('photo');
            $file = "";
            if (Input::hasFile('photo')) {
                foreach (Input::file('photo') as $value) {
                    $file = $value;
                    $filename = $file->getClientOriginalName();
                    $filename = strtolower(str_replace(' ', '_', $filename));
                    $file->move($this->path, $filename);
                    $image = Image::make(sprintf($this->path . '%s', $filename))->resize(500, null, function ($constraint) {
                        $constraint->aspectRatio();
                        $constraint->upsize();
                    })->save();
                    $data['files'][] = $this->path . $filename;
                }
            } else {
                $file = $mortgage->photo;
            }

            $file = implode(',', $data['files']);
            $mortgage->photo = $file;
            if ($mortgage->save()) return Redirect::back()->withMessage(trans("messages.upload_success"))->with('messageType', 'success');
        } catch (Exception $e) {
            return Redirect::back()->withMessage(trans("messages.upload_error"))->with('messageType', 'danger');
        }

    }
}
