<?php
	session_start();
	if($_SESSION['unohs'] == null){
		header("location:index.php?msg=unauthorized");
	}
?>
<?php
	include ("conn.php");

	// site_settings Table (না থাকলে নিজে থেকেই তৈরি হবে)
	$conn->query("
		CREATE TABLE IF NOT EXISTS site_settings (
			setting_key VARCHAR(50) PRIMARY KEY,
			setting_value VARCHAR(255)
		)
	");

	$message = '';
	$message_type = '';

	if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_default_code') {
		$defaultCode = trim($_POST['default_invitation_code'] ?? '');
		$defaultCode = preg_replace('/[^a-zA-Z0-9]/', '', $defaultCode);

		if ($defaultCode === '') {
			$message = '❌ খালি রাখা যাবে না — একটা সঠিক Owncode দিতে হবে।';
			$message_type = 'danger';
		} else {
			// ✅ এই Code সত্যিই কোনো Real Agent/User-এর Owncode কিনা যাচাই
			$check = mysqli_query($conn, "SELECT id FROM shonu_subjects WHERE owncode = '".mysqli_real_escape_string($conn, $defaultCode)."'");
			if (mysqli_num_rows($check) === 0) {
				$message = '❌ এই Code দিয়ে কোনো Agent/User পাওয়া যায়নি — সঠিক, Existing একটা Owncode দিন।';
				$message_type = 'danger';
			} else {
				$stmt = $conn->prepare("
					INSERT INTO site_settings (setting_key, setting_value) VALUES ('default_invitation_code', ?)
					ON DUPLICATE KEY UPDATE setting_value = ?
				");
				$stmt->bind_param("ss", $defaultCode, $defaultCode);
				$stmt->execute();
				$stmt->close();
				$message = '✅ Default Invitation Code সংরক্ষণ হয়েছে — এখন থেকে যারা নিজে কোনো Code ছাড়া Register করতে আসবে, তারা এই Code দিয়েই Register হবে।';
				$message_type = 'success';
			}
		}
	}

	$current = '';
	$result = mysqli_query($conn, "SELECT setting_value FROM site_settings WHERE setting_key = 'default_invitation_code' LIMIT 1");
	if ($result) {
		$row = mysqli_fetch_assoc($result);
		if ($row) $current = $row['setting_value'];
	}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title>Default Invitation Code Settings</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
<link rel="stylesheet" href="css/style.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
.dc-card { background:#1B1633; border:1px solid #322A5C; border-radius:14px; padding:24px; margin-bottom:20px; font-family:'Inter',sans-serif; max-width:600px; }
.dc-card .form-group label { color:#9691B8; font-size:12px; text-transform:uppercase; letter-spacing:.5px; font-weight:600; }
.dc-card .form-control { background:#0E0B1A; border:1.5px solid #322A5C; color:#F3F0FF; border-radius:10px; }
.dc-btn { background:#D4AF37; border:none; font-weight:700; color:#1A1400; border-radius:10px; padding:10px 24px; }
.dc-info { background:rgba(212,175,55,.08); border:1px solid rgba(212,175,55,.25); border-radius:10px; padding:14px 16px; font-size:13px; color:#F5EFDC; margin-bottom:20px; }
</style>
</head>
<body>
<div class="container-scroller">
  <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
    <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
      <a class="navbar-brand brand-logo" href="dashboard.php"><img src="images/logo.png" alt="logo"/></a>
    </div>
    <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
      <ul class="navbar-nav navbar-nav-right">
        <li class="nav-item dropdown d-flex mr-4"><a class="nav-link" href="logout.php"><i class="icon-power"></i> Logout</a></li>
      </ul>
    </div>
  </nav>
  <div class="container-fluid page-body-wrapper">
    <nav class="sidebar sidebar-offcanvas" id="sidebar">
      <?php include 'compass.php'; ?>
    </nav>
    <div class="main-panel">
      <div class="content-wrapper">
        <h4 class="font-weight-bold text-dark mb-4">🔗 Default Invitation Code</h4>

        <div class="dc-info">
          ℹ️ যারা সরাসরি <b>cv111.site</b>-এ ঢুকে কোনো Agent-Link ছাড়াই Register করে, তাদের জন্য এই Default Code ব্যবহার হবে —
          Registration Page-এ এই Code স্বয়ংক্রিয়ভাবে বসে থাকবে (User দেখতে পাবে), আর তারা কোনো নির্দিষ্ট Agent-এর Downline হিসেবে গণ্য হবে।
        </div>

        <?php if ($message): ?>
        <div class="alert alert-<?= $message_type ?> alert-dismissible fade show">
          <?= htmlspecialchars($message) ?>
          <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
        <?php endif; ?>

        <div class="dc-card">
          <form method="POST">
            <input type="hidden" name="action" value="save_default_code">
            <div class="form-group">
              <label>Default Invitation Code (কোনো Real Agent/User-এর Owncode হতে হবে)</label>
              <input type="text" name="default_invitation_code" class="form-control" placeholder="যেমন: B4F57874" value="<?= htmlspecialchars($current) ?>" required>
            </div>
            <button type="submit" class="dc-btn">Save করো</button>
          </form>
        </div>

      </div>
    </div>
  </div>
</div>
<script src="vendors/base/vendor.bundle.base.js"></script>
</body>
</html>
