<?php
// ═══════════════════════════════════════════════════════════
// owner_topup_admin.php — Email+Password Login, Change করা যায়
// ═══════════════════════════════════════════════════════════
session_start();
include "conn.php";

// প্রথমবার Table তৈরি + Default Credential বসানো (না থাকলে)
$conn->query("
    CREATE TABLE IF NOT EXISTS owner_credentials (
        id INT PRIMARY KEY DEFAULT 1,
        email VARCHAR(100) NOT NULL,
        password_hash VARCHAR(255) NOT NULL
    )
");
$existing = $conn->query("SELECT * FROM owner_credentials WHERE id = 1");
if ($existing->num_rows === 0) {
    // ⚠️ প্রথমবার — Default Email/Password। Login করে সাথে সাথেই বদলে ফেলো!
    $defaultEmail = 'owner@example.com';
    $defaultPassHash = password_hash('ChangeMe123', PASSWORD_DEFAULT);
    $stmt = $conn->prepare("INSERT INTO owner_credentials (id, email, password_hash) VALUES (1, ?, ?)");
    $stmt->bind_param("ss", $defaultEmail, $defaultPassHash);
    $stmt->execute();
    $stmt->close();
}

$loginError = '';
$message = '';

// ── Logout ──
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: owner_topup_admin.php");
    exit();
}

