<?php
session_start();
require_once '../include/Constants.php';
require_once "../vendor/autoload.php";
require_once "../include/DatabaseConn.php";
require_once "../models/User.php";
require_once '../models/Settings.php';
require_once '../models/USettings.php';
require_once '../include/GoogleAuthenticator.php';

$db = new DatabaseConn();
$link = $db->connect();

$user = User::getCurrentUser($link);
if (is_null($user)) {
    $url = $_SERVER['REQUEST_URI'];
    header("location: ../login?" . RETURN_URL . "=" . $url);
    die();
}

$settings = USettings::getSystemSettings($link, $user->getEmail());
if ($settings->getTwofa() && is_null($user->getFa())) {
    header("location: add-2fa");
    die();
}


if (isset($_POST['name'])) {
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    if ($name == null || ctype_alpha(preg_replace('/\s+/', '', $name)) == FALSE) {
        $error = 'Name is not valid. Name should contain strings only';
    } else if (strlen($name) <= 3) {
        $error = 'Name is too short';
    }
    $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
    if ($phone == null) {
        $error = 'Phone is not valid.';
    }
    $country = filter_input(INPUT_POST, 'country', FILTER_SANITIZE_STRING);
    if ($country == null || ctype_alpha(preg_replace('/\s+/', '', $country)) == FALSE || strcmp($country, NONE) == 0) {
        $error = 'Please select a country';
    }
    $stmt = mysqli_prepare($link, "update users set `name` = ?, phone = ?, country = ? WHERE email = '{$user->getEmail()}'");
    $stmt->bind_param("sss", $name, $phone, $country);
    $stmt->execute();
    if ($stmt->affected_rows === 1) {
        $success = "Successfully updated!";
    } else {
        $error = "Nothing to update";
    }
} else if (isset($_POST['password'])) {
    $old = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
    $password = filter_input(INPUT_POST, 'newPassword', FILTER_SANITIZE_STRING);
    if ($password == null || $password == FALSE) {
        $error = 'Password is not valid';
    } else if (strlen($password) < 8) {
        $error = 'Password is weak';
    } else if (strcmp($old, $user->getPassword()) !== 0) {
        $error = "Current password is not correct";
    } else {
        $stmt = mysqli_prepare($link, "update users set password = ? WHERE email = '{$user->getEmail()}'");
        $stmt->bind_param("s", $password);
        $stmt->execute();
        if ($stmt->affected_rows === 1) {
            $success = "Your password has been updated";
        } else {
            $error = "Nothing to update";
        }
    }
} else if (isset($_FILES['image'])) {
    $target_dir = IMG_UPLOAD_DIR;
    $s = substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
    $target_file = $target_dir . $s . filter_var(basename($_FILES["image"]["name"]), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);

    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if ($check !== false) {
        $uploadOk = 1;
    } else {
        $error = "File is not an image.";
        $uploadOk = 0;
    }

// Check if file already exists
    if (file_exists($target_file)) {
        $error = "Sorry, file already exists.";
        $uploadOk = 0;
    }

// Check file size
    if ($_FILES["image"]["size"] > 5000000) {
        $error = "Sorry, your file is too large.";
        $uploadOk = 0;
    }

// Allow certain file formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
        $error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    if (!isset($error)) {
        if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
            $success = "Operation was successful";
            $stmt = mysqli_prepare($link, "update users set image = ? WHERE email = '{$user->getEmail()}'");
            $stmt->bind_param("s", $target_file);
            $stmt->execute();
            if ($stmt->affected_rows === 1) {
                $success = "Your profile photo has been updated.";
            } else {
                $error = "Sorry, there was an error uploading your file.";
            }
        } else {
            $error = "Sorry, there was an error uploading your file.";
        }
    }
}
$user = User::getCurrentUser($link);
?>
	<!DOCTYPE html>
	<html lang="en">

	<head>
		<?php require_once './partials/head.php'; ?>
		<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" type="text/css" media="all" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/css/intlTelInput.min.css" />
      
	</head>

	<body class="ltr en">
		<div ui-view="" id="app" ng-class="{'app-mobile' : app.isMobile, 'app-invest' : app.isInvest, 'app-navbar-fixed' : app.layout.isNavbarFixed,
     'app-sidebar-fixed' : app.layout.isSidebarFixed, 'app-footer-fixed':app.layout.isFooterFixed}" class="ng-scope app-navbar-fixed app-sidebar-fixed" style="">
			<?php require_once './partials/sidebar.php'; ?>
				<div class="app-content ng-scope" ng-class="{loading: loading}">
					<!-- ngInclude: 'assets/views/partials/top-navbar.html' -->
					<?php require_once './partials/header_.php'; ?>
						<div data-ng-controller="PageCtrl" class="ng-scope">
						    
							<div data-ng-include=" 'assets/views/partials/main-content.html'" id="main_content" class="main-content ng-scope" ng-class="{'hidden' : hidePageContent, 'wrap-content-dashboard' : (currentPageId == 'app.dashboard')}" style="">
								<!-- uiView:  -->
								<div ui-view="" class="wrap-content container fade-in-up ng-scope" id="container">
									<!-- uiView:  -->
									<div ui-view="" class="smooth ng-scope">
										<!-- uiView:  -->
										<div ui-view="" class="ng-scope">
											<!-- ngInclude: undefined -->
											<data-ng-include src="'assets/views/partials/title.html'" style="margin-top: 10px" class="ng-scope">
											    <div data-ng-include=" 'assets/views/partials/alerts.html'" style="margin-top: 61px;" class="ng-scope">
											<div ng-controller="AlertCtrl" class="PopupAlertDiv ng-scope">
												<div class="container-fluid mt20" ng-show="alertsLen > 0">
													<div class="row">
														<div class="col-sm-12">
															<!-- ngRepeat: (id, alert) in alerts track by $index -->
															<div ng-repeat="(id, alert) in alerts track by $index" class="alert alert-block alert-success alert-type--welcome fade in" id="notice_20300006" data-ng-init="setNoticeAsShown(alert.id)">
																<!-- ngIf: alert.is_closable -->
																<button ng-hide="getInclude(alert.type) == 'alert-prompt.html'" data-ct-dismiss="alert" class="close ng-scope" ng-if="alert.is_closable" type="button" ng-click="profileAlertClose(alert)"></button>
																<!-- end ngIf: alert.is_closable -->
																<div class="PopupAlertDiv__content">
																	<!-- ngInclude: 'assets/views/tpl/' + getInclude(alert.type) --><span ng-include="'assets/views/tpl/' + getInclude(alert.type)" class="ng-scope"><div class="ng-scope">
                                                                            <h4 class="alert-heading margin-bottom-10">
                                                                                <span class="success-title ng-binding" ng-bind-html="('welcome_to_myfxtm' | translate)">Welcome to Ozz Capital - your personal client area.</span> </h4>
																	<p class="m0"> <b class="ng-binding">Your referral ID:  <a class="upgrade-to-text" style="cursor: pointer" data-clipboard-text="https://ozzcapital.com/?referral=irsgmyleigsuc@baybabes.com">
                                                                                        <span>Click to copy referral link</span>
                                                                                    </a> </b>
																		<br> </p>
																	<!-- ngIf: alert.data['30PctBonusAvailable'] || alert.data.switchToFxTmBonusAvailable -->
																</div>
																</span>
															</div>
														</div>
														<!-- end ngRepeat: (id, alert) in alerts track by $index -->
													</div>
												</div>
											</div>
										</div>
								</div>
												<div ng-hide="currentPageId === 'app.dashboard'" class="ng-scope">
													<section id="page-title" class="padding-top-15 padding-bottom-0 ng-scope" ng-controller="TitleCtrl">
														<div class="container-fluid">
															<div class="row">
																<div class="col-xs-12">
																	<h1 class="mainTitle">
                                                                <span ng-bind="title | translate" class="ng-binding">My Profile</span>
                                                                <!-- ngIf: openAccount.account_group === 'investor' --><!-- ngIf: subtitle -->
                                                            </h1> </div>
															</div>
														</div>
													</section>
												</div>
											</data-ng-include>
											<div class="container-fluid bg-white ng-scope" data-ng-controller="ProactiveChatOpenAccountCtrl">
												<div class="row">
													<div class="col-xs-12">
														<!-- ngIf: ::showMeHowForPage.videos.length -->
													</div>
												</div>
												<!-- Enter Mini -->
												<form method="POST" action="profile" name="ChangePasswordForm" class="mt35 ng-scope ng-dirty ng-submitted ng-valid-compare-to ng-invalid ng-invalid-at_least_one_lower ng-invalid-at_least_one_digit ng-invalid-length_range ng-valid-parse" novalidate="" autocomplete="off" fxtm-form-container="" style="">
	<input type="password" style="display:none">
	<!-- ngIf: changePassForm.isSendPinStep -->
	<!-- ngIf: changePassForm.isCheckPinStep -->
	<!-- ngIf: changePassForm.isSaveNewPassStep -->
	<div class="panel panel-white change-password-panel ng-scope" data-ng-if="changePassForm.isSaveNewPassStep" style="">
		<div class="panel-body p0">
			<div class="has-success change-password-input-control form-group form-group my-input-field ng-valid ng-valid-compare-to" name="password2" data-ng-model="changePassForm.body.password2" render-show-pass-btn="true" compare-to="changePassForm.body.password" success-message="" label="Re-enter New Password">
				<label class="control-label"><span data-ng-bind="::attr.label" class="ng-binding">Name</span>
					<!-- ngIf: ::attr.helpText -->
				</label>
				<div class="input-group full-width">
					 <input id="formFirst" name="name" type="text" value="<?php echo $user->getName(); ?>" class="form-control" placeholder="Name">
					<!-- end ngIf: :: renderShowPassBtn -->
				</div>
				<!-- ngIf: ::attr.subscribeText -->
				<!-- ngIf: :: extraData.validationIndicators -->
				<!-- ngRepeat: (e, b) in ngModelCtrl.$error -->
				<!-- ngIf: attr.successMessage -->
			</div>
			<div class="has-success change-password-input-control form-group form-group my-input-field ng-valid ng-valid-compare-to" name="password2" data-ng-model="changePassForm.body.password2" render-show-pass-btn="true" compare-to="changePassForm.body.password" success-message="" label="Re-enter New Password">
				<label class="control-label"><span data-ng-bind="::attr.label" class="ng-binding">Phone</span>
					<!-- ngIf: ::attr.helpText -->
				</label>
				<div class="input-group full-width">
					<input id="phone" name="phone" type="text" value="<?php echo $user->getPhone(); ?>"  class="form-control" placeholder="Phone">
					<!-- end ngIf: :: renderShowPassBtn -->
				</div>
				<!-- ngIf: ::attr.subscribeText -->
				<!-- ngIf: :: extraData.validationIndicators -->
				<!-- ngRepeat: (e, b) in ngModelCtrl.$error -->
				<!-- ngIf: attr.successMessage -->
			</div>
			<div class="has-success change-password-input-control form-group form-group my-input-field ng-valid ng-valid-compare-to" name="password2" data-ng-model="changePassForm.body.password2" render-show-pass-btn="true" compare-to="changePassForm.body.password" success-message="" label="Re-enter New Password">
				<label class="control-label"><span data-ng-bind="::attr.label" class="ng-binding">Country</span>
					<!-- ngIf: ::attr.helpText -->
				</label>
				<div class="input-group full-width">
					   <select name="country" id="country" class="placeholder custom-select form-control">
                           <?php require_once './../include/countries.php'; ?>
                        </select>
					<!-- end ngIf: :: renderShowPassBtn -->
				</div>
				<!-- ngIf: ::attr.subscribeText -->
				<!-- ngIf: :: extraData.validationIndicators -->
				<!-- ngRepeat: (e, b) in ngModelCtrl.$error -->
				<!-- ngIf: attr.successMessage -->
			</div>
			<button class="btn btn-orange ng-scope ladda-button" data-ng-click="submit($event, changePassForm.saveNewPass)" data-submit-button="" ladda="changePassForm.isFormSendingInProgress" data-style="zoom-in"><span class="ladda-label">
              Submit            </span><span class="ladda-spinner"></span></button>
		</div>
	</div>
	<!-- end ngIf: changePassForm.isSaveNewPassStep -->
