<?php

class SuppliersController extends \BaseController {

	/**
	 * Display a listing of suppliers
	 *
	 * @return Response
	 */
	public function index()
	{
		if(!UserRole::has('list_supplier')) return Redirect::route('dashboard');
		$suppliers = Supplier::all();
		return View::make('suppliers.index', compact('suppliers'));
	}

	/**
	 * Show the form for creating a new supplier
	 *
	 * @return Response
	 */
	public function create()
	{
		if(!UserRole::has('create_supplier')) return Redirect::route('dashboard');
		$positions = Position::where('for', 'supplier')->lists('name', 'id');
		$positions[0] = "None";
		return View::make('suppliers.create')->withPositions($positions);
	}

	/**
	 * Store a newly created supplier in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		$data = Input::except('_token', 'submit');
		$data['logo'] = Supplier::upload('logo');
		$data['contact_photo'] = Supplier::upload('contact_photo');
		if(Input::get('position_id') == 0) $data['position_id'] = null;
		$validator = Validator::make(Input::all(), Supplier::$rules);
		if ($validator->fails()) return Redirect::back()
															->withInput()
															->withMessage('messages.fail-to-create')
															->with('messageType', 'danger')
															->withErrors($validator);
		$supplier = Supplier::create($data);
		if ($supplier) return Redirect::back()
										->withInput()
										->with('message','messages.success-to-create')
										->with('messageType','success');
		return Redirect::back()
										->withInput()
										->with('message','messages.fail-to-create')
										->with('messageType','danger');
	}

	/**
	 * Display the specified supplier.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$supplier = DB::table('suppliers as s')
									->leftJoin('positions as p','p.id', '=', 's.position_id')
									->select(
											's.id',
											's.company_name',
											's.company_email',
											's.tel',
											's.contact_name',
											's.contact_tel',
											's.contact_email',
											's.contact_photo',
											's.address',
											's.logo',
											'p.name'
									)->where('s.id', $id)->first();
		$invoices = SupplierInvoice::where('status','<>', 'draft')
															 ->where('supplier_id', $id)
															 ->orderBy('created_at', 'desc')
															 ->get();
		if (!empty($supplier)) return View::make('suppliers.show', compact('supplier'))->withInvoices($invoices);
		return Redirect::route('suppliers.index');
	}
	/**
	 * Show the form for editing the specified supplier.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		if(!UserRole::has('edit_supplier')) return Redirect::route('dashboard');
		$supplier = Supplier::find($id);
		if (empty($supplier)) return Redirect::route('suppliers.index');
		$positions = Position::where('for', 'supplier')->lists('name', 'id');
		$positions[0] = "None";
		return View::make('suppliers.edit', compact('supplier'))->withPositions($positions);
	}

	/**
	 * Update the specified supplier in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$supplier = Supplier::find($id);
		$data = Input::except('_token', 'submit');
		if(Input::get('position_id') == 0) $data['position_id'] = null;
		$path = "suppliers";
		if(Input::hasFile('logo')) {
			$data['logo'] = Supplier::upload('logo');
		} else {
			$data['logo']	= $supplier->logo;
		}
		if (Input::hasFile('contact_photo')) {
			$data['contact_photo'] = Supplier::upload('contact_photo');
		} else {
			$data['contact_photo'] = $supplier->contact_photo;
		}
		$rules = [
			'company_name'	=> 'unique:suppliers,company_name,'. $supplier->id,
			'company_email'	=> 'unique:suppliers,company_email,' . $supplier->id,
			'tel'	=> 'unique:suppliers,tel,'. $supplier->id,
			'contact_tel'	=> 'unique:suppliers,contact_tel,'. $supplier->id,
			'contact_email'	=> 'unique:suppliers,contact_email,'. $supplier->id
		];
		$validator = Validator::make(Input::all(), $rules);
		if ($validator->fails()) return Redirect::back()
															->withMessage('messages.fail-to-update')
															->with('messageType', 'danger')
															->withErrors($validator)
															->withInput();

		$result = $supplier->update($data);
		if ($result) return Redirect::back()
									->withInput()
									->with('message','messages.success-to-update')
									->with('messageType','success');
		return Redirect::back()
										->withInput()
										->with('message','messages.fail-to-update')
										->with('messageType','danger');
	}

	/**
	 * Remove the specified supplier from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$supplier = Supplier::destroy($id);
		if ($supplier) {
			return Redirect::back()->with('message','messages.success-to-delete')->with('messageType','success');
		} else {
			return Redirect::back()->with('message','messages.fail-to-delete')->with('messageType','danger');
		}

	}
	/**
	 * Get Suppliers
	 * Show all suppliers
	 * @return view
	 */
	public function getSuppliers()
	{
		if(!UserRole::has('create_purchase_order')) return Redirect::route('dashboard');
		$suppliers = Supplier::lists('company_name', 'id');
		return View::make('suppliers.suppliers')->withSuppliers($suppliers);
	}
	/**
	 * Post Suppliers
	 * Send Supplier ID
	 * @return void
	 */
	public function postSuppliers()
	{
		return Redirect::route('purchaseOrder', Input::get('company_name'));
	}
	/**
	 * Get Products in invoice
	 * @param  int $invoice_id
	 * @return object
	 */
	private function getProductsInvoice($invoice_id)
	{
		$products = DB::table('supplier_invoices as si')
											->join('users as u', 'u.id', '=', 'si.user_id')
											->join('orders as o', 'o.sup_invoice_id', '=', 'si.id')
											->join('products as p', 'p.id', '=', 'o.product_id')
											->join('suppliers as s', 's.id', '=', 'si.supplier_id')
											->select(
													'p.sku',
													'p.name',
													'o.amount',
													'p.price_in'
												)
											->where('si.id', $invoice_id)
											->get();
		return $products;
	}
	/**
	 * Get Invoie by Supplier
	 * @param  int $id
	 * @param  int $invoice_id
	 * @return object
	 */
	private function getInvoiceBySupplier($id, $invoice_id)
	{
		$detail = DB::table('supplier_invoices as si')
								->join('users as u', 'u.id', '=', 'si.user_id')
								->join('suppliers as s', 's.id', '=', 'si.supplier_id')
								->select(
									'u.first_name',
									'u.tel as user_tel',
									's.id as supplier_id',
									's.company_name',
									's.company_email',
									's.tel',
									's.address',
									's.contact_name',
									's.contact_tel',
									'contact_email',
									'si.id',
									'si.created_at',
									'si.total',
									'si.pay',
									'si.changed',
									'si.status',
									'si.payable',
									'si.tax'
								)
								->where('si.id', $invoice_id)
								->where('s.id', $id)->first();
		return $detail;
	}
	/**
	 * Show Supplier Invoice
	 * @param  int $id
	 * @param  int $invoice_id
	 * @return view
	 */
	public function supInvoices($id, $invoice_id)
	{
		if(!UserRole::has('detail_purchase_order')) return Redirect::route('dashboard');
		$products = $this->getProductsInvoice($invoice_id);
		$detail = $this->getInvoiceBySupplier($id, $invoice_id);
		$sub_invoice = SupplierInvoice::where('referral_id', $invoice_id)
																	->whereNull('supplier_id')
																	->where('status', 'paid')
																	->first();
		return View::make('suppliers.show_invoice')
								->with('sub_invoice', $sub_invoice)
								->withDetail($detail)
								->withProducts($products);
	}
	/**
	 * Supplier Invoice for print
	 * @param  int $id
	 * @param  int $invoice_id
	 * @return mix
	 */
	public function supInvoicePrint($id, $invoice_id)
	{
		if(!UserRole::has('print_purchase_order')) return Redirect::route('dashboard');
		$products = $this->getProductsInvoice($invoice_id);
		$detail = $this->getInvoiceBySupplier($id, $invoice_id);
		return View::make('suppliers.inc.invoice')
								->withDetail($detail)
								->withProducts($products);
	}
	/**
	 * Post Supplier Approve Purcase Order
	 * @return array
	 */
	public function supplierApprove()
	{
		$invoice_id = Input::get('invoice_id');
		$payment = (float) Input::get('payable');
		if(!empty(Input::get('referral_id'))) {
			$referral_id = Input::get('referral_id');
		}else {
			$referral_id = null;
		}

		$invoice = SupplierInvoice::find($invoice_id);
		// prevent some error
		if (empty($invoice)) return ['error' => true, 'msg' => "Something Wrong"];
		if(empty($payment)) return ['error' => true, 'msg' => "Please Enter Payable"];

		// create new invoice
		$new_invoice = new SupplierInvoice();
		$new_invoice->status = "paid";
		$new_invoice->user_id = Auth::user()->id;
		$new_invoice->rate = $invoice->rate;
		$new_invoice->tax = $invoice->tax;
		$new_invoice->referral_id = $invoice->id;

		// create new profit
		$profit = new Profit;
		$profit->type = "expense";
		$profit->description = "Approved Purchase Order";
		$profit->user_id = Auth::user()->id;
		$profit->rate = $invoice->rate;
		DB::beginTransaction();
		try {
			if($payment < $invoice->payable) {
				return ['error' => true, 'msg' => "Not enough money"];
			} else {
				if($payment == $invoice->payable) {
					$new_invoice->pay = $payment;
					$new_invoice->total = $payment;
					$profit->amount = $payment;
				}
				$new_invoice->pay = $payment;
				$new_invoice->changed = $payment - $invoice->payable;
				$new_invoice->total = $payment - $new_invoice->changed;
				$profit->amount = $new_invoice->total;
			}
			if($new_invoice->save()) {
				$profit->sup_invoice_id = $new_invoice->id;
				$invoice->status = "paid";
				$invoice->payable = 0;
				$invoice->referral_id = $referral_id;
				if($profit->save() && $invoice->save() && $this->updateProducts($invoice_id, $referral_id)) {
					DB::commit();
					return ['error' => false, 'msg' => "Approved successfully"];
				} else {
					DB::rollBack();
					return ['error' => true, "msg" => "Something Wrong!"];
				}
			} else {
				DB::rollBack();
				return ['error' => true, "msg" => "Something Wrong!"];
			}

		} catch (Exception $e) {
			DB::rollBack();
			return ['error' => true, "msg" => "Something Wrong!"];
		}
	}
	/**
	 * Update Products Amoun
	 * @param  int $invoice_id
	 * @return boolean
	 */
	public function updateProducts($invoice_id, $ref_id)
	{
		//return dd(History::poHistroy(12, 32));
		$productsOrder = DB::table('products as p')
									->join('orders as o', 'o.product_id', '=', 'p.id')
									->join('supplier_invoices as si', 'o.sup_invoice_id', '=', 'si.id')
									->where('si.status', 'paid')
									->where('o.sup_invoice_id', $invoice_id)
									->select(
										'p.id',
										'o.amount'
									)->get();
		$success = false;
		/**
		 * loop in to product has been orders
		 */
		foreach ($productsOrder as $product_order) {
			// Create New History with product id and amount
			$history = History::poHistroy($product_order->id, $product_order->amount, $ref_id);
			// find existing product and add amount
			$product = Product::find($product_order->id);
			$product->amount += $product_order->amount;
			if($history == true && $product->save()) {
				$success = true;
			} else {
				$success = false;
			}
		}
		return $success;
	}
}
