<?php

namespace App\Models\admin;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AdminModel extends Model
{
    function selectPaymentDetails($field, $value){

        if($field != "All"){
            $i = DB::table('payment_details')
                            ->where($field, $value)
                            ->orderby('Id', 'ASC')
                            ->get();
        }else{

			$i = DB::table('payment_details')
							->leftjoin('orders', 'payment_details.CartKey', '=', 'orders.CartKey')
							->leftjoin('teamstores', 'teamstores.Id', '=', 'orders.StoreId')
							->select('payment_details.*', 'orders.StoreId', 'teamstores.StoreName')
							->where("payment_details.CartKey", "!=", null)
							->groupby('orders.CartKey')
                            ->orderby('payment_details.Id', 'ASC')
                            ->get();
        }
      
		return $i;
    }
    
    function selectOrderItem($field, $ck){
		$i = DB::table('orders')
							->where($field, $ck)	
							->get();
		return $i;
    }
    
    function itemGroup($cartKey){
      $pdo 	= 	DB::connection()->getPdo();
      $query	=	$pdo->prepare("SELECT orders.*,  COUNT(orders.Id) AS qty, orders.Price * SUM(orders.Quantity) AS total_price, teamstores.StoreName FROM orders LEFT JOIN teamstores on teamstores.Id = orders.StoreId 	WHERE CartKey = :ck GROUP BY ProductId");
      $query->execute([':ck'=>$cartKey]);
      $row = $query->fetchAll(\PDO::FETCH_OBJ);
      return $row;
		
    }
    
    function selectDisplayItemThumb(){

		$i = DB::table('teamstore_product_thumbnails')
										->where('ImageClass', 'active')
										->get();
		return $i;
    }
    
    function selectShippingAddress($field, $value){

		$i = DB::table('shipping_addresses')
										->where($field, $value)
										->get();
		return $i;
	}

	function selectClientDesign($design_code){
		$i = DB::table('client_designs')
										->where('DesignCode', $design_code)
										->get();
		return $i;
	}

	function insertTeamstore($data){

		$i = DB::table('teamstores')->insert($data);
		return $i;
	}

	function selectTeamstore(){

		$i = DB::table('teamstores')
								->paginate(16);
		return $i;
	}
	
	function selectTeamstoreFilter($field, $value){

		$i = DB::table('teamstores')
								->orderby($field, $value)
								->paginate(16);
		return $i;
	}
	
	function selectTeamstoreSearch($field, $value, $keyword){

		$i = DB::table('teamstores')
								->where("StoreName", "LIKE","%$keyword%")
								->orderby($field, $value)
								->paginate(16);
		return $i;
	}
	
	function selectTeamstoreById($id){

		$i = DB::table('teamstores')
								->where("Id", $id)
								->get();
		return $i;
	}

	function updateTeamstore($id, $data){

		$i = DB::table('teamstores')
								->where("Id", $id)
								->update($data);	
		return $i;
	}

	function deleteTeamstoreById($id){

		$i = DB::table('teamstores')
								->where("Id", $id)
								->delete();
		return $i;
	}

	function selectPattern(){

		$i = DB::table('patterns')
								->get();
		return $i;
	}

	function selectPatternWithfield($field, $value){

		$i = DB::table('patterns')
								->where($field, $value)
								->get();
		return $i;
	}

	function selectClipartCategory(){
		$i = DB::table('clipart_categories')
					->leftjoin('user_logins', 'clipart_categories.UserId', '=', 'user_logins.id')
					->select('clipart_categories.*', 'user_logins.username')
					->orderby('clipart_categories.Ordering', 'ASC')
					->get();
		return $i;
	}

	function ClipartCategory(){
		$i = DB::table('clipart_categories')
					->leftjoin('user_logins', 'clipart_categories.UserId', '=', 'user_logins.id')
					->select('clipart_categories.*', 'user_logins.username')
					->orderby('clipart_categories.Ordering', 'ASC')
					->paginate(18);
		return $i;
	}

	function selectStoreOwners($store_id){
		$i = DB::table('user_logins')
				->where('role', 'store_owner')
				->where('store_id', $store_id)
				->get();
		return $i;
	}

	function insertClipartCategory($data){

		$i = DB::table('clipart_categories')->insertGetId($data);
		return $i;
	}

	function insertClipart($data){

		$i = DB::table('cliparts')->insert($data);
		return $i;
	}

	function updateClipartCatOrdering($order, $id){
		$i = DB::table('clipart_categories')->where('Id', $id)
							->update(['Ordering' => $order]);
	}


