<?php namespace App\Modules;

use App\Order;
use DB;

class OrderModule {

	public function saveOrder($fields = array())
	{
		return Order::create($fields); 
	}

	public function getPurchaseIdByEmailImeiAndOperator($email, $imei, $operator)
	{
		$order = Order::where('website_id', env('WEBSITE_ID'))->where('email', $email)->where('operator', $operator)->where('status', 'pending')->first();
		return is_object($order) ? $order->order_id : 0;
	}

	public function paginate()
	{
		return Order::where('status', '!=', 'pending')->where('website_id', env('WEBSITE_ID'))->orderBy('dateadded', 'desc')->paginate(50);
	}

	public function getOneByImei($imei)
	{
		return Order::where('imei', $imei)->where('website_id', env('WEBSITE_ID'))->first();
	}

	public function getOneById($id)
	{
		return Order::where('order_id', $id)->where('website_id', env('WEBSITE_ID'))->whereStatus('pending')->first();
	}

	public function update($id, $fields = array())
	{
		return Order::where('order_id', $id)->where('website_id', env('WEBSITE_ID'))->update($fields);
	}

	public function getOneByHashAndId($hash, $order_id)
	{
		return Order::where(DB::raw('md5(CONCAT(operator,phone,imei,datemodified))'), $hash)->where(DB::raw('md5(order_id)'), $order_id)->where('website_id', env('WEBSITE_ID'))->first();
	}

	public function filter($params)
    {
        $per_page = 25;
        if(isset($params['per_page'])) $per_page = (int) $params['per_page'];

        $results = Order::where('status', '!=', 'pending')->where('website_id', env('WEBSITE_ID'));

        if ( isset($params['q']) && trim(strip_tags($params['q'])) != '' ) {
            $q = trim(strip_tags($params['q']));
            $results->where(function($query) use ($q) {
                        $query->orWhere('email', 'like', '%'.$q.'%');
                        $query->orWhere('firstname', 'like', '%'.$q.'%');
                        $query->orWhere('lastname', 'like', '%'.$q.'%');
                        $query->orWhere('phone', 'like', '%'.$q.'%');
                        $query->orWhere('imei', 'like', '%'.$q.'%');
                    });
        } 

        if (isset($params['status'])) {
            $status = str_replace("'", "", strip_tags($params['status']));
            $statuses = array('paid', 'code-sent', 'extracted', 'refunded');
            if ( in_array($status, $statuses) ) {
                $results->where('status', $status);
            }   
        }

        if (isset($params['start_date'])) {
            $start_date = strtotime($params['start_date']. ' 00:00:00');
            $results->where('dateadded', '>=', $start_date);
        }

        if (isset($params['end_date'])) {
            $end_date = strtotime($params['end_date']. ' 23:59:59');
            $results->where('dateadded', '<=', $end_date);
        }

        return $results->orderBy('dateadded', 'desc')->paginate($per_page);
    }


}