<?php
/**
 * change_mobile.php
 * Agent নিজের mobile number নিজেই বদলাতে পারবে।
 * রাখো: agent/change_mobile.php
 */
session_start();
if (!isset($_SESSION['agent_uid']) || $_SESSION['agent_uid'] == "") {
    header("location:index.php");
    exit;
}
include("conn.php");
$agent_uid = $_SESSION['agent_uid'];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_mobile'])) {
    $mobile_raw = trim($_POST['new_mobile'] ?? '');
    $digits     = preg_replace('/^(\+?880|\+?91|0)/', '', $mobile_raw);
    $new_mobile = ($digits !== '') ? '880' . $digits : '';
    $password_confirm = $_POST['password_confirm'] ?? '';

    if (!preg_match('/^880[0-9]{7,12}$/', $new_mobile)) {
        $message = 'সঠিক format-এ Mobile Number দাও।';
        $message_type = 'danger';
    } else {
        // নিরাপত্তার জন্য — নিজের current password দিয়ে confirm করতে হবে
        $pwChk = mysqli_prepare($conn, "SELECT password FROM shonu_subjects WHERE id = ?");
        mysqli_stmt_bind_param($pwChk, "i", $agent_uid);
        mysqli_stmt_execute($pwChk);
        $pwRow = mysqli_stmt_get_result($pwChk)->fetch_assoc();
        mysqli_stmt_close($pwChk);

        if (!$pwRow || $pwRow['password'] !== md5($password_confirm)) {
            $message = 'ভুল Password — নিরাপত্তার জন্য নিজের বর্তমান password দিতে হবে।';
            $message_type = 'danger';
        } else {
            // নতুন mobile আগে থেকে অন্য কারো কিনা চেক করো
            $mchk = mysqli_prepare($conn, "SELECT id FROM shonu_subjects WHERE mobile = ? AND id != ?");
            mysqli_stmt_bind_param($mchk, "si", $new_mobile, $agent_uid);
            mysqli_stmt_execute($mchk);
            mysqli_stmt_store_result($mchk);

            if (mysqli_stmt_num_rows($mchk) > 0) {
                $message = "এই Mobile Number ($new_mobile) আগে থেকেই অন্য কারো account-এ আছে।";
                $message_type = 'danger';
            } else {
                mysqli_stmt_close($mchk);

                $u1 = mysqli_prepare($conn, "UPDATE shonu_subjects SET mobile = ? WHERE id = ?");
                mysqli_stmt_bind_param($u1, "si", $new_mobile, $agent_uid);
                mysqli_stmt_execute($u1);
                mysqli_stmt_close($u1);

                $u2 = mysqli_prepare($conn, "UPDATE tb_agent SET mobile = ? WHERE userid = ?");
                mysqli_stmt_bind_param($u2, "si", $new_mobile, $agent_uid);
                mysqli_stmt_execute($u2);
                mysqli_stmt_close($u2);

                $_SESSION['agent_mobile'] = $new_mobile;
                $message = "✅ Mobile Number সফলভাবে বদলে গেছে: $new_mobile — এখন থেকে এই number দিয়েই login করবে।";
                $message_type = 'success';
            }
        }
    }
}

// ─────────────────────────────────────────────────────────────
// ACTION ২: Contact Number set করো (Login Mobile থেকে আলাদা)
// User-দের balance-insufficient message-এ এই number-ই দেখানো হবে
// ─────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_contact'])) {
    $contact_raw = trim($_POST['contact_mobile'] ?? '');
    $c_digits    = preg_replace('/^(\+?880|\+?91|0)/', '', $contact_raw);
    $contact_mobile = ($c_digits !== '') ? '880' . $c_digits : '';

    if (!preg_match('/^880[0-9]{7,12}$/', $contact_mobile)) {
        $message = 'সঠিক Contact Number দাও।';
        $message_type = 'danger';
    } else {
        $cu = mysqli_prepare($conn, "UPDATE tb_agent SET contact_mobile = ? WHERE userid = ?");
        mysqli_stmt_bind_param($cu, "si", $contact_mobile, $agent_uid);
        mysqli_stmt_execute($cu);
        mysqli_stmt_close($cu);

        $message = "✅ Contact Number সেট হয়ে গেছে: $contact_mobile — User-রা এখন এই number-ই দেখবে।";
        $message_type = 'success';
    }
}

