<?php

class DebtController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /debt
	 *
	 * @return Response
	 */
	public function index()
	{
		return View::make('debts.index');
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /debt/create
	 *
	 * @return Response
	 */
	public function create()
	{
		$debt = new SupplierInvoice;
		$suppliers = Supplier::lists('company_name', 'id');
		$suppliers['none'] = "None";
		return View::make('debts.form', [
			'debt' => $debt,
			'suppliers' => $suppliers
		]);
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /debt
	 *
	 * @return Response
	 */
	public function store()
	{
        // Assign form request values
        // And Check in deposit of invoice or not
        $pay = (float) Input::get('pay');
        $total = (float) Input::get('total');
        if ($pay >= $total) return Redirect::back()->withInput()
                                   ->with("messageType", 'warning')
                                   ->withMessage('debts.msg.incorrect');
        // Min 25% and Max 75% of total price
        $min_payment = (float) round((25/100) * $total);
        $max_payment = (float) round((75/100) * $total);	
        $invoice = new SupplierInvoice;
        if ($pay > 0 && $pay < $min_payment) {
            return Redirect::back()->withInput()
                   ->with("messageType", 'warning')
                   ->withMessage(trans('debts.min_amount', ['attribute' => money($min_payment)]));
        } elseif ($pay > $max_payment) {
            return Redirect::back()->withInput()
                   ->with("messageType", 'warning')
                   ->withMessage(trans('debts.max_amount', ['attribute' => money($min_payment)]));
        } else {
            $invoice->status = "unpaid";
        }

        $invoice->supplier_id = Input::get('supplier_id') == "none" ? null : Input::get('supplier_id');
        $invoice->total =  $total;
        $invoice->invoice_no = Input::get('invoice_no');
        $invoice->pay     = $pay;
        $invoice->comment = Input::get('comment');
        $invoice->is_debt = true;

        if ($pay >= $min_payment) {
            $invoice->status = "deposit";
            $invoice->payable = ($total - $pay);

        } else {
            $invoice->status = "unpaid";
            $invoice->payable = $total;
        }

        if ($invoice->save()) {
            if ($pay >= $min_payment) {
                Profit::create([
                    'amount' => $pay,
                    'type'   => "expense",
                    'user_id' => Auth::user()->id,
                    'debt_id' => $invoice->id
                ]);
            }
            return Redirect::route('debts.index')->with('messageType', 'success')
            								->withMessage('messages.success-to-create');
        }
        return Redirect::back()->withInput()->with('messageType', 'success')
            								->withMessage('messages.fail-to-create');
	}

	/**
	 * Display the specified resource.
	 * GET /debt/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$invoice = SupplierInvoice::leftJoin('suppliers', 'suppliers.id', '=', 'supplier_invoices.supplier_id')
														->select([
						            				'suppliers.company_name',
						            				'supplier_invoices.id',
						            				'supplier_invoices.invoice_no',
						            				'supplier_invoices.total',
						            				'supplier_invoices.pay',
						            				'supplier_invoices.payable',
						            				'supplier_invoices.status',
						            				'supplier_invoices.created_at'
            								])->where('supplier_invoices.is_debt', true)->where('supplier_invoices.id', $id)->first();
		if (empty($invoice)) return Redirect::route('debts.index');
		$payables = Payable::where('sup_invoice_id', $id)->get();
		return View::make('debts.show',['invoice' => $invoice, 'payables' => $payables]);
	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /debt/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$debt = SupplierInvoice::find($id);
		if (empty($debt)) return Redirect::route('debts.index');
		$suppliers = Supplier::lists('company_name', 'id');
		$suppliers['none'] = "None";
		return View::make('debts.form', [
			'debt' => $debt,
			'suppliers' => $suppliers
		]);
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /debt/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		// Assign form request values
     // And Check in deposit of invoice or not
     $pay = (float) Input::get('pay');
     $total = (float) Input::get('total');
     if ($pay >= $total) return Redirect::back()->withInput()
                                ->with("messageType", 'warning')
                                ->withMessage('debts.msg.incorrect');
     // Min 25% and Max 75% of total price
     $min_payment = (float) round((25/100) * $total);
     $max_payment = (float) round((75/100) * $total);	
     $invoice = SupplierInvoice::find($id);
     $oldProfit = Profit::where('debt_id', $invoice->id)->first();
     if ($pay > 0 && $pay < $min_payment) {
         return Redirect::back()->withInput()
                ->with("messageType", 'warning')
                ->withMessage(trans('debts.min_amount', ['attribute' => money($min_payment)]));
     } elseif ($pay > $max_payment) {
         return Redirect::back()->withInput()
                ->with("messageType", 'warning')
                ->withMessage(trans('debts.max_amount', ['attribute' => money($min_payment)]));
     } else {
         $invoice->status = "unpaid";
     }

     $invoice->supplier_id = Input::get('supplier_id') == "none" ? null : Input::get('supplier_id');
     $invoice->total =  $total;
     $invoice->invoice_no = Input::get('invoice_no');
     $invoice->pay     = $pay;
     $invoice->comment = Input::get('comment');
     $invoice->is_debt = true;

     if ($pay >= $min_payment) {
         $invoice->status = "deposit";
         $invoice->payable = ($total - $pay);
         if (empty($oldProfit)) {
         	 Profit::create([
                 'amount' => $pay,
                 'type'   => "expense",
                 'user_id' => Auth::user()->id,
                 'debt_id' => $invoice->id
             ]);
         } else {
         	$oldProfit->amount = $pay;
          $oldProfit->save();
         }

     } else {
         $invoice->status = "unpaid";
         $invoice->payable = $total;
         if (!empty($oldProfit)) {
            $oldProfit->delete();
         }
     }

     if ($invoice->save()) {
         return Redirect::route('debts.index')->with('messageType', 'success')
         								->withMessage('messages.success-to-update');
     }
     return Redirect::back()->withInput()->with('messageType', 'success')
         								->withMessage('messages.fail-to-update');
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /debt/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$debt = SupplierInvoice::find($id);
		if (empty($debt)) return Redirect::back();
		$expense = Profit::where('type', 'expense')->where('debt_id', $id)->first();
		$payables = Payable::where('sup_invoice_id', $id)->get();
		// Not allow to delete debt has been return 
		if (count($payables) > 0) return Redirect::back()->withMessage('messages.not_allow_to_delete')->with('messageType', "warning");
		// Delete debt with profit related 
		if (!empty($expense)) {
			$expense->delete();
			$debt->delete();
			return Redirect::back()->withInput()->with('message','messages.success-to-delete')->with('messageType','success');
		}
			return Redirect::back()->withInput()->with('message','messages.fail-to-delete')->with('messageType','danger');
	}

	public function getDebtList() 
	{
		$debts = DB::table('supplier_invoices as si')
								->leftJoin('suppliers as s', 's.id', '=', 'si.supplier_id')
            		->select([
            				's.company_name',
            				'si.invoice_no',
            				'si.id',
            				'si.total',
            				'si.pay',
            				'si.status',
            				'si.created_at'
            			]);
   	 return Datatables::of($debts)
   	 				->editColumn('company_name', '{{$company_name ? $company_name : "None" }}')
   	 				->editColumn('total', '{{money($total)}}')
   	 				->editColumn('pay', '{{money($pay)}}')
   	 				->editColumn('status', '{{get_debt_status($status)}}')
            ->editColumn('action',
            	'
            	@if (user_can("show_debt"))
            	<a href="{{ route("debts.show", $id) }}" class="btn btn-default btn-xs"><i class="fa fa-th"></i> {{ trans("dashboard.others.show") }}</a>
            	@endif
            	@if (user_can("edit_debt"))
            	<a href="{{ route("debts.edit", $id)}}" class="btn btn-info btn-xs"><i class="fa fa-edit"></i> {{ trans("dashboard.crud.edit") }}</a>
            	@endif
            	@if (user_can("delet_debt"))
            	<a href="#" class="btn btn-xs btn-danger" data-toggle="modal" data-target="#myModal{{$id}}"><i class="fa fa-trash"></i> {{Trans("dashboard.crud.remove")}}</a>
          		<div class="modal fade" id="myModal{{$id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
							  <div class="modal-dialog modal-primary" role="document">
							    <div class="modal-content">
							      <div class="modal-header">
							        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
							        <h4 class="modal-title" id="myModalLabel">{{Trans("dashboard.crud.remove")}}</h4>
							      </div>
							      <div class="modal-body">
							        {{Trans("messages.delete-confirm", array("attribute" => $company_name ? $company_name : money($total)))}}?
							      </div>
							      <div class="modal-footer">
							        <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">{{Trans("dashboard.others.no")}}</button>
							        {{ Form::open(array("action" => array("debts.destroy",$id),"method"=>"DELETE"))}}
							        {{ Form::hidden("_method", "DELETE") }}
							        <button type="submit" class="btn btn-outline">{{Trans("dashboard.others.yes")}}</button>
							        {{ Form::close() }}
							      </div>
							    </div>
							  </div>
							</div>
							@endif
							'
            )
            ->make(true);
	}
	public function postDebtReturn()
	{
	    $invoiceId = (int) Input::get("invoice_id");
	    $payment  = (float) Input::get('payable');
	    $note     = Input::get('note');
	    $invoice = SupplierInvoice::find($invoiceId);

	    // Invoice doesn't exist redirect back
	    if (empty($invoice)) return Redirect::back();
	    $min_payment = (float) round((get_min_return()/100) * $invoice->payable);
	    if ($payment < $min_payment) return Redirect::back()->withInput()
	                                  ->withMessage(trans("invoices.min_payment", ['attribute' => money($min_payment)]))
	                                  ->with("messageType", 'danger');
		DB::beginTransaction();
		try {
			$payable = new Payable;
			$payable->amount = $payment;
			$payable->user_id = Auth::user()->id;
			$payable->sup_invoice_id = $invoice->id;
			$payable->note      = $note;
			// create new profits
			$income = new Profit;
			$income->user_id = Auth::user()->id;
			$income->type = 'expense';
			$income->rate = $invoice->rate;
			$income->debt_id = $invoice->id;
	      if ($payment >= $invoice->payable) {
	        	$payable->deposit = $invoice->payable;
	        	$payable->changed = $payment - $invoice->payable;
	        	$income->amount = $invoice->payable;
	        	$invoice->status = "paid";
	        	$invoice->payable = 0;
	      } else {
	        	$payable->deposit = $invoice->payable;
	        	$invoice->status = "deposit";
	        	$income->amount = $payment;
	        	$invoice->payable -= $payment;
	      }
	      if ($invoice->save() && $payable->save() && $income->save()) {
	        DB::commit();
	        return Redirect::back()->withMessage(trans('invoices.payment_success'))
	                       ->with("messageType", 'success');
	      } else {
	        return Redirect::back()->withMessage(trans('invoices.payment_fail'))
	                       ->with("messageType", 'danger');
	        DB::rollback();
	      }
		} catch (Exception $e) {
			DB::rollback();
			return dd($e->getMessage());
		}
	}
}