<?php

namespace App\Models\user;

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

class UserModel extends Model
{

	function insertAddressBook($data)
	{

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

	function selectAddresBook($field, $userId)
	{

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

	function saveUpdateAddressBook($data, $id)
	{
		$i = DB::table('user_address_book')->where('Id', $id)
			->update($data);

		return $i;
	}

	function selectProfileInfo($id)
	{

		$i = DB::table('user_logins')->select('user_logins.name', 'user_logins.username', 'user_logins.email', 'user_logins.email_is_verified', 'user_logins.other_email', 'user_logins.role', 'user_logins.store_id', 'user_info.ContactNumber', 'user_info.Gender', 'user_info.Birthday')
			->leftjoin('user_info', 'user_info.UserId', '=', 'user_logins.id')
			->where('user_logins.id', '=', $id)
			->get();
		return $i;
	}

	function saveUpdateUserLogins($data, $id)
	{
		$i = DB::table('user_logins')->where('id', $id)
			->update($data);

		return $i;
	}

	function saveUpdateUserInfo($data, $id)
	{
		$exists = DB::table('user_info')->where('UserId', $id)->first();

		if (!$exists) {
			$i = DB::table('user_info')->insert($data);
		} else {
			$i = DB::table('user_info')
				->where('UserId', $id)
				->update($data);
		}
		return $i;
	}

	function saveUpdatePassword($password, $id)
	{

		$i = DB::table('user_logins')->where('id', $id)
			->update(['password' => $password]);

		return $i;
	}

	function selectPaymentDetails($field, $val)
	{

		$i = DB::table('payment_details')
			->where($field, $val)
			->get();

		return $i;
	}

	function selectClientDesigns($userid)
	{

		$i = DB::table('client_designs')->where('ClientId', $userid)
			->orderBy('Id', 'DESC')
			->paginate(12);

		return $i;
	}

	function selectClientDesignsbyCode($code)
	{

		$i = DB::table('client_designs')->where('DesignCode', $code)
			->get();

		return $i;
	}

	function selectTemplatePaths($field, $templateid)
	{
		$i = DB::table('template_paths')
			->where($field, $templateid)
			->where('IsActive', 'TRUE')
			->get();
		return $i;
	}

	function updateClientDesign($data, $id)
	{
		$i = DB::table('client_designs')->where('DesignCode', $id)
			->update($data);

		return $i;
	}

	function selectStoreInfo($storeId)
	{
		$i = DB::table('teamstores')->where('Id', $storeId)
			->get();

		return $i;
	}

	function saveResendCode($data)
	{

		$res = DB::table('email_verification_codes')->where("EmailAddress", $data['EmailAddress'])
			->get();

		if ($res) {
			$i = DB::table('email_verification_codes')->where('EmailAddress',  $data['EmailAddress'])
				->update($data);
			return $i;
		} else {
			$i = DB::table('email_verification_codes')->insert($data);
			return $i;
		}
	}

	function validateCode($data)
	{

		$i = DB::table('email_verification_codes')->where('EmailAddress', $data['EmailAddress'])
			->where('VerCode', $data['Code'])
			->get();

		return $i;
	}

	function selectOrderItem($ck)
	{
		$i = DB::table('orders')
			->where('CartKey', $ck)
			->get();
		return $i;
	}

	function selectOrderItemWithStoreId($store_id, $ck)
	{
		$i = DB::table('orders')
			->where('StoreId', $store_id)
			->where('CartKey', $ck)
			->get();
		return $i;
	}

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

	// function selectStoreOrders($store_id){
	// 	$i = DB::table('orders')->select('orders.*', 'orders.Id as Order_Id', 'payment_details.InvoiceNumber', 'payment_details.Currency', 'payment_details.Payer_Email', 'payment_details.Payer_Firstname', 'payment_details.Payer_Lastname', 'shipping_addresses.*', 'tracking_steps.StepLabel')
	// 					->leftjoin('payment_details', 'payment_details.CartKey','=','orders.CartKey')
	// 					->leftjoin('shipping_addresses', 'shipping_addresses.PaymentDetail_Id','=','payment_details.Id')
	// 					->leftjoin('tracking', 'tracking.InvoiceNumber','=','payment_details.InvoiceNumber')
	// 					->leftjoin('tracking_steps', 'tracking_steps.Id','=','tracking.StepId')
	// 					->where('orders.StoreId', $store_id)	
	// 					->orderby('orders.DateCreated', 'DESC')
	// 					->get();
	// 	return $i;
	// }

	function selectStoreOrders($store_id)
	{
		$i = DB::table('orders')->select('orders.*', 'orders.Id as Order_Id', 'payment_details.InvoiceNumber', 'payment_details.Currency', 'payment_details.Payer_Email', 'payment_details.Payer_Firstname', 'payment_details.Payer_Lastname', 'shipping_addresses.*', DB::raw('(SELECT tracking_steps.StepLabel FROM tracking LEFT JOIN tracking_steps ON  tracking_steps.Id = tracking.StepId WHERE tracking.InvoiceNumber = payment_details.InvoiceNumber ORDER BY  tracking.Id DESC LIMIT 1 ) AS StepLabel'), 'teamstore_products.ProductCode')
			->leftjoin('payment_details', 'payment_details.CartKey', '=', 'orders.CartKey')
			->leftjoin('shipping_addresses', 'shipping_addresses.PaymentDetail_Id', '=', 'payment_details.Id')
			->leftjoin('teamstore_products', 'teamstore_products.Id', '=', 'orders.ProductId')
			->where('orders.StoreId', $store_id)
			->orderby('orders.DateCreated', 'DESC')
			->get();
		return $i;
	}


	function itemGroup($cartKey)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$query	=	$pdo->prepare("SELECT *,  COUNT(Id) AS qty, Price * SUM(Quantity) AS total_price FROM orders WHERE CartKey = :ck GROUP BY ProductId");
		$query->execute([':ck' => $cartKey]);
		$row = $query->fetchAll(\PDO::FETCH_OBJ);
		return $row;
	}


	function itemGroupWithStoreId($store_id, $cartKey)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$query	=	$pdo->prepare("SELECT *,  COUNT(Id) AS qty, Price * SUM(Quantity) AS total_price FROM orders WHERE StoreId= :si AND CartKey = :ck GROUP BY ProductId");
		$query->execute(array(':si' => $store_id, ':ck' => $cartKey));
		$row = $query->fetchAll(\PDO::FETCH_OBJ);
		return $row;
	}