	function userList(){
		$i = DB::table('user_logins')
				->select('id', 'name', 'username', 'email')
				// ->where("name", "LIKE","%$keyword%")
				// ->orWhere("username", "LIKE","%$keyword%")
				// ->orWhere("email", "LIKE","%$keyword%")
				->where("role", "user")
				->orderby('name', 'ASC')
				->get();
		return $i;
	}

	function makeUserAsStoreOwner($data){
	
		$i = DB::table('user_logins')
								->where("Id", $data['user_id'])
								->update(['role'=> 'store_owner', 'store_id'=> $data['store_id']]);	
		return $i;
	}

	function model_removeStoreAccess($data){
		$i = DB::table('user_logins')
				->where("Id", $data['user_id'])
				->update(['role'=> 'user', 'store_id'=> $data['store_id']]);	
		return $i;
	}

	function deleteClipartCategory($id){

		$i = DB::table('clipart_categories')
								->where("Id", $id)
								->delete();
		return $i;
	}

	function deleteClipart($id){

		$i = DB::table('cliparts')
								->where("Id", $id)
								->delete();
		return $i;
	}

	function updateClipartCategory($id, $data){

		$i = DB::table('clipart_categories')
								->where("Id", $id)
								->update($data);	
						return $i;
	}

	function selectCliparts($cat_id){

		if($cat_id != 0 || $cat_id != ""){
			$i = DB::table('cliparts')->select('cliparts.*', 'clipart_categories.CategoryName')
					->leftjoin('clipart_categories', 'clipart_categories.Id','=','cliparts.CategoryId')
					->where('cliparts.CategoryId', $cat_id)
					->orderby("Id", "DESC")
					->paginate(16);
					return $i;
		}else{
			$i = DB::table('cliparts')->select('cliparts.*', 'clipart_categories.CategoryName')
			->leftjoin('clipart_categories', 'clipart_categories.Id','=','cliparts.CategoryId')
			// ->where('cliparts.CategoryId', $cat_id)
			->orderby("Id", "DESC")
			->paginate(16);
			return $i;
		}

		

						
	}

	function selectSports(){

		$i = DB::table('sports')
								->orderby("SportsName", "ASC")
								->get();
						return $i;
	}

	function selectSportsCategory($id){

		$i = DB::table('template_categories')
								->where('TemplateId', $id)
								->orderby("Category", "ASC")
								->get();
						return $i;
	}
	
	function selectStoreOrders(){
		$i = DB::table('orders')->select('orders.*', 'orders.Id as Order_Id', 'orders.DateCreated AS date_ordered', 'payment_details.InvoiceNumber', 'payment_details.Currency', 'payment_details.Payer_Email', 'payment_details.Payer_Firstname', 'payment_details.Payer_Lastname', 'shipping_addresses.*', 'teamstores.*')
						->leftjoin('payment_details', 'payment_details.CartKey','=','orders.CartKey')
						->leftjoin('shipping_addresses', 'shipping_addresses.PaymentDetail_Id','=','payment_details.Id')
						->leftjoin('teamstores', 'teamstores.Id','=','orders.StoreId')
						// ->where('orders.StoreId', $store_id)	
						->orderby('orders.DateCreated', 'DESC')
						->get();
		return $i;
	}

	function saveNewVisualizer($data){
		$i = DB::table('templates')->insert($data);
		$id = DB::getPdo()->lastInsertId();
		
		return array(
				'i' => $i,
				'lastId' => $id
		);
	}

	function updateVisualizer($id, $data){

		$i = DB::table('templates')
								->where("Id", $id)
								->update($data);	
		return $i;
	}

	function saveVisualizerDefaultBodyColor($data){
		$i = DB::table('template_body_colors')->insert($data);
		
		return $i;
	}

	function saveVisualizerDefaultTrimColor($data){
		$i = DB::table('template_trim_colors')->insert($data);
		return $i;
	}

	function saveVisualizerPath($data){
		$i = DB::table('template_paths')->insert($data);
		return $i;
	}

	function selectVisualizer($sports_id, $sports_category){
		$i = DB::table('templates')
								->where('SportsId', $sports_id)
								->where('Category', $sports_category)
								->orderBy('Id', 'DESC')
								->get();
		return $i;
	}

	function selectDisplayItemThumbById($id){

		$i = DB::table('teamstore_product_thumbnails')
										->where('ProductId', $id)
										->where('ImageClass', 'active')
										->get();
		return $i;
	}

	function selectOrder($field, $value){
		$i = DB::table('orders')
							->where($field, $value)
							->get();
		return $i;
	}

