<?php  
session_start();  
require_once '_inc/dbconn.php';  
require_once '_inc/function.php';  
  
/* ========= HELPERS ========= */  
function generateAccountNumber($con){  
    do {  
        $acc = '203' . rand(1000000, 9999999);  
        $check = mysqli_query($con, "SELECT id FROM users WHERE account_number='$acc'");  
    } while(mysqli_num_rows($check) > 0);  
    return $acc;  
}  
  
function generateOTP(){  
    return rand(100000, 999999);  
}  
  
/* ========= REGISTER ========= */  
if(isset($_POST['registerBtn'])){  
  
    $fullname = mysqli_real_escape_string($con, $_POST['fullname']);  
    $email = mysqli_real_escape_string($con, $_POST['email']);  
    $phone_full = mysqli_real_escape_string($con, $_POST['phone_full']);  
    $country = mysqli_real_escape_string($con, $_POST['country']);  // Now comes from the visible <select>
    $country_code = mysqli_real_escape_string($con, $_POST['country_code']);  
    $password_raw = $_POST['password'];  
    $confirm_password = $_POST['confirm_password'];
    $pin = $_POST['pin'];  
  
    // VALIDATION  
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){  
        $error = "Invalid email format";  
    } elseif(!preg_match('/^[0-9]{4}$/', $pin)){  
        $error = "PIN must be exactly 4 digits";  
    } elseif(strlen($password_raw) < 6){  
        $error = "Password must be at least 6 characters";  
    } elseif($password_raw !== $confirm_password){
        $error = "Passwords do not match";
    } else {  
  
        $password = password_hash($password_raw, PASSWORD_DEFAULT);  
  
        $check = mysqli_query($con, "SELECT id FROM users WHERE email='$email'");  
        if(mysqli_num_rows($check) > 0){  
            $error = "Email already exists";  
        } else {  
  
            $account_number = generateAccountNumber($con);  
            $otp = generateOTP();  
            $expiry = date("Y-m-d H:i:s", strtotime("+10 minutes"));  
  
            $sql = "INSERT INTO users   
            (fullname,email,country,country_code,phone_number,password,account_number,account_pin,otp_code,otp_expiry,verified)  
            VALUES  
            ('$fullname','$email','$country','$country_code','$phone_full','$password','$account_number','$pin','$otp','$expiry',0)";  
  
            if(mysqli_query($con, $sql)){  
                sendSystemEmail($email, $fullname, "OTP Verification", "Your OTP is: $otp");  
                $_SESSION['verify_email'] = $email;  
                $success = "Verification code sent to your email.";  
            } else {  
                $error = "Registration failed";  
            }  
        }  
    }  
}  
  
/* ========= VERIFY ========= */  
if(isset($_POST['verifyBtn']) || isset($_POST['otp'])){  
    $otp = is_array($_POST['otp']) ? implode('', $_POST['otp']) : $_POST['otp'];
    $otp = mysqli_real_escape_string($con, $otp);
    $email = $_SESSION['verify_email'] ?? '';  
  
    $sql = "SELECT * FROM users WHERE email='$email' AND otp_code='$otp' AND otp_expiry > NOW()";  
    $result = mysqli_query($con, $sql);  
  
    if(mysqli_num_rows($result) == 1){  
        
        $user = mysqli_fetch_assoc($result);

        mysqli_query($con, "UPDATE users SET verified=1, otp_code=NULL WHERE email='$email'");  
  
        // Send Account Details Email
        $subject = "Welcome! Your Account Details";
        $message = "Hello {$user['fullname']},\n\nYour account has been successfully verified.\n\n"
                 . "Here are your account details:\n"
                 . "Account Number: {$user['account_number']}\n"
                 . "Login Email: {$user['email']}\n"
                 . "Country: {$user['country']}\n\n"
                 . "Thank you for joining us!";
                 
        sendSystemEmail($email, $user['fullname'], $subject, $message);

        // Auto-login
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_email'] = $user['email'];

        unset($_SESSION['verify_email']);  
  
        header("Location: index.php?verified=1");  
        exit();  
  
    } else {  
        $error = "Invalid or expired OTP";  
    }  
}  
  
