<?php
require_once('../database/header.php');
if($userdata['status']=='paywait'){
echo '<script>
window.location = "paywait.php"
</script>
';	
}
?>
<!-- Begin Page Content -->
<div class="main-panel">
<div class="content-wrapper">
    
<div class="row">
<div class="col-md-12 stretch-card">    
<?php if($userdata['usertype']!="apipartner" AND $userdata['usertype']!="retailer" ){?> 

<?php
require_once('../database/config.php');

// Ensure password column is long enough for Bcrypt hashes
try {
    $conn->exec("ALTER TABLE loginusers MODIFY password VARCHAR(255)");
} catch (Exception $e) {}

if (isset($_POST['register']) && 
    !empty($_POST['mobile_no']) && 
    !empty($_POST['password']) && 
    !empty($_POST['usertype'])) {

    // Check if username/mobile is unique
    $ussql = $conn->prepare("SELECT COUNT(*) FROM loginusers WHERE username = ?");
    $ussql->execute([$_POST['mobile_no']]); 
    $msql = $conn->prepare("SELECT COUNT(*) FROM loginusers WHERE mobile_no = ?");
    $msql->execute([$_POST['mobile_no']]);

    // Dummy checks for removed unique fields to skip errors if table constraints exist, 
    // assuming we insert unique dummy values or just bypass if not unique constraint
    $esql_count = 0; 
    $psql_count = 0;
    $usql_count = 0;
    
    // Hash the password
    $hash = password_hash($_POST['password'], PASSWORD_DEFAULT);

    // Prepare Dummy Data
    $dummy_email = $_POST['mobile_no'] . "@example.com";
    $dummy_pan = "PAN" . substr(time(), -5);
    $dummy_uid = "UID" . substr(time(), -5);
    $dummy_name = "User " . $_POST['mobile_no'];
    $dummy_shop = "Shop " . $_POST['mobile_no'];
    $telegram_id = $_POST['telegram_id'] ?? '';


// (Removed residual code block)

// Check if all fields are unique and user type is valid
    // Check if user is unique
    if ($ussql->fetchColumn() == 0 && $msql->fetchColumn() == 0) {

    // Insert user data into the database
    // We kept the structure but passing dummy data for removed fields
    // Attempting to add telegram_id column if not exists (silent fail/success)
    try { $conn->exec("ALTER TABLE loginusers ADD COLUMN telegram_id VARCHAR(255) DEFAULT NULL"); } catch(Exception $e){}

    $sql = "INSERT INTO `loginusers` (`username`, `password`, `owner_name`, `shop_name`, `mobile_no`, `email_id`, `pan_no`, `uid_no`, `address`, `state`, `transactions_limit`, `subscription_date`, `pin_code`, `usertype`, `createby`, `date_time`, `status`, `telegram_id`) 
            VALUES (:username, :password, :owner_name, :shop_name, :mobile_no, :email_id, :pan_no, :uid_no, :address, :state, :transactions_limit, :subscription_date, :pin_code, :usertype, :createby, :date_time, :status, :telegram_id)";

    $status = "approved";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(":username", $_POST['mobile_no']);
    $stmt->bindParam(":password", $hash);
    $stmt->bindParam(":owner_name", $dummy_name);
    $stmt->bindParam(":shop_name", $dummy_shop);
    $stmt->bindParam(":mobile_no", $_POST['mobile_no']);
    $stmt->bindParam(":email_id", $dummy_email);
    $stmt->bindParam(":pan_no", $dummy_pan);
    $stmt->bindParam(":uid_no", $dummy_uid);
    $stmt->bindValue(":address", "N/A");
    $stmt->bindValue(":transactions_limit", "100000");
    $stmt->bindValue(":subscription_date", date('Y-m-d', strtotime('+1 year')));
    $stmt->bindValue(":state", "1");
    $stmt->bindValue(":pin_code", "000000");
    $stmt->bindParam(":usertype", $_POST['usertype']);
    $stmt->bindParam(":createby", $userdata['username']);
    $stmt->bindParam(":date_time", date('Y-m-d H:i:s'));
    $stmt->bindParam(":status", $status);
    $stmt->bindParam(":telegram_id", $telegram_id);

if ($stmt->execute()) {
    // Send SMS notification
    $sms_number = $_POST['mobile_no'];
    $msg = 'Dear ' . $dummy_name . ', Your Username: ' . $_POST['mobile_no'] . ', Password: ' . $_POST['password'] . ', Now Login: ' . $_SERVER['SERVER_NAME'];
    require_once('../database/sendsms.php');
    
    // AUTO-ADD RSPay MERCHANT for this user
    try {
        // Generate a unique API Key for the user's RSPay integration (internal use)
        // This key is what THEY will use to call YOUR system, distinct from your actual RSPay key
        $user_rspay_key = 'sk_' . bin2hex(random_bytes(16));
        $merchant_name = 'RSPay';
        $status = 'Active';
        $last_sync = date('Y-m-d H:i:s');
        // Use mobile number as their specific "Merchant ID" reference in your system or auto-gen one
        $user_merchant_id = 'MER_' . time() . rand(100,999); 
        
        $sql_merchant = "INSERT INTO `add_merchant`(`user`, `user_id`, `merchant_name`, `status`, `last_sync`, `access_token`, `merchant_id`) 
                         VALUES (:user, :user_id, :merchant_name, :status, :last_sync, :access_token, :merchant_id)";
        
        // Fetch the new user's ID
        $new_user_stmt = $conn->prepare("SELECT id FROM loginusers WHERE username = ?");
        $new_user_stmt->execute([$_POST['mobile_no']]);
        $new_user_id = $new_user_stmt->fetchColumn();
        
        $stmt_m = $conn->prepare($sql_merchant);
        $stmt_m->bindParam(":user", $_POST['mobile_no']); // Username
        $stmt_m->bindParam(":user_id", $new_user_id);
        $stmt_m->bindParam(":merchant_name", $merchant_name);
        $stmt_m->bindParam(":status", $status);
        $stmt_m->bindParam(":last_sync", $last_sync);
        $stmt_m->bindParam(":access_token", $user_rspay_key); // This acts as their Secret Key
        $stmt_m->bindParam(":merchant_id", $user_merchant_id); // This acts as their Merchant ID
        
        $stmt_m->execute();
        
    } catch (Exception $e) {
        // Log error but don't fail the whole registration
        // error_log("Failed to auto-add RSPay merchant: " . $e->getMessage());
    }

    $success = 1;
}
} else {
$invalid = 1; // Invalid registration attempt
}
} else {
$invalid = 0;
$success = 0;
}
?>

<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3 bg-primary">
<h6 class="m-0 font-weight-bold text-white">创建用户</h6>
</div>
<div class="card-body">
  
<?php if($success==1){ 
    echo '<div class="alert alert-success" role="alert"><strong>'.strtoupper($usertype).'!</strong> 创建成功！正在重定向到商户页面...</div>';
    echo '<script>setTimeout(function(){ window.location.href="manage-merchant.php?user=' . $_POST['mobile_no'] . '"; }, 1000);</script>';
} ?>
<?php if($invalid==1){ echo '<div class="alert alert-danger" role="alert">无效或数据已存在！</div>';} ?>
<?php if(isset($coupon) && $coupon==1){ echo '<div class="alert alert-danger" role="alert">无效优惠券或 NSDL 费率！</div>';} ?>

<form class="user" action="" method="POST">

<div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
        <h6 class="m-0 font-weight-bold text-dark">用户 ID（手机号码）</h6> 
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text">YAN8810</span>
            </div>
            <input required="required" type="text" class="form-control" placeholder="输入号码" id="mobile_part" maxlength="10">
            <input type="hidden" name="mobile_no" id="full_mobile_no">
        </div>
    </div>

    <div class="col-sm-6">
        <h6 class="m-0 font-weight-bold text-dark">密码</h6> 
        <input required="required" type="text" class="form-control" placeholder="密码" name="password" value="">
    </div>
</div>

<div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
        <h6 class="m-0 font-weight-bold text-dark">Telegram ID</h6> 
        <input type="text" class="form-control" placeholder="Telegram ID" name="telegram_id" value="">
    </div>
   
    <div class="col-sm-6">
        <h6 class="m-0 font-weight-bold text-dark">账户类型</h6> 
        <select class="form-control select" name="usertype" required>
            <option value="">--选择账户类型--</option>
            <option value="retailer">零售商</option>
            <option value="apipartner">API 合作伙伴</option>
            <option value="wl">白标</option>
        </select>
    </div>
</div>

<div class="form-group row">
    <div class="col-sm-6">
         <input type="submit" name="register" value="创建用户" class="btn btn-primary btn-user btn-block">
    </div>
</div>


</form>

<script>
document.getElementById('mobile_part').addEventListener('input', function() {
    var prefix = "YAN8810";
    var entered = this.value;
    document.getElementById('full_mobile_no').value = prefix + entered;
});
</script>			  
			  
</div>
</div>
<?php }?>
</div>

  <!-- End of Main Content -->
</div>   
<?php
require_once('../database/footer.php');
?>