$cur = mysqli_prepare($conn, "SELECT mobile FROM shonu_subjects WHERE id = ?");
mysqli_stmt_bind_param($cur, "i", $agent_uid);
mysqli_stmt_execute($cur);
$curRow = mysqli_stmt_get_result($cur)->fetch_assoc();
mysqli_stmt_close($cur);
$current_mobile = $curRow['mobile'] ?? '';

$curC = mysqli_prepare($conn, "SELECT contact_mobile FROM tb_agent WHERE userid = ?");
mysqli_stmt_bind_param($curC, "i", $agent_uid);
mysqli_stmt_execute($curC);
$curCRow = mysqli_stmt_get_result($curC)->fetch_assoc();
mysqli_stmt_close($curC);
$current_contact = $curCRow['contact_mobile'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Mobile Number</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;font-family:-apple-system,sans-serif;}
body{background:#f4f6fb;}
.navbar{background:linear-gradient(135deg,#1a1a2e,#16213e);padding:0 24px;display:flex;align-items:center;justify-content:space-between;height:60px;}
.navbar .brand{color:#38ef7d;font-size:20px;font-weight:700;text-decoration:none;}
.navbar a.back{color:#c9d2ff;text-decoration:none;font-size:14px;}
.wrap{max-width:480px;margin:30px auto;padding:0 16px;}
.card{background:#fff;border-radius:12px;padding:24px;box-shadow:0 2px 12px rgba(0,0,0,.06);}
.card h5{margin-bottom:6px;}
.card p.sub{color:#777;font-size:13px;margin-bottom:20px;}
.field{margin-bottom:16px;}
.field label{display:block;font-size:13px;font-weight:600;margin-bottom:6px;color:#333;}
.field input{width:100%;padding:10px 12px;border:1.5px solid #e2e2e2;border-radius:8px;font-size:14px;}
.field input:focus{outline:none;border-color:#11998e;}
.current{background:#f0f4ff;border-radius:8px;padding:10px 14px;font-size:13px;margin-bottom:18px;}
.current b{color:#11998e;}
button{width:100%;padding:11px;border:none;border-radius:8px;background:#11998e;color:#fff;font-weight:700;font-size:14px;cursor:pointer;}
.alert{padding:12px 16px;border-radius:8px;font-size:13px;margin-bottom:16px;}
.alert-success{background:#e8f5e9;color:#2e7d32;}
.alert-danger{background:#fdecea;color:#c0392b;}
</style>
</head>
<body>

<div class="navbar">
  <a href="dashboard.php" class="brand">🎯 Agent Panel</a>
  <a href="dashboard.php" class="back">← Dashboard-এ ফিরে যাও</a>
</div>

<div class="wrap">
  <div class="card">
    <h5>📱 Mobile Number পরিবর্তন করো</h5>
    <p class="sub">এটাই তোমার Login ID হিসেবে ব্যবহৃত হয় — সাবধানে বদলাও।</p>

    <div class="current">বর্তমান Mobile: <b><?php echo htmlspecialchars($current_mobile); ?></b></div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>

    <form method="POST">
      <div class="field">
        <label>নতুন Mobile Number</label>
        <input type="text" name="new_mobile" placeholder="যেমন: 1812345678" required>
      </div>
      <div class="field">
        <label>নিজের বর্তমান Password (নিশ্চিত করার জন্য)</label>
        <input type="password" name="password_confirm" placeholder="Password" required>
      </div>
      <button type="submit" name="change_mobile" value="1">Mobile Number পরিবর্তন করো</button>
    </form>
  </div>

  <div class="card" style="margin-top:20px;">
    <h5>📞 Contact Number (User-দের জন্য)</h5>
    <p class="sub">Balance কম থাকলে User-রা এই number-ই দেখবে "Agent-এর সাথে যোগাযোগ করুন" message-এ। Login-এর number থেকে আলাদা রাখতে পারো।</p>

    <div class="current">বর্তমান Contact Number: <b><?php echo $current_contact ? htmlspecialchars($current_contact) : '(এখনো set করা হয়নি — Login mobile-ই দেখানো হচ্ছে)'; ?></b></div>

    <form method="POST">
      <div class="field">
        <label>নতুন Contact Number</label>
        <input type="text" name="contact_mobile" placeholder="যেমন: 1812345678" required>
      </div>
      <button type="submit" name="set_contact" value="1">Contact Number সেট করো</button>
    </form>
  </div>
</div>

</body>
</html>