	function editVisualizer($id){
		$i = DB::table('templates')
							->where('Id', $id)
							->get();
		return $i;
	}


	function deleteVisualizer($id){

		$i = DB::table('templates')
								->where("Id", $id)
								->delete();
		return $i;
	}

	function deleteDefaultBodyColor($tempCode){

		$i = DB::table('template_body_colors')
								->where("TemplateCode", $tempCode)
								->delete();
		return $i;
	}

	function deleteTemplatePath($tempCode){

		$i = DB::table('template_paths')
								->where("TemplateCode", $tempCode)
								->delete();
		return $i;
	}

	function deleteDefaultTrimColor($tempCode){

		$i = DB::table('template_trim_colors')
								->where("TemplateCode", $tempCode)
								->delete();
		return $i;
	}

	function deletePrintPatternList($tempCode){

		$i = DB::table('print_pattern_list')
								->where("TemplateCode", $tempCode)
								->delete();
		return $i;
	}
	
	function selectTemplatePath($tempCode){

		$i = DB::table('template_paths')
								->where("TemplateCode", $tempCode)
								->get();
		return $i;
	}

	function selectDefaultBodyColor($tempCode){

		$i = DB::table('template_body_colors')
								->where("TemplateCode", $tempCode)
								->get();
		return $i;
	}

	function selectDefaultTrimColor($tempCode){

		$i = DB::table('template_trim_colors')
								->where("TemplateCode", $tempCode)
								->get();
		return $i;
	}
	
	function updateDefaultBodyColor($tempCode, $data){

		$i = DB::table('template_body_colors')
								->where("TemplateCode", $tempCode)
								->update($data);
		return $i;
	}

	function updateVisualizerPath($id, $data){

		$i = DB::table('template_paths')
								->where("Id", $id)
								->update($data);
		return $i;
	}

	function selectCommission(){
		$i = DB::select("SELECT t.StoreName, pd.InvoiceNumber, pd.CartKey, pd.Total, pd.SubTotal, pd.Tax, pd.Currency,
				(pd.Total * 0.029) AS proc_fee,
				(pd.SubTotal - 0.29) AS trans_rate, ROUND(((
				SELECT trans_rate) - (
				SELECT proc_fee)), 2) AS commission_rate, ROUND(((
				SELECT commission_rate) * 0.25), 2) AS twenty_five_percent, ROUND(((
				SELECT commission_rate) * 0.05), 2) AS five_percent
				FROM orders AS o
				INNER JOIN payment_details AS pd ON pd.CartKey = o.CartKey
				INNER JOIN teamstores AS t ON o.StoreId = t.Id
				GROUP BY pd.CartKey
				ORDER BY o.DateCreated");

		return $i;	
	}

	function selectVisualizerPrint(){
		$i = DB::select("SELECT t.TemplateCode, t.Thumbnail, t.TemplateName, t.IsActive,
		s.SportsName, tc.Category
		FROM templates AS t
		LEFT JOIN sports AS s ON t.SportsId = s.Id
		LEFT JOIN template_categories AS tc ON tc.Id = t.Category");

		return $i;	
	}

	function insertPrintFiles($data){

		$i = DB::table('print_pattern_list')->insert($data);
		return $i;
	}

	function selectGroupPrintFiles(){
		$i = DB::select("SELECT ppl.TemplateCode, t.TemplateName, s.SportsName, tc.Category
		FROM print_pattern_list AS ppl
		INNER JOIN templates AS t ON t.TemplateCode = ppl.TemplateCode
		INNER JOIN sports AS s ON s.Id = t.SportsId
		INNER JOIN template_categories AS tc ON tc.Id = t.Category
		GROUP BY ppl.TemplateCode");

		return $i;	
	}

	function selectPrintFiles($tempCode){
		$i = DB::select("SELECT t.TemplateName, ppl.Id, ppl.Path, ppl.`Type`, ppl.Size from templates AS t
		INNER JOIN print_pattern_list AS ppl ON ppl.TemplateCode = t.TemplateCode
		WHERE t.TemplateCode = '$tempCode'
		ORDER BY ppl.`Type` ASC");

		return $i;	
	}

	function deletePrintFiles($id){
		$i = DB::table('print_pattern_list')
					->where("Id", $id)
					->delete();
			return $i;
	}

	function selectTax(){
		$i = DB::select("SELECT t.Id, t.StoreName, tx.DateCreated FROM tax AS tx
		INNER JOIN teamstores AS t 
		ON t.Id = tx.TeamstoreId");
		return $i;	
	}
}