/* ========= RESEND ========= */  
if(isset($_POST['resendOtp'])){  
    $email = $_SESSION['verify_email'] ?? '';  
  
    if($email){  
        $otp = generateOTP();  
        $expiry = date("Y-m-d H:i:s", strtotime("+10 minutes"));  
  
        mysqli_query($con, "UPDATE users SET otp_code='$otp', otp_expiry='$expiry' WHERE email='$email'");  
  
        sendSystemEmail($email, '', "OTP Resend", "Your new OTP is: $otp");  
        $success = "New OTP sent.";  
    }  
}  
?>  
  
<?php include 'h_header.php'; ?>  
  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/css/intlTelInput.min.css">  
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/intlTelInput.min.js"></script>  
  
<style>  
body{  
    font-family: 'Inter', sans-serif;  
    background: linear-gradient(135deg,#eef2f7,#f8fbff);  
}  
  
.page-wrap{  
    min-height:100vh;  
    display:flex;  
    justify-content:center;  
    align-items:flex-start;  
    padding-top:80px;  
    padding-bottom: 40px;
}  
  
.card{  
    width:100%;  
    max-width:420px;  
    background:#fff;  
    padding:25px;  
    border-radius:16px;  
    box-shadow:0 10px 30px rgba(0,0,0,0.08);  
}  
  
.header{  
    display:flex;  
    justify-content:space-between;  
    align-items:center;  
    margin-bottom:20px;  
}  
  
.login-btn{  
    background:#0a1f44;  
    color:#fff;  
    padding:10px 15px;  
    border-radius:8px;  
    text-decoration:none;  
}  
  
input, select{  
    width:100%;  
    padding:14px;  
    margin-bottom:12px;  
    border-radius:10px;  
    border:1px solid #ddd;  
    box-sizing: border-box; 
    font-size: 15px;
    background-color: #fff;
}  
  
input:focus, select:focus{  
    border-color:#1565d8;  
    box-shadow:0 0 0 2px rgba(21,101,216,0.1);  
    outline:none;  
}  

.iti { width: 100%; margin-bottom: 12px; }
.iti input { margin-bottom: 0; }
  
button{  
    width:100%;  
    padding:14px;  
    background:#1565d8;  
    color:#fff;  
    border:none;  
    border-radius:10px;  
    font-weight:600;  
    cursor: pointer;
    margin-top: 5px;
}  
  
button:hover{background:#0d47a1;}  
button:disabled { background:#a0c4ff; cursor: not-allowed; }
  
.otp-wrapper{display:flex;gap:8px; margin-bottom: 15px;}  
.otp-box{text-align:center;font-size:18px;height:50px; margin-bottom: 0;}  
  
.alert{padding:10px;margin-bottom:10px;border-radius:8px;}  
.error{background:#ffe5e5; color: #d32f2f;}  
.success{background:#e6ffed; color: #2e7d32;}  
</style>  
  
<div class="page-wrap">  
<div class="card">  
  
<div class="header">  
   <!------<img src="assets/logo.png" height="40" alt="Logo">---->  
    <a href="index.php" class="login-btn">Login</a>  
</div>  
  
<?php if(isset($error)) echo "<div class='alert error'>$error</div>"; ?>  
<?php if(isset($success)) echo "<div class='alert success'>$success</div>"; ?>  
  
<?php if(!isset($_SESSION['verify_email'])): ?>  
  
<form method="post" id="registerForm">  
  
    <input name="fullname" placeholder="Full Name" required>  
    <input name="email" type="email" placeholder="Email" required>  
    
    <select name="country" id="country_select" required>
        <option value="" disabled selected>Select your country</option>
        </select>
    
    <input id="phone" type="tel" required>  
    
    <input type="hidden" name="phone_full" id="phone_full">  
    <input type="hidden" name="country_code" id="country_code">  
    
    <input type="password" name="password" id="pass" placeholder="Password" required minlength="6">  
    <input type="password" name="confirm_password" id="confirm_pass" placeholder="Confirm Password" required minlength="6">  
    
    <input name="pin" maxlength="4" placeholder="4-digit PIN" required pattern="\d{4}" title="Please enter exactly 4 digits">  
    
    <button type="submit" name="registerBtn">Create Account</button>  
  
</form>  
  
<?php else: ?>  
  
<form method="post" id="otpForm">  
    <div class="otp-wrapper">  
        <input class="otp-box" type="text" maxlength="1" required>  
        <input class="otp-box" type="text" maxlength="1" required>  
        <input class="otp-box" type="text" maxlength="1" required>  
        <input class="otp-box" type="text" maxlength="1" required>  
        <input class="otp-box" type="text" maxlength="1" required>  
        <input class="otp-box" type="text" maxlength="1" required>  
    </div>  
    <input type="hidden" name="otp" id="otp_hidden">  
    <button type="submit" name="verifyBtn">Verify</button>  
</form>

<form method="post" style="margin-top: 10px;">
    <button type="submit" name="resendOtp" id="resendBtn" disabled>  
        Resend in <span id="timer">60</span>s
    </button>  
</form>  
  
<?php endif; ?>  
  
</div>  
</div>  
  
<script>  
const phoneInput = document.querySelector("#phone");
const countrySelect = document.querySelector("#country_select");

if(phoneInput) {
    // 1. Initialize intl-tel-input
    const iti = window.intlTelInput(phoneInput, {  
        initialCountry: "auto",  
        separateDialCode: true,  
        geoIpLookup: cb => {  
            fetch("https://ipapi.co/json")  
            .then(res => res.json())  
            .then(data => {
                cb(data.country_code);
            })  
            .catch(() => cb("US"));  
        },
        utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js"
    });  
      
    // 2. Populate Country Dropdown using intl-tel-input's built-in data
    // This allows us to use emoji flags without external libraries or huge HTML lists
    const countryData = window.intlTelInputGlobals.getCountryData();
    
    countryData.forEach((country) => {
        const option = document.createElement("option");
        option.value = country.name; 
        
        // Convert ISO2 to Emoji Flag
        const iso2 = country.iso2.toUpperCase();
        const flagEmoji = iso2.replace(/./g, char => String.fromCodePoint(char.charCodeAt(0) + 127397));
        
        option.text = `${flagEmoji} ${country.name}`;
        countrySelect.appendChild(option);
    });

    // 3. Keep Dropdown & Phone Input In Sync
    // Wait for auto-lookup to finish before setting initial select value
    phoneInput.addEventListener('countrychange', function(e) {
        const currentCountry = iti.getSelectedCountryData();
        countrySelect.value = currentCountry.name;
    });

    // When user changes the dropdown, update the phone input flag automatically!
    countrySelect.addEventListener("change", function() {
        const selectedCountryName = this.value;
        const matchingCountryData = countryData.find(c => c.name === selectedCountryName);
        if(matchingCountryData) {
            iti.setCountry(matchingCountryData.iso2);
        }
    });

    // 4. Form Submit Interception
    document.getElementById("registerForm").addEventListener("submit", function(e){  
        const pass = document.getElementById("pass").value;
        const confirmPass = document.getElementById("confirm_pass").value;
        
        if(pass !== confirmPass) {
            e.preventDefault();
            alert("Passwords do not match!");
            return;
        }

        if(!iti.isValidNumber()){  
            e.preventDefault();  
            alert("Please enter a valid phone number for the selected country.");  
            return;  
        }  
      
        // Pass phone info to hidden inputs
        document.getElementById("phone_full").value = iti.getNumber();  
        document.getElementById("country_code").value = "+" + iti.getSelectedCountryData().dialCode;  
    });
}
  
// OTP AUTO INPUT
const boxes = document.querySelectorAll(".otp-box");  
const hiddenOtp = document.getElementById("otp_hidden");  
const otpForm = document.getElementById("otpForm");

if(boxes.length > 0) {
    boxes.forEach((b, i) => {  
        b.addEventListener("input", (e) => {  
            b.value = b.value.replace(/[^0-9]/g, '');
            if(b.value && i < boxes.length - 1){  
                boxes[i+1].focus();  
            }  
            let code = [...boxes].map(x => x.value).join('');  
            hiddenOtp.value = code;  
      
            if(code.length === 6){  
                otpForm.submit();  
            }  
        });

        b.addEventListener("keydown", (e) => {
            if (e.key === "Backspace" && !b.value && i > 0) {
                boxes[i-1].focus();
            }
        });
    });  
}
  
// RESEND TIMER  
let t = 60;  
let timerDisplay = document.getElementById("timer");  
let resendBtn = document.getElementById("resendBtn");  
  
if(timerDisplay && resendBtn){  
    let countdown = setInterval(() => {  
        t--;  
        timerDisplay.innerText = t;  
        if(t <= 0){  
            clearInterval(countdown);  
            resendBtn.disabled = false;  
            resendBtn.innerText = "Resend OTP";  
        }  
    }, 1000);  
}  
</script>  
  
<?php include 'h_footer.php'; ?>
