<?php
session_start();
include '../../../auth_bootstrap.php';
sa_require_guest();

$err = '';
$ok  = '';
function after_login_redirect() {
    $base_url = '/mobile/';
    if (substr($base_url, -1) !== '/') {
        $base_url .= '/';
    }
    return $base_url;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first = trim($_POST['first_name'] ?? '');
    $last  = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $pass  = (string)($_POST['password'] ?? '');

    if (!$first || !$last || !$email || !$pass) {
        $err = 'Please fill all fields.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $err = 'Please enter a valid email.';
    } else {
        $sql = "SELECT id FROM " . TBL_USERS . " WHERE email = ? LIMIT 1";
        $stmt = $DB->prepare($sql);
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $exists = $stmt->get_result()->fetch_row();
        $stmt->close();

        if ($exists) {
            $err = 'This email is already registered.';
        } else {
            $hash = password_hash($pass, PASSWORD_BCRYPT);
            $role_id = 6;

            $sql = "INSERT INTO " . TBL_USERS . " (first_name,last_name,email,phone,password,role_id) VALUES (?,?,?,?,?,?)";
            $stmt = $DB->prepare($sql);
            $phone = $_POST['phone'] ?? null;
            $stmt->bind_param('sssssi', $first, $last, $email, $phone, $hash, $role_id);

            if ($stmt->execute()) {
                $user_id = $stmt->insert_id;
                $stmt->close();

                $full_name = $first . ' ' . $last;
                $pan_number = $_POST['pan_number'] ?? null;
                $company_name = $_POST['company_name'] ?? null;
                $address = $_POST['address'] ?? null;
                $reference = $_POST['how_heard'] ?? null;

                $sql2 = "INSERT INTO broker_kyc (name, email, phone, pan_number, company_name, address, reference) VALUES (?, ?, ?, ?, ?, ?, ?)";
                $stmt2 = $conn_broker->prepare($sql2);
                $stmt2->bind_param('sssssss', $full_name, $email, $phone, $pan_number, $company_name, $address, $reference);

                if ($stmt2->execute()) {
                    $stmt2->close();
                     $_SESSION['info_message'] = 'Registered successfully. Please sign in.';
					$redirect_url = after_login_redirect();
					header('Location: ' . $redirect_url);
					exit;
                } else {
                    $stmt2->close();
                    $err = 'Registration succeeded but failed to save broker KYC data.';
                }
            } else {
                $err = 'Registration failed. Please try again.';
                $stmt->close();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, minimal-ui, viewport-fit=cover">
	<meta name="theme-color" content="#2196f3">
	<link rel="shortcut icon" type="image/x-icon" href="../../../assets/images/favicon.png" />
	<title>Create Account • Broriser</title>

	<link rel="stylesheet" href="../../../assets/vendor/swiper/swiper-bundle.min.css">
	<link rel="stylesheet" type="text/css" href="../../../assets/css/style.css">
	<link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	<link href="https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@200;300;400;600;700;800;900&family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet">
</head>
<body class="gradiant-bg">
<div class="page-wraper">

	<div id="preloader"><div class="spinner"></div></div>

	<div class="content-body">
		<div class="container vh-100">
			<div class="welcome-area">
				<div class="bg-image bg-image-overlay" style="background-image: url(../../../assets/images/login/pic3.jpg);"></div>
				<div class="join-area">
					<div class="started">
						<h1 class="title">Create an Account</h1>
						<p>It only takes a minute</p>
						<?php if ($err): ?><div class="alert alert-danger mt-2 py-2"><?php echo h($err); ?></div><?php endif; ?>
					</div>

					<form method="post" autocomplete="on" novalidate>
						<div class="row">
							<div class="mb-3 col-md-6">
								<label class="form-label">First Name <span class="text-danger">*</span></label>
								<input name="first_name" type="text" class="form-control" placeholder="First Name" required value="<?php echo h($_POST['first_name'] ?? ''); ?>">
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">Last Name <span class="text-danger">*</span></label>
								<input name="last_name" type="text" class="form-control" placeholder="Last Name" required value="<?php echo h($_POST['last_name'] ?? ''); ?>">
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">Company Name</label>
								<input name="company_name" type="text" class="form-control" placeholder="Company Name" value="<?php echo h($_POST['company_name'] ?? ''); ?>">
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">Address</label>
								<input name="address" type="text" class="form-control" placeholder="Address" value="<?php echo h($_POST['address'] ?? ''); ?>">
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">PAN Number</label>
								<input name="pan_number" type="text" class="form-control" placeholder="PAN Number" value="<?php echo h($_POST['pan_number'] ?? ''); ?>">
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">Email <span class="text-danger">*</span></label>
								<input name="email" type="email" class="form-control" placeholder="Email" required value="<?php echo h($_POST['email'] ?? ''); ?>">
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">Mobile <span class="text-danger">*</span></label>
								<input name="phone" type="text" class="form-control" placeholder="Phone" required value="<?php echo h($_POST['phone'] ?? ''); ?>">
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">Password <span class="text-danger">*</span></label>
								<input name="password" type="password" class="form-control dz-password" placeholder="Password" required>
							</div>
							<div class="mb-3 col-md-6">
								<label class="form-label">How did you hear about us?</label>
								<input name="how_heard" type="text" class="form-control" placeholder="Referral, Social Media, etc." value="<?php echo h($_POST['how_heard'] ?? ''); ?>">
							</div>
						</div>
						<button class="btn btn-primary btn-block mb-3" type="submit">REGISTER</button>
					</form>
					<div class="d-flex align-items-center justify-content-center">
						<a href="../../login" class="btn-link d-block ms-3 text-underline">Signin here</a>
					</div>
				</div>
			</div>
		</div>
	</div>

</div>
<script src="../../../assets/js/jquery.js"></script>
<script src="../../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../../assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="../../../assets/js/dz.carousel.js"></script>
<script src="../../../assets/js/settings.js"></script>
<script src="../../../assets/js/custom.js"></script>
</body>
</html>