// ── Login Handle ──
if (!isset($_SESSION['owner_authenticated'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_email'], $_POST['login_password'])) {
        $cred = $conn->query("SELECT * FROM owner_credentials WHERE id = 1")->fetch_assoc();
        if ($_POST['login_email'] === $cred['email'] && password_verify($_POST['login_password'], $cred['password_hash'])) {
            $_SESSION['owner_authenticated'] = true;
        } else {
            $loginError = "❌ Email অথবা Password ভুল";
        }
    }
}

// ── Email/Password বদলানো ──
if (isset($_SESSION['owner_authenticated']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'change_credentials') {
    $newEmail = trim($_POST['new_email']);
    $newPassword = trim($_POST['new_password']);
    $currentPassword = trim($_POST['current_password']);

    $cred = $conn->query("SELECT * FROM owner_credentials WHERE id = 1")->fetch_assoc();
    if (!password_verify($currentPassword, $cred['password_hash'])) {
        $message = "❌ বর্তমান Password ভুল — বদলানো যায়নি";
    } elseif (empty($newEmail) || empty($newPassword)) {
        $message = "❌ নতুন Email/Password খালি রাখা যাবে না";
    } elseif (strlen($newPassword) < 6) {
        $message = "❌ Password কমপক্ষে ৬ Character হতে হবে";
    } else {
        $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE owner_credentials SET email = ?, password_hash = ? WHERE id = 1");
        $stmt->bind_param("ss", $newEmail, $newHash);
        $stmt->execute();
        $stmt->close();
        $message = "✅ Email/Password সফলভাবে বদলানো হয়েছে!";
    }
}

// ── Coin Top-up ──
if (isset($_SESSION['owner_authenticated']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_unohs'], $_POST['topup_amount'])) {
    $unohs = trim($_POST['admin_unohs']);
    $amount = floatval($_POST['topup_amount']);
    if ($amount > 0) {
        $stmt = $conn->prepare("UPDATE nirvahaka_shonu SET motta = motta + ? WHERE unohs = ?");
        $stmt->bind_param("ds", $amount, $unohs);
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $message = "✅ Admin (unohs: $unohs)-এর Balance-এ ৳" . number_format($amount, 2) . " যোগ হয়েছে।";
        } else {
            $message = "❌ এই unohs-এর Admin খুঁজে পাওয়া যায়নি।";
        }
        $stmt->close();
    }
}

$admins = [];
$currentEmail = '';
if (isset($_SESSION['owner_authenticated'])) {
    $result = $conn->query("SELECT unohs, nirvahaka_hesaru, motta FROM nirvahaka_shonu ORDER BY unohs");
    while ($row = $result->fetch_assoc()) { $admins[] = $row; }
    $cred = $conn->query("SELECT email FROM owner_credentials WHERE id = 1")->fetch_assoc();
    $currentEmail = $cred['email'];

    // ✅ নতুন যোগ — সব Agent-এর তালিকা আনা
    $agents = [];
    $agentResult = $conn->query("
        SELECT s.id, s.mobile, a.status
        FROM shonu_subjects s
        INNER JOIN tb_agent a ON a.userid = s.id
        ORDER BY s.id
    ");
    while ($row = $agentResult->fetch_assoc()) { $agents[] = $row; }
}

/* ══════════════════════════════════════════════════════════════
   ✅ নতুন যোগ — Owner সরাসরি যেকোনো Admin/Agent Account-এ ঢুকতে
   পারবে (Email Verification ছাড়াই) — Emergency/Support-এর জন্য।
   Owner নিজের Password দিয়ে আগেই Verified, তাই এটা নিরাপদ।
   ══════════════════════════════════════════════════════════════ */
if (isset($_SESSION['owner_authenticated']) && isset($_GET['impersonate_admin'])) {
    $targetUnohs = intval($_GET['impersonate_admin']);
    $targetAdmin = $conn->query("SELECT unohs, nirvahaka_hesaru FROM nirvahaka_shonu WHERE unohs = $targetUnohs")->fetch_assoc();
    if ($targetAdmin) {
        $_SESSION['unohs'] = $targetAdmin['unohs'];
        $_SESSION['nirvahaka_hesaru'] = $targetAdmin['nirvahaka_hesaru'];
        header("Location: dashboard.php");
        exit;
    }
}

if (isset($_SESSION['owner_authenticated']) && isset($_GET['impersonate_agent'])) {
    $targetAgentId = intval($_GET['impersonate_agent']);

    // ✅ FIX — agent/auth.php ঠিক এই Query দিয়েই Verify করে
    // (tb_agent Table-এ, status='1' Check করে) — তাই এখানেও
    // ঠিক একই Query দিয়ে আগে Verify করা হচ্ছে, যাতে Session
    // বসানোর পর auth.php-তে গিয়ে Reject না হয়
    $verifyStmt = $conn->prepare("SELECT userid FROM tb_agent WHERE userid = ? AND status = '1' LIMIT 1");
    $verifyStmt->bind_param("i", $targetAgentId);
    $verifyStmt->execute();
    $verifyResult = $verifyStmt->get_result();

    if ($verifyResult->num_rows > 0) {
        $mobileRow = $conn->query("SELECT mobile FROM shonu_subjects WHERE id = $targetAgentId")->fetch_assoc();

        $_SESSION['agent_uid'] = $targetAgentId;
        $_SESSION['agent_mobile'] = $mobileRow['mobile'] ?? '';

        // ⚠️ সাময়িক Debug — Session ঠিকভাবে বসছে কিনা দেখা
        echo "<pre>DEBUG INFO:\n";
        echo "Session ID: " . session_id() . "\n";
        echo "agent_uid set to: " . $_SESSION['agent_uid'] . "\n";
        echo "agent_mobile set to: " . $_SESSION['agent_mobile'] . "\n";
        echo "Redirecting to: ../agent/dashboard.php\n";
        echo "</pre>";
        echo "<a href='../agent/dashboard.php'>এখানে চাপো Dashboard-এ যেতে (Manual Link)</a>";
        exit; // ⚠️ সাময়িকভাবে এখানেই থামানো হচ্ছে, Auto-Redirect বন্ধ রেখে
        header("Location: ../agent/dashboard.php");
        exit;
    } else {
        $message = "❌ এই Agent-এর tb_agent Table-এ Active Status পাওয়া যায়নি, তাই Login As সম্ভব হয়নি।";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Owner Panel - RAJ365</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
    * { box-sizing: border-box; }
    body {
        background: radial-gradient(ellipse at 50% -10%, #241245 0%, #0A0A0A 55%);
        color: #F5EFDC; font-family: 'Segoe UI', sans-serif; margin: 0; padding: 20px;
        min-height: 100vh;
    }
    .wrap { max-width: 440px; margin: 0 auto; }
    .logo { text-align: center; margin-bottom: 24px; }
    .logo span { font-size: 24px; font-weight: 900; background: linear-gradient(90deg,#D4AF37,#F0D264,#D4AF37); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: 1px; text-shadow: 0 0 20px rgba(212,175,55,.3); }
    .card { background: linear-gradient(160deg,#1A1433,#16112B); border: 1px solid rgba(212,175,55,.25); border-radius: 16px; padding: 24px; margin-bottom: 16px; box-shadow: 0 8px 32px rgba(0,0,0,.4); }
    .card h3 { margin: 0 0 16px; color: #D4AF37; font-size: 16px; }
    label { display: block; color: #9691B8; font-size: 11.5px; font-weight: 700; text-transform: uppercase; letter-spacing: .4px; margin-bottom: 6px; margin-top: 14px; }
    label:first-child { margin-top: 0; }
    input { width: 100%; padding: 12px 14px; border-radius: 10px; border: 1px solid #2A2250; background: #0E0B1A; color: #F5EFDC; font-size: 14px; }
    input:focus { outline: none; border-color: #D4AF37; }
    button { width: 100%; padding: 14px; border-radius: 12px; border: none; font-weight: 800; font-size: 14.5px; margin-top: 18px; cursor: pointer; }
    .btn-gold { background: linear-gradient(180deg,#F0D264,#D4AF37); color: #1A1400; box-shadow: 0 4px 20px rgba(212,175,55,.35); }
    .btn-danger { background: rgba(232,50,60,.12); color: #E8323C; border: 1px solid #E8323C; }
    .msg { padding: 12px 16px; border-radius: 10px; font-size: 13px; margin-bottom: 16px; }
    .msg-ok { background: rgba(31,185,121,.12); border: 1px solid #1FB979; color: #1FB979; }
    .msg-err { background: rgba(232,50,60,.12); border: 1px solid #E8323C; color: #E8323C; }
    .admin-row { display: flex; justify-content: space-between; align-items: center; background: #0E0B1A; border: 1px solid #241C42; border-radius: 10px; padding: 10px 14px; margin-bottom: 8px; font-size: 13px; }
    .admin-row b { color: #F5EFDC; }
    .admin-row .bal { color: #D4AF37; font-weight: 700; }
    .logout-link { display: block; text-align: center; color: #9691B8; font-size: 12.5px; margin-top: 20px; text-decoration: none; }
    .toggle-link { display: block; text-align: center; color: #A970FF; font-size: 12.5px; margin-top: 14px; cursor: pointer; }
    .hidden { display: none; }
</style>
</head>
<body>
<div class="wrap">
<div class="logo"><span>👑 OWNER PANEL</span></div>

<?php if (!isset($_SESSION['owner_authenticated'])): ?>

    <div class="card">
        <h3>🔐 Login করো</h3>
        <?php if ($loginError): ?><div class="msg msg-err"><?= $loginError ?></div><?php endif; ?>
        <form method="POST">
            <label>Email</label>
            <input type="email" name="login_email" placeholder="owner@example.com" required>
            <label>Password</label>
            <input type="password" name="login_password" placeholder="••••••••" required>
            <button type="submit" class="btn-gold">ঢোকো</button>
        </form>
    </div>

<?php else: ?>

    <?php if ($message): ?>
        <div class="msg <?= strpos($message, '✅') !== false ? 'msg-ok' : 'msg-err' ?>"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <div class="card">
        <h3>💰 Admin-দের Balance</h3>
        <?php foreach ($admins as $a): ?>
            <div class="admin-row">
                <span><b><?= htmlspecialchars($a['nirvahaka_hesaru']) ?></b> (unohs: <?= htmlspecialchars($a['unohs']) ?>)</span>
                <span class="bal">৳<?= number_format($a['motta'] ?? 0, 2) ?></span>
                <a href="?impersonate_admin=<?= $a['unohs'] ?>" style="color:#A970FF; font-size:11px; text-decoration:underline;">Login As →</a>
            </div>
        <?php endforeach; ?>

        <form method="POST" style="margin-top:16px;">
            <label>Admin-এর unohs</label>
            <input type="text" name="admin_unohs" placeholder="যেমন: 1" required>
            <label>কত Coin যোগ করবে</label>
            <input type="number" step="0.01" name="topup_amount" placeholder="যেমন: 10000" required>
            <button type="submit" class="btn-gold">Balance যোগ করো</button>
        </form>
    </div>

    <div class="card">
        <h3>👥 Agent-দের তালিকা</h3>
        <?php foreach ($agents as $ag): ?>
            <div class="admin-row">
                <span><b><?= htmlspecialchars($ag['mobile']) ?></b> (ID: <?= htmlspecialchars($ag['id']) ?>)</span>
                <span class="bal"><?= $ag['status'] == 1 ? '🟢' : '🔴' ?></span>
                <a href="?impersonate_agent=<?= $ag['id'] ?>" style="color:#A970FF; font-size:11px; text-decoration:underline;">Login As →</a>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="toggle-link" onclick="document.getElementById('credBox').classList.toggle('hidden')">
        ⚙️ Email/Password বদলাতে চাও? এখানে চাপো
    </div>

    <div class="card hidden" id="credBox">
        <h3>🔑 Email/Password বদলাও</h3>
        <p style="color:#9691B8; font-size:12px; margin-top:-8px;">বর্তমান Email: <?= htmlspecialchars($currentEmail) ?></p>
        <form method="POST">
            <input type="hidden" name="action" value="change_credentials">
            <label>বর্তমান Password (Verify করার জন্য)</label>
            <input type="password" name="current_password" placeholder="বর্তমান Password" required>
            <label>নতুন Email</label>
            <input type="email" name="new_email" placeholder="নতুন Email" value="<?= htmlspecialchars($currentEmail) ?>" required>
            <label>নতুন Password</label>
            <input type="password" name="new_password" placeholder="কমপক্ষে ৬ Character" required minlength="6">
            <button type="submit" class="btn-danger">বদলে ফেলো</button>
        </form>
    </div>

    <a href="?logout=1" class="logout-link">🚪 Logout করো</a>

<?php endif; ?>
</div>
</body>
</html>
