<?php
class USERS extends BASE
{

	public $isLogin = false;

	// اگر وضعیت شخص فعال باشد
	const STATUS_ACTIVE = "فعال";
	// اگر شخص غیر فعال شده باشد
	const STATUS_DISACTIVE = "کاربری غیر فعال";

	const STATUS_LIST = [
		self::STATUS_ACTIVE,
		self::STATUS_DISACTIVE
	];

	const QUESTION_LIST = [
		"اسم اولین مدرسه شما چیست؟",
		"نام اولین معلم شما چیست؟",
		"نام بزرگترین خواهر شما چیست؟",
		"نام کوچکترین خواهر شما چیست؟",
		"نام بزرگترین برادر شما چیست؟",
		"نام کوچکترین برادر شما چیست؟",
		"اسم حیوان خانگی شما چیست؟",
		"اسم اولین سایتی که داشتی چیست؟",
		"اسم بهترین دوست شما چیست؟",
		"اسم وسیله نقلیه مورد علاقه شما چیست؟",
	];
	public $cols = [

		"id" => ["type" => self::TYPE_AUTOID, "lbl" => "شماره", "val" => "-1", "list" => []],
		"tel" => ["type" => self::TYPE_TEL, "lbl" => "موبایل", "val" => "", "list" => [], "require" => true],

		"name" => ["type" => self::TYPE_TEXT30, "lbl" => "نام", "val" => "", "list" => [], "require" => true],
		"family" => ["type" => self::TYPE_TEXT100, "lbl" => "فامیلی", "val" => "", "list" => [], "require" => true],
		"birthday" => ["type" => self::TYPE_DATE, "lbl" => "تاریخ تولد", "val" => "1402/1/1", "require" => true],

		"pass" => ["type" => self::TYPE_SECRET, "lbl" => "رمز", "val" => "", "list" => [], "require" => true],

		"address" => ["type" => self::TYPE_TEXT400, "lbl" => "آدرس"],
		"postalcode" => ["type" => self::TYPE_TEXT20, "lbl" => "کدپستی"],
		"meli" => ["type" => self::TYPE_TEXT20, "lbl" => "شماره ملی"],
		"email" => ["type" => self::TYPE_EMAIL, "lbl" => " email ایمیل", "val" => "", "list" => ["مقدماتی", "متوسط", "پیش رفته"], "require" => false],
		"question" => ["type" => self::TYPE_SELECT, "lbl" => "سوال محرمانه <span class='text-info'>هنگام بازیابی رمز عبور</span>", "val" => "", "list" => self::QUESTION_LIST, "require" => true],
		"ansver" => ["type" => self::TYPE_SECRET, "lbl" => "پاسخ محرمانه", "val" => "", "list" => [], "require" => true],
		"moaref_tel" => ["type" => self::TYPE_TEL, "lbl" => "موبایل معرف", "val" => "", "list" => [], "require" => false],
		"pic_url" => ["type" => self::TYPE_IMG, "lbl" => "تصویر", "val" => "", "list" => [], "require" => false],
		"access" => ["type" => self::TYPE_MULTI_SELECT, "lbl" => "مجوز ها", "val" => "", "list" => [], "require" => false],
		"status" => ["type" => self::TYPE_SELECT, "lbl" => "وضعیت کاربر", "val" => self::STATUS_ACTIVE, "list" => self::STATUS_LIST, "require" => true],
		"tarikh" => ["type" => self::TYPE_TIMESTAMP, "lbl" => "ایجاد", "val" => "", "list" => [], "require" => false],
		"last_modify" => ["type" => self::TYPE_LAST_TIMESTAMP, "lbl" => "ویرایش", "val" => "", "list" => [], "require" => false],
	];
	public function __construct($conn, )
	{
		$vals = [];
		$lbl = [];

		// لیست منوهای صفحه ادمین برای تنظیم قسمت مجوز ها
		global $adminMenus;
		foreach ($adminMenus as $item) {
			$vals[] = $item['name'];
			$lbl[] = $item['label'];
			if (isset($item['list'])) {
				foreach ($item['list'] as $subItem) {
					$vals[] = $subItem['name'];
					$lbl[] = $subItem['label'];
				}
			}

		}

		$this->cols['access']['list']['val'] = $vals;
		$this->cols['access']['list']['lbl'] = $lbl;
		parent::__construct(conn: $conn, table_name: __CLASS__, ListOfCols: $this->cols, className: __CLASS__);

	}
	public function getByTel($tel = NULL)
	{
		// این تابع یک ردیف از اطلاعات دیتا بیس را بر اساس شماره تلفن آن استخراج می کند
		$tel = (isset($tel)) ? $tel : $this->cols['tel']['val'];
		if ($tel == "") {
			if (count($this->search(["id" => "!=''"])) <= 0)
				$this->set([
					"name" => "hrrjAdmin",
					"family" => "admin",
					"id" => "-1364",
					"pass" => "hrrjpass",
					"status" => self::STATUS_ACTIVE,
					"access" => implode("\n", $this->cols['access']['list']['val'])
				]);
		} else {
			return parent::getByCols(["tel" => $tel]);
		}
	}
	public function find($textToFind = "")
	{
		// این تابع جستجو بر اساس رشته درون ستون های رشته ای انجام می دهد
		$option = [
			"CONCAT(`name`,' ',`family`)" => "like '%" . $textToFind . "%'",
			"name" => "like '%" . $textToFind . "%'",
			"family" => "like '%" . $textToFind . "%'",
			"tel" => "like '%" . $textToFind . "%'",
			"meli" => "like '%" . $textToFind . "%'",
		];
		// نتایج جستجو برگردانده می شود 
		return $this->search($option, " or ");
	}

