<?php

class CustomersController extends \BaseController {
    /**
    * Display a listing of the resource.
    * GET /customers
    *
    * @return Response
    */
    public function index()
    {
        if(!UserRole::has('list_customer')) return Redirect::route('dashboard');
        $q = Input::get('q');
        $pattern = "%" . $q . "%";
        if(!empty($q)) {
            $customers = Customer::where('first_name', "LIKE", $pattern)
            ->orWhere('last_name', "LIKE", $pattern)
            ->orWhere('tel', 'LIKE', $pattern)
            ->orWhere('email', "LIKE", $pattern)->paginate(5);
        } else {
            $customers = Customer::paginate(10);
        }
        return View::make('Customers.index')->withCustomers($customers);

    }
    /**
    * Get Customers
    * @return [Json] [For Datatable]
    */
    public function getCustomers() {
        $customers = DB::table('Customers')
        ->orderBy('id','DESC')
        ->select(['id','sex', 'tel','first_name','last_name']);
        return Datatables::of($customers)
        ->editColumn('first_name',function($customer) {
                return  $customer->first_name;
        })
        ->editColumn('last_name',function($customer) {
                return$customer->last_name;
        })
        ->editColumn('sex', function ($customer) {
            return trans('customers.gender.'. $customer->sex);
        })
        ->editColumn('action',
        '
        @if(UserRole::has("detail_customer"))
        <a href="{{ Route("customers.show",$id) }}" class="btn btn-xs btn-default"><i class="fa fa-th-list"></i> {{Trans("dashboard.others.show")}}</a>
        @endif
        @if(UserRole::has("edit_customer"))
        <a href="{{ Route("customers.edit",$id) }}" class="btn btn-xs btn-info"><i class="fa fa-edit"></i> {{Trans("dashboard.crud.edit")}}</a>
        @endif
        @if(UserRole::has("delete_customer"))
        <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>
        @endif

        <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" => $first_name))}}?
        </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("customers.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>
        '
        )
        ->make(true);
    }
    /**
    * Show the form for creating a new resource.
    * GET /customers/create
    *
    * @return Response
    */
    public function create()
    {
        if(!UserRole::has('create_customer')) return Redirect::route('dashboard');
        if(Branch::getNumber() == "one") {
            $branches = Branch::take(1)->lists('name', 'id');
        } else {
            $branches = Branch::all()->lists('name', 'id');
        }
        return View::make('Customers.new_customer')->withBranches($branches);
    }

    /**
    * Store a newly created resource in storage.
    * POST /customers
    *
    * @return Response
    */
    public function store()
    {
        $data = Input::except(['_token', 'submit']);
        $data['user_id'] = Auth::user()->id;
        $validator = Validator::make(Input::all(), Customer::$rules);
        if ($validator->fails()) return Redirect::back()
        ->withMessage('messages.fail-to-create')
        ->with('messageType', 'danger')
        ->withErrors($validator->messages())
        ->withInput();
        $path = "uploads/customers/";
        if (Input::hasFile('photo')) {
            $data['photo'] = Helper::uploadFile(Input::file('photo'), $path);
        } else {
            if(!empty(Input::get("image_name"))) {
                $destinationPath = public_path() . DIRECTORY_SEPARATOR . $path;
                $imageName = uniqid().".jpg";
                saveImage(Input::get("image_name"),$destinationPath,$imageName);
                $data['photo'] = \Config::get('app.ip'). $path . $imageName;
            }
            else {
                $data['photo'] = \Config::get('app.ip').'uploads/none.jpg';
            }
        }
        if (Customer::create($data)) return Redirect::back()
        ->withMessage('messages.success-to-create')
        ->with('messageType', 'success');
        return Redirect::back()
        ->withInput()
        ->withMessage('messages.success-to-create')
        ->with('messageType', 'success');
    }

    /**
    * Display the specified resource.
    * GET /customers/{id}
    *
    * @param  int  $id
    * @return Response
    */
    public function show($id)
    {
        if(!UserRole::has('detail_customer')) return Redirect::route('dashboard');
            $customer = Customer::find($id);
            $invoices = Invoice::where('customer_id',$id)->get();
            $quotations = CustomerQuotation::where('customer_id', $id)
            ->where('status', 'closed')
            ->get();
        if ($customer) {
            return View::make('Customers.show')
            ->withCustomer($customer)
            ->withQuotations($quotations)
            ->withInvoices($invoices);
        } else {
            return Redirect::route('customers.index');
        }
    }
    /**
    * Print the specified resource.
    * GET /customers/{id}print
    *
    * @param  int  $id
    * @return Response
    */
    public function printCustomer($id)
    {
        if(!UserRole::has('detail_customer')) return Redirect::route('dashboard');
            $customer = LoanCustomer::find($id);
            $guarantor = Garantor::find($id);
        if ($customer) {
            return View::make('customers.print_detail')
            ->withCustomer($customer)
            ->withGuarantor($guarantor);
        } else {
            return Redirect::route('customers.index');
        }
    }

    /**
    * Show the form for editing the specified resource.
    * GET /customers/{id}/edit
    *
    * @param  int  $id
    * @return Response
    */
    public function edit($id)
    {
        if(!UserRole::has('edit_customer')) return Redirect::route('dashboard');
        $branches = Branch::all()->lists('name', 'id');
        $customer = Customer::find($id);
        if (!$customer) return Redirect::route('customers.index');
        return View::make("Customers.edit")->withCustomer($customer)->withBranches($branches);
    }

        /**
        * Update the specified resource in storage.
        * PUT /customers/{id}
        *
        * @param  int  $id
        * @return Response
        */
        public function update($id)
        {
            $customer = Customer::find($id);
            $rules = [
                'email' => 'unique:customers,email,'.$customer->id,
                'tel' => 'unique:customers,tel,'.$customer->id
            ];
            $validator = Validator::make(Input::all(), $rules);
            if ($validator->fails()) return Redirect::back()
            ->withMessage('messages.fail-to-update')
            ->with('messageType', 'danger')
            ->withErrors($validator->messages())
            ->withInput();

            $customer->first_name = Input::get('first_name');
            $customer->last_name = Input::get('last_name');
            $customer->branch_id = Input::get('branch_id');
            $customer->dob = !empty(Input::get('dob')) ? Input::get('dob') : null;
            $customer->email = Input::get('email');
            $customer->tel = Input::get('tel');
            $customer->sex 	= Input::get('sex');
            $customer->note = Input::get('note');
            $customer->id_card = Input::get('id_card');
            $customer->address = Input::get('address');
            $path = 'uploads/customers/';
            if (Input::hasFile('photo')) {
                $customer->photo = Helper::uploadFile(Input::file('photo'), $path);
            } else {
                if(!empty(Input::get("image_name"))) {
                    $destinationPath = public_path() . DIRECTORY_SEPARATOR.  $path;
                    $imageName = uniqid().".jpg";
                    saveImage(Input::get("image_name"),$destinationPath,$imageName);
                    $customer->photo = \Config::get('app.ip'). $path . $imageName;
                }
            }
            $result = $customer->save();
            if (!$result) return Redirect::back()->withInput()->withMessage('messages.fail-to-update')->with('messageType', 'danger');
            if (!empty(Input::get('installment_id'))) {
                return Redirect::route('installments.show', Input::get('installment_id'))->withMessage('messages.success-to-update')->with('messageType', 'success');
            }
            return Redirect::back()->withInput()->withMessage('messages.success-to-update')->with('messageType', 'success');
        }

        /**
        * Remove the specified resource from storage.
        * DELETE /customers/{id}
        *
        * @param  int  $id
        * @return Response
        */
        public function destroy($id)
        {
            $customer = Customer::find($id);
            if (!$customer) return Redirect::back();
            $invoices = Invoice::where('customer_id', $id)->get();
            if (count($invoices) > 0) return Redirect::back()->withMessage('messages.not_allow_to_delete')->with('messageType', 'warning');
            $result = $customer->delete();
            if (!$result) return Redirect::back()->withMessage('messages.fail-to-delete')->with('messageType', 'danger');
            return Redirect::back()->withMessage('messages.success-to-delete')->with('messageType', 'success');
        }

        /**
        * Customer
        */
        public function customersList()
        {
            $customers = DB::table('Customers')->where('first_name','LIKE',"%".Input::get('term')."%")->orWhere('last_name','LIKE',"%".Input::get('term')."%")->select(['id','last_name','first_name','photo'])->get();
            return Response::json(array(
                'customers'			=>	$customers,
                'error' 		=> false),
                200
            );
        }

        /**
        * List All Products in Stock
        * Using Ajax datatables
        * @return mix
        */
        public function getProducts()
        {
            $products = DB::table('Products')
            ->select(['Products.id',
            'Products.sku',
            'Products.name',
            'Products.name_kh',
            'Products.amount',
            'Products.price'
        ]);
        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('amount', function($product) {

            if($this->getProductInStock($product->id) > 0) {
                return $product->amount += $this->getProductInStock($product->id);
            } else {
                return $product->amount;
            }
        })
        ->editColumn('price', function($product) {
            return money($product->price);
        })
        ->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' data-sku='$product->sku' />
            ";
        })
        ->editColumn('action', function($product) {
            $output = "";
            $output .= "<button class='btn btn-xs btn-info add-order' 'id='btnAdd$product->id' onclick='quotation.addItem($product->id)'>".trans('dashboard.crud.add'). "</button>";
            return $output;
        })
        ->make(true);
    }
    /**
    * Quotation View
    * @return mix
    */
    public function quotation($id)
    {
        if(!UserRole::has('create_quotation')) return Redirect::route('dashboard');
        // pass customer id to get customer quotation
        $customer = Customer::find($id);
        if(empty($customer)) return Redirect::back();
        return View::make('Customers.quotations.index')
        ->withCustomer($customer);
    }
    public function postQuotation()
    {
        /**
        * Get value from Ajax request
        * @var int
        */
        $customer_id = (int) Input::get('customer_id');
        $customer_quot_id = (int) Input::get('customer_quot_id');
        /**
        * Find exiting Customer Quoation
        * @var object
        */
        $customerQuot = CustomerQuotation::find($customer_quot_id);
        $customerQuot->status = 'closed';;

        if($customerQuot->save()) {
            return Redirect::route('customers.quot', [$customer_id, $customer_quot_id]);
        } else {
            return Redirect::back()->withMessage("Something Wrong!");
        }
    }
    /**
    * Add Item into Order
    * @return array
    */
    public function postAddItem()
    {
        /**
        * Get Customer Quotation ID
        * @var int
        */
        $customer_quot_id = \Helper::getCustomerQuotID(Input::get('customer_id'));
        $amount = (int) Input::get('amount');
        $product_id = (int) Input::get('product_id');
        /**
        * Check Exiting Product in Quotation
        */
        if(!empty($this->checkItemInQuot($product_id, $customer_quot_id))) return ['error' => true, 'msg' => trans('messages.duplicated_product')];
        $amountInstock = $this->getProductInStock($product_id);
        $product = Product::find($product_id);
        if($amountInstock > 0) {
            $product->amount += $amountInstock;
        }
        if($amount > $product->amount) return ['error' => true, 'msg' => "Not Enough Item"];
        /**
        * Create new Quotation
        * @var Quotation
        */
        $quotation = new Quotation;
        $quotation->product_id 				= $product_id;
        $quotation->customer_quot_id 	=  $customer_quot_id;
        $quotation->amount 						= $amount;
        $quotation->user_id 						= Auth::user()->id;
        $quotation->save();
        return ['error' => false, 'msg' => trans('messages.success-to-create')];
    }
    /**
    * Check Proudct In Order
    * @param  int $product_id
    * @return object
    */
    private function checkItemInQuot($product_id, $customer_quot_id)
    {
        $product = DB::table('products as p')
        ->join('quotations as q', 'q.product_id', '=', 'p.id')
        ->select('q.product_id')
        ->where('q.product_id', $product_id)
        ->where('q.customer_quot_id', $customer_quot_id)
        ->first();
        return $product;
    }
    /**
    * Get Products Order
    * @return mix html plain text
    */
    public function getProductsQuotation()
    {
        $customer_id = (int) Input::get('customer_id');
        $customer_quot_id = (int) Input::get('customer_quot_id');
        $tax = \Helper::getConfig('invoice_tax');
        $products = DB::table('products as p')
        ->join('quotations as q', 'q.product_id', '=', 'p.id')
        ->select(
            'p.id',
            'p.name',
            'p.sku',
            'p.price',
            'q.id as quotation_id',
            'q.amount as qty'
            )
            ->where('q.customer_quot_id', $customer_quot_id)
            ->get();
            if (empty($products)) return ['error' => true, 'msg' => "No Product in Quotaion"];
            $output = "";
            $total = 0;
            $i = 1;
            foreach($products as $product) {
                $total += (float) $product->qty * $product->price;
                $output .= "<tr>";
                $output .= "<td>" . $i++ . "</td>";
                $output .= "<td>" . $product->sku. "</td>";
                $output .= "<td>" . $product->name . "</td>";
                $output .= "<td><input type='number' class='form-control' min='1' id='qtyupdate{$product->quotation_id}' value='{$product->qty}' data-product-id='$product->id'></td>";
                $output .= "<td>" . money($product->price) . "</td>";
                $output .= "<td>" . money($product->qty * $product->price) . "</td>";
                $output .= "<td><button onclick='quotation.editItem($product->quotation_id)' id='update{$product->id}' class='btn btn-xs btn-info update'>".trans('dashboard.crud.update')."</button>
                <button onclick='quotation.deleteItem($product->quotation_id)' class='btn btn-xs btn-danger'>". trans('dashboard.crud.remove')."</button>
                </td>";
                $output .= "</tr>";
            }
            $output .= "<tr>";
            $output .= "<td colspan='6' class='text-right'>Sub Total :</td>";
            $output .= "<td>" .money($total). "</td>";
            $output .= "</tr>";
            $output .= "<tr>";
            $output .= "<td colspan='6' class='text-right'>Tax :</td>";
            $output .= "<td>" .$tax. "%</td>";
            $output .= "</tr>";
            $output .= "<tr>";
            $total += $total * ($tax/100);
            $output .= "<td colspan='6' 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 toast message
        */
        public function putProductsQuot()
        {
            /**
            * Get the value form Ajax request
            * @var int
            */
            $amount = (int) Input::get('amount');
            $product_id = (int) Input::get('product_id');
            $customer_quot_id = (int) Input::get('customer_quot_id');
            /**
            * Find existing Quotation
            * @var object
            * @param int customer quot id
            */
            $quotation = Quotation::where('id', Input::get('quotation_id'))
            ->where('customer_quot_id', $customer_quot_id)
            ->first();
            if(empty($quotation)) return ['error' => true, 'msg' => trans('messages.fail-to-update')];
            $amountInstock = $this->getProductInStock($product_id);
            $product = Product::find($product_id);
            if($amountInstock > 0) {
                $product->amount += $amountInstock;
            }
            if($amount > $product->amount) {
                return ['error' => true, 'msg' => "Not enough Item", 'reload' => true];
            } else {
                $quotation->amount = $amount;
            }
            if ($quotation->save()) return ['error' => false, 'msg' => trans('messages.success-to-update')];
        }
        /**
        * Delete Product Order
        * @return array
        */
        public function deleteProductsQuot()
        {
            /**
            * Find Exiting Quotation and delete
            * @var boolean
            */
            $quotation = Quotation::find(Input::get('quotation_id'))
            ->where('customer_quot_id', Input::get('customer_quot_id'))
            ->first();
            if ($quotation->delete()) return ['error' => false, 'msg' => trans('messages.success-to-delete')];
            return ['error' => true, 'msg' => 'messages.fail-to-delete'];
        }
        /**
        * Check amount Products in stock
        * @param  int $id
        * @return object
        */
        private function checkAmountInStock($id)
        {
            // Product In Stock
            $product = DB::table('products as p')
            ->join('outlets as o', 'o.product_id', '=', 'p.id')
            ->join('stocks as s', 'o.stock_id', '=', 's.id')
            ->select('o.amount', 'o.price')
            ->where('o.product_id', $id)
            ->first();
            return $product;
        }
        /**
        * Delete All products
        * in Order for Create Quotation for Customer
        * @return array
        */
        public function deleteAllProductsQuot()
        {
            /**
            * Get Value from Ajax Request
            * @var int
            */
            $customer_quot_id = (int) Input::get('customer_quot_id');
            /**
            * Get All Quotation
            * @var object
            */
            $quotations = DB::table('products as p')
            ->join('quotations as q', 'q.product_id', '=', 'p.id')
            ->select('q.id')
            ->where('q.customer_quot_id', $customer_quot_id)
            ->get();
            /**
            * Check Empty
            */
            if (empty($quotations)) return ['error' => true, 'msg' => trans('messages.fail-to-cancel')];
            /**
            * Quotation ID
            * @var array
            */
            $quotation_id = [];
            foreach ($quotations as $quotation) {
                $quotation_id[] = $quotation->id;
            }
            /**
            * Delete all Quotation
            * @var boolean
            */
            $quotations = Quotation::destroy($quotation_id);
            if ($quotations) return ['error' => false, 'msg' => trans('messages.success-to-cancel')];
            return ['error' => true, 'msg' => trans('messages.fail-to-cancel')];
        }
        /**
        * View Quotation by Customer
        * @param  int $id
        * @param  int $qid
        */
        public function getCustomerQuots($id, $qid)
        {
            if(!UserRole::has('detail_quotation')) return Redirect::route('dashboard');
            $customer = Customer::find($id);
            $customer_quot = CustomerQuotation::find($qid);
            if(empty($customer) && empty($customer_quot)) return Redirect::back();
            return View::make('Customers.quotations.detail')
            ->withCustomer($customer)
            ->with('customer_quot', $customer_quot);
        }
        /**
        * Print Quotation by Customer
        * @param  int $id
        * @param  int $qid
        */
        public function printCustomerQuot($id, $qid)
        {
            // find products in quotation for print
            $products = DB::table('products as p')
            ->join('quotations as q', 'q.product_id', '=', 'p.id')
            ->join('customer_quotations as cq', 'cq.id', '=', 'q.customer_quot_id')
            ->leftjoin('units', 'units.id', '=', 'p.unit_id')
            ->select(
                'units.name as unit',
                'p.sku',
                'p.name',
                'p.price',
                'q.amount')
                ->where('cq.id', $qid)
                ->where('status', 'closed')
                ->where('cq.customer_id', $id)
                ->get();
                // Customer info and quotation
                $detail = DB::table('customers as c')
                ->join('customer_quotations as cq', 'cq.customer_id', '=', 'c.id')
                ->join('users as u', 'u.id', '=', 'cq.user_id')
                ->select(
                    'u.first_name as u_first',
                    'u.last_name as u_last',
                    'c.first_name',
                    'c.last_name',
                    'c.tel',
                    'cq.id',
                    'cq.created_at')
                    ->where('c.id', $id)
                    ->where('cq.id', $qid)
                    ->where('cq.status', 'closed')
                    ->first();
                    if(empty($products) && empty($detail)) return Redirect::back();
                    return View::make('Customers.quotations.print')
                    ->withProducts($products)
                    ->withDetail($detail);
                }
                /**
                * Get Amount of product in stock
                * @param  int $id ID of Product
                * @return int amount of Product
                */
                private function getProductInStock($id)
                {
                    $product = DB::table('products as p')
                    ->join('outlets as o', 'o.product_id', '=', 'p.id')
                    ->join('stocks as s', 'o.stock_id', '=', 's.id')
                    ->select('o.amount')
                    ->where('p.id', $id)
                    ->first();
                    if(empty($product)) return 0;
                    return $product->amount;
                }
                /**
                * Delete Customer Quotation
                * @param  int $id
                */
                public function deleteCustomerQuotation($id)
                {
                    $quotation = CustomerQuotation::find($id);
                    $result = $quotation->delete();
                    if (!$result) return Redirect::back()->withMessage('messages.fail-to-delete')->with('messageType', 'danger');
                    return Redirect::back()->withMessage('messages.success-to-delete')->with('messageType', 'success');
                }

                public function addNewCustomer()
                {
                    $invoiceId = InvoiceHelper::getInvoiceID();
                    $data = Input::except('_token');
                    if (!empty($data['tel'])) {
                        $exitTel = Customer::where('tel', $data['tel'])->first();
                        if ($exitTel) return ['error' => true, 'msg' => "Tel aleady existing"];
                    }
                    $data['photo'] = \Config::get('app.ip'). "uploads/none.jpg";
                    $customer = Customer::create($data);
                    if ($customer) {
                        $invoice = Invoice::find($invoiceId);
                        $invoice->customer_id = $customer->id;
                        if ($invoice->save()) return ['error' => false, 'msg' => "Created Customer"];
                    }
                    return ['error' => "Fail to create customer"];
                }

                public function addNewCustomerQuotation()
                {
                    $data = Input::except('_token');
                    if (!empty($data['tel'])) {
                        $exitTel = Customer::where('tel', $data['tel'])->first();
                        if ($exitTel) return ['error' => true, 'msg' => "Tel aleady existing"];
                    }
                    $data['photo'] = \Config::get('app.ip').'uploads/none.jpg';
                    $customer = Customer::create($data);
                    if ($customer) {
                        return ['error' => false, 'msg' => "Created Customer", 'customer' => $customer];
                    }
                    return ['error' => true, 'msg' => "Fail to create customer"];
                }
            }