</form>
												<!-- End Mini -->
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
				</div>
				<!-- ngInclude: 'assets/views/partials/footer.html' -->
				<footer data-ng-include=" 'assets/views/partials/footer.html'" id="footer" class="ng-scope">
					<div class="footer-inner ng-scope">
						<div class="pull-left">
							<p class="m0"> ©
								<?php echo APP_NAME; ?> 2011-2021
									<br /> </p>
							<!-- ngIf: footerAddText -->
						</div>
						<div class="pull-right"> <span class="go-top" ng-click="toTheTop()"><i style="font-size: 30px;" class="icon-angle-up"></i></span> </div>
						<!-- ngIf: !isMobileApp -->
						<!-- ngInclude: 'assets/views/partials/livechat.html' -->
						<!-- end ngIf: !isMobileApp -->
					</div>
				</footer>
		</div>
		<?php require_once './partials/scripts_.php'; ?>
		 <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/intlTelInput.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
        <script>
            (function () {


<?php if (isset($_POST['country'])) { ?>
                    var theValue = '<?php echo($_POST['country']); ?>';
                    var query = 'select#country option[value="' + theValue + '"]';
                    $(query).attr("selected", true);
    <?php
} else {
    ?>
                    var theValue = '<?php echo ($user->getCountry()); ?>';
                    var query = 'select#country option[value="' + theValue + '"]';
                    $(query).attr("selected", true);
<?php } ?>
                $(".placeholder").select2({
                    placeholder: "Make a Selection"
                });
                var input = document.querySelector("#phone");
                let iti = window.intlTelInput(input, {
                    initialCountry: "auto",
                    geoIpLookup: function (success, failure) {
                        $.get("https://ipinfo.io", function () {}, "jsonp").always(function (resp) {
                            var countryCode = (resp && resp.country) ? resp.country : "US";
                            success(countryCode);
                        });
                    },
                    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.min.js"
                });

                $('#btnup').click(function (e) {
                    e.preventDefault();
                    let number = iti.getNumber();
                    console.log(number);
                    $('#phone').val(number);
                    $('#upForm').submit();
                });
                $('#fileUpload').click(function () {
                    $('#image').trigger('click');
                });
                $('#image').change(function () {
                    $('#imgFm').trigger('submit');
                });
            })();
            $('a[href="profile"]').addClass('active');
        </script>
          <script>
        
 $('#k2').addClass('active');
        </script>
	</body>

	</html>