<?php
/**
 * Class Purchases Controller
 */
class PurchasesController extends \BaseController {
  /**
   * Get Products by a Supplier
   * @return int id of a supplier
   */
  public function getProducts($id)
  {
    if(!UserRole::has('create_purchase_order')) return Redirect::route('dashboard');
    $supplier = Supplier::whereId($id)->first();
    if(empty($supplier)) return Redirect::back();
    return View::make('purchases.products')
                ->withSupplier($supplier);
  }
  /**
   * Get products by a suppliers
   * Using datatable
   * @return mix
   */
  public function getProductsBySupplier($supplier_id)
  {
    $products = DB::table('Products')
                  ->join('Suppliers', 'Suppliers.id', '=', 'Products.supplier_id')
                  ->select(['Products.id',
                      'Products.sku',
                      'Products.name',
                      'Products.name_kh',
                      'Products.price_in'
                    ])->where('Suppliers.id', $supplier_id);
    return Datatables::of($products)
            ->editColumn('id', function($product) {
              return $product->sku;
            })
            ->editColumn('name', function($product) {
              return $product->name;
            })
            ->editColumn('name_kh', function($product) {
                return $product->name_kh;
            })
            ->editColumn('price_in', function($product) {
                return money($product->price_in);
            })
            ->editColumn('qty', function($product) {
              return "
              <input type='number' min='1' class='form-control' placeholder='Qty' id='qty$product->id' value='1' data-price='$product->price_in' data-sku='$product->sku' />
              ";
            })
            ->editColumn('action', function($product) {
              $output = "";
              $output .= "<button class='btn btn-xs btn-info add-order' 'id='btnAdd$product->id' onclick='purchaseOrder.addItem($product->id)'>".trans('dashboard.crud.add'). "</button>";
              return $output;
            })
            ->make(true);

  }
  /**
   * Post Order Product
   * @return [type] [description]
   */
  public function postOrderProduct()
  {
    $supplier_id = Input::get('supplier_id');
    $product_id = Input::get('product_id');
    // Check product in order
    if(!empty($this->checkItemInOrder($product_id, $supplier_id))) return ['error' => true, 'msg' => trans('messages.duplicated_product')];
    // Get invoice id and create new order
    $id = \InvoiceHelper::getSupInvoiceID($supplier_id);
    $order = new Order;
    $order->invoice_id = null;
    $order->sup_invoice_id = $id;
    $order->product_id = $product_id;
    $order->amount = Input::get('amount');
    $order->price = Input::get('price');
    $order->sold = 0;
    $order->user_id = Auth::user()->id;
    $order->sku = Input::get('sku');
    $order->save();
    return ['error' => false, 'msg' => trans('messages.success-to-add')];
  }
  /**
   * Get Products Order
   * @return mix html plain text
   */
  public function getProductsOrder()
  {
    $sup_invoice_id = InvoiceHelper::getSupInvoiceID(Input::get('supplier_id'));
    $tax = \Helper::getConfig('invoice_tax');
    $productsOrder = DB::table('products as p')
                    ->join('orders as o', 'o.product_id', '=', 'p.id')
                    ->select(
                        'p.id',
                        'p.sku',
                        'p.name',
                        'o.id as order_id',
                        'o.amount as qty',
                        'o.price'
                      )
                    ->where('o.sup_invoice_id', $sup_invoice_id)
                    ->get();
    if (empty($productsOrder)) return ['error' => true];
    $output = "";
    $total = 0;
    foreach($productsOrder as $product) {
      $total += (float) $product->qty * $product->price;
      $output .= "<tr>";
      $output .= "<td>" . $product->sku. "</td>";
      $output .= "<td>" . $product->name . "</td>";
      $output .= "<td><input type='number' class='form-control' min='1' id='qtyupdate{$product->order_id}' value='{$product->qty}'></td>";
      $output .= "<td>" . money($product->price) . "</td>";
      $output .= "<td>" . money($product->qty * $product->price) . "</td>";
      $output .= "<td><button onclick='purchaseOrder.editItem($product->order_id)' id='update{$product->id}' class='btn btn-xs btn-info update'>".trans('dashboard.crud.update')."</button>
        <button onclick='purchaseOrder.deleteItem($product->order_id)' class='btn btn-xs btn-danger'>". trans('dashboard.crud.remove')."</button>
      </td>";
      $output .= "</tr>";
    }
    $output .= "<tr>";
    $output .= "<td colspan='5' class='text-right'>Sub Total :</td>";
    $output .= "<td>" .money($total). "</td>";
    $output .= "</tr>";
    $output .= "<tr>";
    $output .= "<td colspan='5' class='text-right'>Tax :</td>";
    $output .= "<td>" .$tax. "%</td>";
    $output .= "</tr>";
    $output .= "<tr>";
    $total += $total * ($tax/100);
    $output .= "<td colspan='5' class='text-right'>Total :</td>";
    $output .= "<td id='total'​​​​ data-total=". $total .">" .money($total). "</td>";
    $output .= "</tr>";
    if (Request::ajax()) return $output;
    return ['error' => "Not ajax request"];
  }
  /**
   * Put Product Order
   * Update amount of products
   * @return array
   */
  public function putProductsOrder()
  {
    $order = Order::find(Input::get('order_id'));
    if (empty($order)) return ['error' => true, 'msg' => trans('messages.fail-to-update')];
    $order->amount = Input::get('amount');
    if ($order->save()) return ['error' => false, 'msg' => trans('messages.success-to-update')];
  }
  /**
   * Delete Product Order
   * @return array
   */
  public function deleteProductsOrder()
  {
    $order = Order::destroy(Input::get('order_id'));
    if ($order) return ['error' => false, 'msg' => trans('messages.success-to-delete')];
    return ['error' => true, 'msg' => 'messages.fail-to-delete'];
  }
  /**
   * Delete all products order
   * @return array
   */
  public function deleteAllProductsOrder()
  {
    $supplier_id = Input::get('supplier_id');
    $productsOrder = DB::table('products as p')
                  ->join('orders as o', 'o.product_id', '=', 'p.id')
                  ->select('o.id as order_id')
                  ->where('o.sup_invoice_id', InvoiceHelper::getSupInvoiceID($supplier_id))
                  ->get();
    if (empty($productsOrder)) return ['error' => true, 'msg' => trans('messages.fail-to-cancel')];
    $orders_id = [];
    foreach ($productsOrder as $order) {
      $orders_id[] = $order->order_id;
    }
    $orders = Order::destroy($orders_id);
    if ($orders) return ['error' => false, 'msg' => trans('messages.success-to-cancel')];
    return ['error' => true, 'msg' => trans('messages.fail-to-cancel')];
  }
  /**
   * Check Item in Order
   * @param  int $id   id of product
   * @return array of object
   */
  private function checkItemInOrder($product_id, $supplier_id)
  {
    $product = 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')
                  ->select('p.name')
                  ->where('si.id', InvoiceHelper::getSupInvoiceID($supplier_id))
                  ->where('p.id', $product_id)
                  ->first();
    return $product;
  }
  /**
   * Post Deposit
   * @return array Status of message
   */
  public function postDeposit()
  {
    // Get the value of form
    $supplier_id = Input::get('supplier_id');
    $payment = Input::get('payment');
    $sup_invoice_id = InvoiceHelper::getSupInvoiceID($supplier_id);
    // Get Supplier invice
    $sup_invoice = SupplierInvoice::find($sup_invoice_id);
    $data = [
      'user_id' => Auth::user()->id,
      'sup_invoice_id' => (int) $sup_invoice_id,
      'type' => "expense",
      'rate' => $sup_invoice->rate,
      'description' => "Purchase Order"
    ];
    // Calculate total price
    $orders = DB::table('orders')
                ->where('sup_invoice_id', $sup_invoice_id)
                ->get();
    if(empty($orders)) return ['error' => true, 'msg' => "Something Wrong!"];
    $total_price = 0;
    $total_amount = 0;
    foreach($orders as $order) {
      $total_amount += $order->amount;
      $total_price += $order->price * $order->amount;
    }
    // Total Price
    $sup_invoice->total = $total_price + ($total_price * \Helper::getConfig('invoice_tax') /100);
    // Check and Calculate user payment
    $min_deposit = (float) (30/100) * $sup_invoice->total;
    $max_deposit = (float) (70/100) * $sup_invoice->total;
    if(!empty($payment)) {
      if($payment >= $min_deposit && $payment <= $max_deposit) {
        $sup_invoice->pay = (float) $payment;
        $sup_invoice->status = "deposit";
        $sup_invoice->payable = (float) $sup_invoice->total - $payment;
        $data['amount'] = $payment;
      } else {
        return ['error' => true, 'msg' => "Payment must min 30% and max 70% of total price"];
      }
    } else {
      $sup_invoice->status = "unpaid";
      $sup_invoice->payable = $sup_invoice->total;
    }
    if(array_key_exists('amount', $data)) {
      Profit::create($data);
    }
    // Success redirect to invoice
    if ($sup_invoice->save()) {
      return ['error' => false, 'msg' => "Confirm Order Successfully"];
    } else {
      return ['error' => true, 'msg' => "Something Wrong!"];
    }
  }
}