	function selectDisplayItemThumb()
	{

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

	function selectDisplayItemThumbById($id)
	{

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

	function deleteImageThumb($field, $id)
	{
		$i = DB::table('teamstore_product_thumbnails')
			->where($field, $id)
			->delete();
		return $i;
	}

	function deleteStoreItem($id)
	{
		$i = DB::table('teamstore_products')
			->where('Id', $id)
			->delete();
		$this->deleteImageThumb('ProductId', $id);
		return $i;
	}

	function selectItemsStoreId($ck)
	{

		$i = DB::table('cart_tmp')
			->select(DB::raw('StoreId'))
			->where('CartKey', $ck)
			->groupby('StoreId')
			->get();
		return $i;
	}


	function selectUserLogins($field, $value)
	{

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

	function insertNewProduct($data)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$i = DB::table('teamstore_products')->insert($data);
		$id = DB::getPdo()->lastInsertId();
		return $id;
	}

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

	function updateProductCode($data, $id)
	{
		$i = DB::table('teamstore_products')->where('Id', $id)
			->update($data);

		return $i;
	}

	function selectTeamStoreName($ck)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$query	=	$pdo->prepare("SELECT t.Id, t.StoreName, t.NoShippingFee FROM orders AS o INNER JOIN teamstores AS t ON t.Id = o.StoreId WHERE o.CartKey = :ck GROUP BY o.StoreId ORDER BY t.StoreName ASC");
		$query->execute(array(':ck' => $ck));
		$row = $query->fetchAll(\PDO::FETCH_OBJ);
		return $row;
	}



	function updateActiveThumb($id, $product_id)
	{
		DB::table('teamstore_product_thumbnails')->where('ProductId', $product_id)
			->update(['ImageClass' => null]);
		$i = DB::table('teamstore_product_thumbnails')->where('Id', $id)
			->update(['ImageClass' => 'active']);
	}

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

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

	function updateTeamstore($id, $data)
	{

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

	function selectShippingAddress($field, $value)
	{

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

	function selectUserLoginsWhereIn($ids)
	{
		$i = DB::table('user_logins')
			->whereIn('store_id', $ids)
			->get();
		return $i;
	}

	function selectShippingCost()
	{
		$i = DB::table('shipping_cost')
			->get();
		return $i;
	}


	function countStoreOrder($storeId)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$query	=	$pdo->prepare("SELECT SUM(o.Quantity) AS count_order FROM orders AS o WHERE o.StoreId = :storeId");
		$query->execute([':storeId' => $storeId]);
		$row = $query->fetchAll(\PDO::FETCH_OBJ);
		return $row;
	}

	function storeIncome($storeId)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$query	=	$pdo->prepare("SELECT SUM(o.Price) AS store_income  FROM orders AS o WHERE o.StoreId = :storeId");
		$query->execute([':storeId' => $storeId]);
		$row = $query->fetchAll(\PDO::FETCH_OBJ);
		return $row;
	}

	function countStoreProduct($storeId)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$query	=	$pdo->prepare("SELECT COUNT(Id) AS store_product_count FROM teamstore_products AS tp WHERE tp.TeamStoreId = :storeId");
		$query->execute([':storeId' => $storeId]);
		$row = $query->fetchAll(\PDO::FETCH_OBJ);
		return $row;
	}

	function countStorePublishedProduct($storeId)
	{
		$pdo 	= 	DB::connection()->getPdo();
		$query	=	$pdo->prepare("SELECT COUNT(Id) AS store_published_product FROM teamstore_products AS tp WHERE tp.TeamStoreId = :storeId AND PrivacyStatus = 'public'");
		$query->execute([':storeId' => $storeId]);
		$row = $query->fetchAll(\PDO::FETCH_OBJ);
		return $row;
	}

	function getAnnouncement($storeId)
	{
		$i = DB::table('store_announcement')
			->where('StoreId', $storeId)
			->get();
		return $i;
	}

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

	function updateAnnouncement($id, $data)
	{
		$i = DB::table('store_announcement')
			->where('Id', $id)
			->update($data);
		return $i;
	}

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

	function getRoster($productId)
	{
		$i = DB::table('roster')
			->where('ProductId', $productId)
			->get();
		return $i;
	}

	 function deleteRoster($idArray)
	{
		$deletedRows = DB::table('roster')
			->whereIn('Id', $idArray) // Replace 'id' with the actual column name if different
			->delete();
	
		return $deletedRows; // Returns the number of rows deleted
	}

	function updateRoster($data)
	{
		$updatedRows = 0;

		foreach ($data as $item) {
			// Assuming each item contains an 'id' and the fields to update
			$id = $item['Id'];
			unset($item['Id']); // Remove 'id' from the update data

			$updatedRows += DB::table('roster')
				->where('Id', $id)
				->update($item);
		}

		return $updatedRows; // Returns the total number of rows updated
	}
}