<?php
@session_start();
include('./includes/config.php');
$R='';if(!empty($_GET['ref'])){$R=base64_decode(mysqli_real_escape_string($ahk_conn,$_GET['ref']));}
include('./template/ahkweb/authentication-signup.php');

function O($P,$ahk_conn,$R,$webdata,$ENDPOINT,$tng_wa_apikey,$tng_wa_sender){
    $N=mysqli_real_escape_string($ahk_conn,$P['name']);
    $E=mysqli_real_escape_string($ahk_conn,$P['email']);
    $M=mysqli_real_escape_string($ahk_conn,$P['phone']);
    $T=mysqli_real_escape_string($ahk_conn,$P['usertype']);
    $PW=mysqli_real_escape_string($ahk_conn,$P['password']);
    $CPW=mysqli_real_escape_string($ahk_conn,$P['cpassword']);

    if(strtolower($T)=="admin"){echo '<script>$(function(){Swal.fire("Oops!","You cannot register as ADMIN!","error");});</script>';exit;}
    if(mysqli_num_rows(mysqli_query($ahk_conn,"SELECT id FROM users WHERE phone='$M' OR email='$E'"))>0){echo '<script>$(function(){Swal.fire("Oops!","Email or Phone already exists!","error");});</script>';exit;}
    if($PW!==$CPW){echo '<script>$(function(){Swal.fire("Oops!","Password and Confirm Password do not match!","error");});</script>';exit;}

    // ✅ OTP on/off check
    if(strtolower($webdata['otp_option'])=="yes"){
        $O=rand(100000,999999);
        $_SESSION['s_otp']=$O;
        $_SESSION['s_data']=['n'=>$N,'e'=>$E,'p'=>$M,'t'=>$T,'r'=>$R,'pw'=>$PW];
        $msg=urlencode("Your OTP for registration is: $O");
        $ftr=strtoupper($_SERVER['SERVER_NAME']);
        $url="$ENDPOINT?api_key=$tng_wa_apikey&sender=$tng_wa_sender&number=91$M&message=$msg&footer=$ftr";
        $resp=@json_decode(file_get_contents($url),true);
        if(!empty($resp['status'])){
            echo '<script>$(function(){Swal.fire({title:"OTP Sent!",html:"Enter OTP sent to WhatsApp:",input:"text",inputLabel:"OTP",inputPlaceholder:"Enter OTP",confirmButtonText:"Verify",allowOutsideClick:false}).then((r)=>{if(r.isConfirmed){var f=document.createElement("form");f.method="POST";f.action="";var i=document.createElement("input");i.type="hidden";i.name="v_otp";i.value=r.value;f.appendChild(i);document.body.appendChild(f);f.submit();}});});</script>';
        }else{
            echo '<script>$(function(){Swal.fire("Error!","Failed to send OTP. Try later.","error");});</script>';
        }
    } else {
        // Direct register without OTP
        $VP=password_hash($PW,PASSWORD_DEFAULT);
        $oid="AHK_".rand(100000,999999);
        $dt=date("d-m-Y");
        $q="INSERT INTO `users`(`name`,`phone`,`email`,`password`,`type`,`status`,`referred_by`,`order_id`,`date`) VALUES('$N','$M','$E','$VP','$T','{$webdata['payment_status']}','$R','$oid','$dt')";
        $res=mysqli_query($ahk_conn,$q);
        if($R!=''){mysqli_query($ahk_conn,"INSERT INTO referal (`phone`,`referred_by`,`txn_no`,`referral_balance`,`status`) VALUES('$M','$R','REF".rand(10000,99999)."','".$webdata['ref_bal']."','1')");}
        if($res){
            $msg2=urlencode("✅ Registration Successful!\nPhone/ID:$M\nPassword:$PW");
            $ftr=strtoupper($_SERVER['SERVER_NAME']);
            @file_get_contents("$ENDPOINT?api_key=$tng_wa_apikey&sender=$tng_wa_sender&number=91$M&message=$msg2&footer=$ftr");
            echo '<script>$(function(){Swal.fire({title:"Success!",html:"Account created!<br>Phone/ID:<b>'.$M.'</b><br>Password:<b>'.$PW.'</b>",icon:"success",confirmButtonText:"Login Now"}).then(()=>{window.location.href="login.php";});});</script>';
        }else{
            echo '<script>$(function(){Swal.fire("Error!","Something went wrong! Try again.","error");});</script>';
        }
    }
}

if(!empty($_POST['phone']) && !isset($_POST['v_otp'])){O($_POST,$ahk_conn,$R,$webdata,$ENDPOINT,$tng_wa_apikey,$tng_wa_sender);}

if(!empty($_POST['v_otp'])){
    $V=mysqli_real_escape_string($ahk_conn,$_POST['v_otp']);
    if(isset($_SESSION['s_otp']) && $V==$_SESSION['s_otp']){
        $D=$_SESSION['s_data'];
        $VP=password_hash($D['pw'],PASSWORD_DEFAULT);
        $oid="AHK_".rand(100000,999999);
        $dt=date("d-m-Y");
        $res=mysqli_query($ahk_conn,"INSERT INTO `users`(`name`,`phone`,`email`,`password`,`type`,`status`,`referred_by`,`order_id`,`date`) VALUES ('".$D['n']."','".$D['p']."','".$D['e']."','$VP','".$D['t']."','{$webdata['payment_status']}','".$D['r']."','$oid','$dt')");
        if($D['r']!=''){mysqli_query($ahk_conn,"INSERT INTO referal (`phone`,`referred_by`,`txn_no`,`referral_balance`,`status`) VALUES('".$D['p']."','".$D['r']."','REF".rand(10000,99999)."','".$webdata['ref_bal']."','1')");}
        if($res){
            $msg2=urlencode("✅ Registration Successful!\nPhone/ID: ".$D['p']."\nPassword: ".$D['pw']);
            $ftr=strtoupper($_SERVER['SERVER_NAME']);
            @file_get_contents("$ENDPOINT?api_key=$tng_wa_apikey&sender=$tng_wa_sender&number=91".$D['p']."&message=$msg2&footer=$ftr");
            echo '<script>$(function(){Swal.fire({title:"Success!","text":"Account created successfully!","icon":"success"}).then(()=>{window.location.href="login.php";});});</script>';
        }else{
            echo '<script>$(function(){Swal.fire("Error!","Something went wrong!","error");});</script>';
        }
        unset($_SESSION['s_otp'],$_SESSION['s_data']);
    }else{
        echo '<script>$(function(){Swal.fire("Invalid OTP","Entered OTP is incorrect.","error");});</script>';
    }
}
?>