	public function showCard($userList, $label1 = NULL, $link1 = NULL)
	{
		foreach ($userList as $user) {

			$label = isset($label1) ? $label1 : '';
			$link = isset($link1) ? $link1 : "?" . strtolower(__CLASS__) . "_id=" . $user['id'];

			?>
			<div class="col-md-4 mb-1 mt-1 g-5 ">
				<div class="card shadow">
					<div class="card-header text-center bg-info">
						<?= $label . ' ' . $user['name'] . ' ' . $user['family'] ?>
					</div>
					<div class="card-body">

						<p><b>شماره تماس:</b> <?= $user['tel'] ?></p>
						<p><b>ادرس ایمیل:</b> <?= $user['email'] ?></p>
						<p><b>دسترسی ها:</b> <?= implode(" ، ", explode('_', $user['access'])) ?></p>
					</div>
					<div class="card-footer">
						<a class=" btn btn-sm btn-outline-secondary" href="<?= $link ?>">بیشتر </a>
					</div>

				</div>

			</div>
			<?php
		}
	}
	public function set_loginout_reciver()
	{
		// این دستور همیشه باید در ابتدای صفحه قبل از ارسال هدر قرار گیرد
		if (isset($_REQUEST['loginData'])) {
			if ($this->SET_REQUEST_RECIVER("idLoginUser", [self::SHOW_LOGIN_BTN])) {
				// بررسی برای ورود
				if ($this->autenticate($_REQUEST['tel'], $_REQUEST['pass'])) {
					$this->getByTel($_REQUEST['tel']);
					if ($this->status != self::STATUS_ACTIVE) {
						echo "<div dir='rtl' class='alert alert-danger mb-5 mt-5'>
						اطلاعات کاربری شما محدود شده است
						<br>
						با مسئول مربوطه هماهنگ کنید
						</div>";
					} else {
						$remember = isset($_REQUEST['remember']) ? true : NULL;
						$this->login($_REQUEST['tel'], $this->id, $remember);
						echo "<h1 dir='rtl' class='alert alert-success mb-5 mt-5'>{$this->name} خوش آمدید</h1>";
					}
				} else {
					echo "<h1 dir='rtl' class='alert alert-danger mb-5 mt-5'>اطلاعات ورودی نادرست است</h1>";
					$this->logout();
				}
			}
		} elseif (isset($_REQUEST['logout'])) {
			// بررسی برای خروج
			//$this->set($data);
			$this->logout();
		} elseif (isset($_REQUEST['signupData'])) {

			// بررسی برای ثبت نام
			$find = $this->search(["tel" => $_REQUEST['tel']]);
			if (count($find)) {

				echo "<h1 class='alert alert-warning'>شماره موبایل قبلا ثبت شده است</h1>";
			} else {
				$this->SET_REQUEST_RECIVER("idSignupUser", [self::SHOW_SIGNUP_BTN]);
			}
		} elseif (isset($_REQUEST['selectData'])) {

			if ($this->SET_REQUEST_RECIVER("idForgetUser", [self::SHOW_SELECT_BTN])) {
				$find = $this->search([
					//"name"=>$this->name,
					// "family"=>$this->family,
					"tel" => $this->tel,
					"question" => [$this->question],
					"ansver" => $this->ansver
				]);
				if (count($find) == 1) {
					$this->get($find[0]['id']);
					$this->pass = $_REQUEST['pass'];
					$this->update();
					echo "<h1 class='alert alert-success'>رمز عبور با موفقیت ویرایش شد</h1>";
				}
			}
		}


	}
	public function loginoutForm()
	{
		if (!$this->isLogin) {
			?>
			<div>
				<div class="modal fade" id="loginUserModal" tabindex="-1" aria-labelledby="loginUserModalLabel" aria-hidden="true">
					<div class="modal-dialog  modal-dialog-scrollable">
						<div class="modal-content">
							<div class="modal-header">

								<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
								<h1 class="modal-title fs-5" id="loginUserModalLabel">ورود کاربران</h1>
							</div>
							<div class="modal-body" dir="rtl">
								<?php
								$label = [
									"tel" => ["require" => false],
									"pass" => ["require" => false],
									"remember" => [
										"type" => "checkbox",
										"val" => "",
										"lbl" => "30 روز ",
										"require" => false,
										"list" => ["مرا به خاطر داشته باش"]
									]
								];
								$this->form("idLoginUser", $label, [self::SHOW_LOGIN_BTN], ["validation" => true, "columnClass" => "form-floating p-2"]); ?>
							</div>
							<div class="modal-footer">
								<button type="button" class="btn " data-bs-toggle="modal" data-bs-target="#forgetUserModal">
									فراموشی رمز
								</button>
								<button type="button" class="btn " data-bs-toggle="modal" data-bs-target="#signupUserModal">
									ثبت نام
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div>
				<div class="modal fade" id="signupUserModal" tabindex="-1" aria-labelledby="signupUserModalLabel"
					aria-hidden="true">
					<div class="modal-dialog  modal-dialog-scrollable">
						<div class="modal-content">
							<div class="modal-header">

								<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
								<h1 class="modal-title fs-5" id="signupUserModalLabel">ثبت نام</h1>
							</div>
							<div class="modal-body" dir="rtl">
								<?php
								$label = [
									"name" => "نام",
									//"status"=>self::STATUS_ACTIVE,
									"family" => "فامیلی",
									"tel" => "موبایل",
									"pass" => "رمز عبور",
									"question" => "سوال محرمانه(برای زمان فراموشی رمز)",
									"ansver" => "پاسخ شما به سوال محرمانه",
									"moaref_tel" => "شماره تماس معرف",
								];
								$this->form("idSignupUser", $label, [self::SHOW_SIGNUP_BTN], ["validation" => true, "columnClass" => "d-flex flex-column-reverse mt-3"]); ?>
							</div>
							<div class="modal-footer">
								<button type="button" class="btn " data-bs-toggle="modal" data-bs-target="#forgetUserModal">
									فراموشی رمز
								</button>
								<button type="button" class="btn " data-bs-toggle="modal" data-bs-target="#loginUserModal">
									ثبت نام کرده ام
								</button>


							</div>
						</div>
					</div>
				</div>
			</div>
			<div>
				<div class="modal fade" id="forgetUserModal" tabindex="-1" aria-labelledby="forgetUserModalLabel"
					aria-hidden="true">
					<div class="modal-dialog  modal-dialog-scrollable">
						<div class="modal-content">
							<div class="modal-header">

								<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
								<h1 class="modal-title fs-5" id="forgetUserModalLabel">فراموشی رمز عبور</h1>
							</div>
							<div class="modal-body" dir="rtl">
								برای تغییر رمز قبلی، اطلاعات خواسته شده را به دقت وارد نمایید و در پایان دکمه بررسی را کلیک کنید
								<?php
								$cols = [
									//"name",
									//"family",
									"tel",
									"pass" => "رمز جدید",
									"question",
									"ansver",
								];
								$this->form("idForgetUser", $cols, [self::SHOW_SELECT_BTN => ["lbl" => "بررسی"]], ["validation" => true, "columnClass" => "form-floating p-2"]); ?>
							</div>
							<div class="modal-footer">
								<button type="button" class="btn " data-bs-toggle="modal" data-bs-target="#signupUserModal">
									ثبت نام
								</button>
								<button type="button" class="btn " data-bs-toggle="modal" data-bs-target="#loginUserModal">
									ورود
								</button>


							</div>
						</div>
					</div>
				</div>
			</div>
			<?php
		}

	}
	public function loginoutButtons()
	{

		if ($this->isLogin) {
			?>
			<div class="btn-group dropend" role="group" dir="ltr">
				<button type="button" class="btn btn-secondary shadow dropdown-toggle text-nowrap" data-bs-toggle="dropdown"
					aria-expanded="false">
					<?php $src = ($this->pic_url != "") ? $this->pic_url : "../src/site_images/man.jpg"; ?>

					<span>
						<img src="<?= $src; ?>" class="rounded-3" width="30px" alt="<?= $this->name ?>">
						<span class="d-none d-md-inline-block"><?= $this->name ?> 			<?= $this->family ?></span>
					</span>

				</button>
				<ul class="dropdown-menu" dir="rtl">
					<li class="d-md-none btn w-100 disabled border-0">
						<?= $this->name ?> 			<?= $this->family ?>
					</li>
					<li>
						<a href="?logout=ok&id=" class="btn w-100">خروج</a>
					</li>
					<li>
						<a href="?panel=profile" class="btn w-100 <?php if (isset($_GET['panel']) && $_GET['panel'] == "profile")
							echo " active "; ?> ">
							حساب کاربری
						</a>
					</li>
					<?php
					global $isAdminPage; // متغییری که مشخص می کند در صفحه ادمین هستیم یا نه
		
					if ($this->hasAnyAccess() && !$isAdminPage ) {
						?>
						<li>
							<a href="admin.php" class="btn w-100  ">
								داشبورد مدیریت
							</a>
						</li>
						<?php
					}
					?>
				</ul>
			</div>


			<?php
		} else {


			?>
			<!-- Button trigger modal -->
			<button type="button" class="btn btn-secondary shadow  m-1" data-bs-toggle="modal" data-bs-target="#loginUserModal">
				ورود به حساب / ثبت نام
			</button>


			<?php
		}
	}
	protected function autenticate($tel, $pass)
	{
		// در این تابع فقط باید شماره تماس و رمز عبور چک شود
		if ($tel == "" && count($this->search(["id" => "!=''"])) <= 0)
			return true;
		$colValList = ["tel" => $tel, "pass" => $pass];
		if (count($this->search($colValList))) {
			return true;
		} else {
			return false;
		}
	}
	protected function autenticateById($tel, $id)
	{
		if ($tel == "" && count($this->search(["id" => "!=''"])) <= 0)
			return true;
		$colValList = ["tel" => $tel, "id" => $id, "status" => self::STATUS_ACTIVE];

		if (count($this->search($colValList))) {
			return true;
		} else {
			return false;
		}
	}
	protected function login($user_phone, $user_id, $remember = NULL)
	{
		// این دستور همیشه باید در ابتدای صفحه قبل از ارسال هدر قرار گیرد
		$_SESSION['user_phone'] = $user_phone;
		$_SESSION['user_id'] = $user_id;
		$this->isLogin = true;

		if (isset($remember)) {
			$phone = '' . $user_phone;
			$id = '' . $user_id;
			$expiry = 0 + time() + (86400 * 30);
			setcookie("user_phone", $phone, $expiry);
			setcookie("user_id", $id, $expiry);
			if (count($_COOKIE) === 0) {
				echo '<h1 class="alert alert-danger" role="alert">شما در تنظیمات مرورگر خود کوکی ها را مسدود کرده اید!</h1>';
			}
		}
	}
	protected function logout()
	{
		// این دستور همیشه باید در ابتدای صفحه قبل از ارسال هدر قرار گیرد
		$this->isLogin = false;
		$this->setDefaults();
		if (isset($_COOKIE['user_phone'])) {
			$tt = 0 + time() - 3600;
			$_COOKIE['user_phone'] = '';
			$_COOKIE['user_id'] = '';
			setcookie('user_phone', '', $tt);
			setcookie('user_id', '', $tt);
		}
		if (isset($_SESSION['user_phone'])) {
			$_SESSION['user_phone'] = NULL;
			unset($_SESSION['user_phone']);
			$_SESSION['user_id'] = NULL;
			unset($_SESSION['user_id']);
		}
		//echo 'logout';
	}
	public function checkLoginoutState()
	{
		// این دستور همیشه باید در ابتدای صفحه قبل از ارسال هدر قرار گیرد

		if (isset($_COOKIE['user_phone'])) {
			if ($this->autenticateById($_COOKIE['user_phone'], $_COOKIE['user_id'])) {
				$this->getByTel($_COOKIE['user_phone']);
				$this->isLogin = true;
			} else {
				$this->isLogin = false;
				$this->logout();
			}
		}
		if (isset($_SESSION['user_phone'])) {
			if ($this->autenticateById($_SESSION['user_phone'], $_SESSION['user_id'])) {
				$this->getByTel($_SESSION['user_phone']);
				$this->isLogin = true;
			} else {
				$this->isLogin = false;
				$this->logout();
			}
		}
	}
	public function hasAccess($checkingList = NULL)
	{
		if ($this->status == self::STATUS_DISACTIVE)
			return false;
		$thisAccessList = explode("\n", $this->access);
		// اگر نام دسترسی وارد نشود همه دسترسی ها چک می شود
		if (isset($checkingList)) {
			if (is_array($checkingList)) {
				foreach ($checkingList as $aItem) {
					if (!in_array($aItem, $thisAccessList)) {
						return false;
					}
				}
				return true;
			} else {
				if (in_array($checkingList, $thisAccessList))
					return true;
				else
					return false;
			}
		} else {

			return false;
		}
	}

	public function hasAnyAccess()
	{
		$vals = [];
		$res = false;
		//foreach(FINAL_ADMIN_MENUS as $item){
		foreach ($GLOBALS['adminMenus'] as $item) {
			if ($this->hasAccess($item['name'])) {
				$res = true;
				break;
			}
		}

		return $res;
	}



}

?>