<?php
session_start();
include '../includes/db.php';

$reset_error   = $reset_success = "";
$create_error  = $create_success = "";

// CSRF tokens
if (empty($_SESSION['csrf_reset']))  $_SESSION['csrf_reset']  = bin2hex(random_bytes(32));
if (empty($_SESSION['csrf_create'])) $_SESSION['csrf_create'] = bin2hex(random_bytes(32));
if (empty($_SESSION['csrf_addeml'])) $_SESSION['csrf_addeml'] = bin2hex(random_bytes(32));

$addeml_msg = $addeml_type = "";

// Token URL se validate (email flow)
$raw_token           = isset($_GET['token']) ? trim($_GET['token']) : '';
$id_param            = isset($_GET['id'])    ? intval($_GET['id'])  : 0;
$token_valid         = false;
$admin_id_from_token = null;

if ($raw_token && $id_param > 0) {
    $hashed_token = hash('sha256', $raw_token);
    $s = $conn->prepare("SELECT id FROM admin_users WHERE id=? AND reset_token=? AND reset_token_expiry>NOW()");
    $s->bind_param("is", $id_param, $hashed_token);
    $s->execute(); $s->store_result();
    if ($s->num_rows > 0) { $token_valid = true; $admin_id_from_token = $id_param; }
    $s->close();
}

// ── ACTION: Reset / Change Password ──────────────────────────────────────────
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action']) && $_POST['action'] === 'reset_pwd') {
    if (!isset($_POST['csrf_reset']) || !hash_equals($_SESSION['csrf_reset'], $_POST['csrf_reset'])) {
        $reset_error = "Invalid request.";
    } else {
        $uid     = trim($_POST['user_id']         ?? '');
        $new_pwd = $_POST['new_password']          ?? '';
        $con_pwd = $_POST['confirm_password']      ?? '';

        if (empty($uid))              $reset_error = "User ID daalna zaroori hai.";
        elseif (strlen($new_pwd) < 6) $reset_error = "Password kam se kam 6 characters hona chahiye.";
        elseif ($new_pwd !== $con_pwd) $reset_error = "Dono passwords match nahi karte.";
        else {
            $chk = $conn->prepare("SELECT id FROM admin_users WHERE username=?");
            $chk->bind_param("s", $uid); $chk->execute(); $chk->store_result();
            if ($chk->num_rows === 0) {
                $reset_error = "Invalid User ID. Sahi User ID dalein ya neeche 'Create New User' use karein.";
                $chk->close();
            } else {
                $chk->bind_result($mid); $chk->fetch(); $chk->close();
                $hp = password_hash($new_pwd, PASSWORD_DEFAULT);
                $upd = $conn->prepare("UPDATE admin_users SET password=?, reset_token=NULL, reset_token_expiry=NULL WHERE id=?");
                $upd->bind_param("si", $hp, $mid);
                if ($upd->execute()) {
                    $_SESSION['flash_success'] = "✅ Password change ho gaya! Ab naye password se login karein.";
                    header("Location: login.php"); exit;
                } else { $reset_error = "Error. Try again."; }
                $upd->close();
            }
        }
    }
}

// ── ACTION: Create New Admin User ─────────────────────────────────────────────
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action']) && $_POST['action'] === 'create_user') {
    if (!isset($_POST['csrf_create']) || !hash_equals($_SESSION['csrf_create'], $_POST['csrf_create'])) {
        $create_error = "Invalid request.";
    } else {
        $new_uid = trim($_POST['new_uid']      ?? '');
        $new_pwd = $_POST['new_uid_pwd']       ?? '';
        $con_pwd = $_POST['new_uid_pwd_con']   ?? '';

        if (empty($new_uid))              $create_error = "User ID daalna zaroori hai.";
        elseif (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $new_uid))
                                          $create_error = "User ID: letters, numbers, underscore only. Min 3 chars.";
        elseif (strlen($new_pwd) < 6)     $create_error = "Password kam se kam 6 characters hona chahiye.";
        elseif ($new_pwd !== $con_pwd)    $create_error = "Dono passwords match nahi karte.";
        else {
            $dup = $conn->prepare("SELECT id FROM admin_users WHERE username=?");
            $dup->bind_param("s", $new_uid); $dup->execute(); $dup->store_result();
            if ($dup->num_rows > 0) {
                $create_error = "Yeh User ID already exist karta hai. Alag choose karein.";
                $dup->close();
            } else {
                $dup->close();
                $hp  = password_hash($new_pwd, PASSWORD_DEFAULT);
                $ins = $conn->prepare("INSERT INTO admin_users (username, password) VALUES (?,?)");
                $ins->bind_param("ss", $new_uid, $hp);
                if ($ins->execute()) {
                    $_SESSION['flash_success'] = "✅ Naya User ID '<strong>" . htmlspecialchars($new_uid) . "</strong>' create ho gaya! Ab login karein.";
                    header("Location: login.php"); exit;
                } else { $create_error = "Error. Try again."; }
                $ins->close();
            }
        }
    }
}

// ── ACTION 3: Add / Update Email ID ─────────────────────────────────────────
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['action']) && $_POST['action'] === 'add_email') {
    if (!isset($_POST['csrf_addeml']) || !hash_equals($_SESSION['csrf_addeml'], $_POST['csrf_addeml'])) {
        $addeml_msg  = "Invalid request."; $addeml_type = "danger";
    } else {
        $ae_uid   = trim($_POST['ae_uid']   ?? '');
        $ae_email = trim($_POST['ae_email'] ?? '');
        if (empty($ae_uid) || empty($ae_email)) {
            $addeml_msg  = "User ID aur Email dono zaroori hain."; $addeml_type = "danger";
        } elseif (!filter_var($ae_email, FILTER_VALIDATE_EMAIL)) {
            $addeml_msg  = "Sahi email format dalein."; $addeml_type = "danger";
        } else {
            $chk = $conn->prepare("SELECT id FROM admin_users WHERE username=?");
            $chk->bind_param("s", $ae_uid); $chk->execute(); $chk->store_result();
            if ($chk->num_rows === 0) {
                $addeml_msg  = "❌ User ID nahi mila."; $addeml_type = "danger"; $chk->close();
            } else {
                $chk->bind_result($ae_id); $chk->fetch(); $chk->close();
                $upd = $conn->prepare("UPDATE admin_users SET email=? WHERE id=?");
                $upd->bind_param("si", $ae_email, $ae_id);
                if ($upd->execute()) {
                    $_SESSION['flash_success'] = "✅ Email '<strong>" . htmlspecialchars($ae_email) . "</strong>' add ho gayi! Ab login karein.";
                    header("Location: login.php"); exit;
                } else { $addeml_msg = "Error. Try again."; $addeml_type = "danger"; }
                $upd->close();
            }
        }
    }
}

// Which tab to show active
$active_tab = 'reset';
if (isset($_POST['action']) && $_POST['action'] === 'create_user') $active_tab = 'create';
if (isset($_POST['action']) && $_POST['action'] === 'add_email')   $active_tab = 'addeml';
if ($create_error  || $create_success)  $active_tab = 'create';
if ($addeml_msg)                        $active_tab = 'addeml';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset / Create – Balimeen Admin</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f4f7f6; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; }
        .main-card { width: 100%; max-width: 440px; padding: 2rem; border-radius: 30px; box-shadow: 0 6px 20px rgba(0,0,0,0.13); background: deepskyblue; }
        .tab-btns { display: flex; gap: 8px; margin-bottom: 1.2rem; }
        .tab-btn {
            flex: 1; padding: 10px 0; border: 2px solid rgba(255,255,255,0.7);
            background: transparent; color: #fff; border-radius: 12px;
            font-weight: 600; font-size: 13px; cursor: pointer; transition: all 0.2s;
        }
        .tab-btn.active { background: #fff; color: deepskyblue; border-color: #fff; }
        .tab-btn:hover:not(.active) { background: rgba(255,255,255,0.2); }
        .tab-panel { display: none; }
        .tab-panel.active { display: block; }
        .form-label { color: #fff; font-size: 13px; font-weight: 600; margin-bottom: 3px; }
        .hint { font-size: 11px; color: rgba(255,255,255,0.8); margin-top: 2px; }
        .password-wrapper { position: relative; }
        .password-wrapper .eye { position: absolute; right: 11px; top: 50%; transform: translateY(-50%); background: none; border: none; color: #555; cursor: pointer; padding: 0; }
        .password-wrapper input { padding-right: 38px; }
        .divider { border-top: 1px solid rgba(255,255,255,0.3); margin: 1rem 0; }
        .back-link { font-size: 13px; color: #fff; text-decoration: underline; }
        .email-info { font-size: 12px; color: #fff; text-align: center; margin-top: 10px; }
        h3 { color: #fff; }
    </style>
    <?php if ($reset_success): ?>
    <meta http-equiv="refresh" content="3;url=login.php">
    <?php endif; ?>
</head>
<body>
<div class="main-card">
    <h3 class="text-center mb-1"><i class="fa fa-lock me-2"></i>Admin Access</h3>
    <p class="text-center text-white mb-3" style="font-size:12px;">Password reset karein ya naya User ID banayein</p>

    <!-- Tab Buttons -->
    <div class="tab-btns">
        <button class="tab-btn <?php echo $active_tab==='reset'  ? 'active' : ''; ?>" onclick="switchTab('reset')">
            <i class="fa fa-key me-1"></i>Reset Pwd
        </button>
        <button class="tab-btn <?php echo $active_tab==='create' ? 'active' : ''; ?>" onclick="switchTab('create')">
            <i class="fa fa-user-plus me-1"></i>New User
        </button>
        <button class="tab-btn <?php echo $active_tab==='addeml' ? 'active' : ''; ?>" onclick="switchTab('addeml')">
            <i class="fa fa-envelope me-1"></i>Add Email
        </button>
    </div>

    <!-- ── Tab 1: Reset Password ── -->
    <div class="tab-panel <?php echo $active_tab==='reset' ? 'active' : ''; ?>" id="tab-reset">

        <?php if ($reset_success): ?>
            <div class="alert alert-success">
                <i class="fa fa-check-circle me-1"></i><?php echo $reset_success; ?>
                <br><small>3 seconds mein login page par redirect...</small>
            </div>
        <?php else: ?>
            <?php if ($reset_error): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($reset_error); ?></div>
            <?php endif; ?>
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>" autocomplete="off">
                <input type="hidden" name="action"     value="reset_pwd">
                <input type="hidden" name="csrf_reset" value="<?php echo htmlspecialchars($_SESSION['csrf_reset']); ?>">

                <div class="mb-2">
                    <label class="form-label">User ID</label>
                    <input type="text" class="form-control" name="user_id" placeholder="Apna User ID dalein" required autocomplete="off"
                           value="<?php echo isset($_POST['user_id']) ? htmlspecialchars($_POST['user_id']) : ''; ?>">
                </div>
                <div class="mb-2">
                    <label class="form-label">Naya Password</label>
                    <div class="password-wrapper">
                        <input type="password" class="form-control" id="r1" name="new_password" placeholder="Min 6 characters" required>
                        <button type="button" class="eye" onclick="tp('r1','re1')"><i class="fa fa-eye" id="re1"></i></button>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Confirm Password</label>
                    <div class="password-wrapper">
                        <input type="password" class="form-control" id="r2" name="confirm_password" placeholder="Dobara dalein" required>
                        <button type="button" class="eye" onclick="tp('r2','re2')"><i class="fa fa-eye" id="re2"></i></button>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary w-100"><i class="fa fa-save me-1"></i>Save New Password</button>
            </form>
        <?php endif; ?>
    </div>

    <!-- ── Tab 2: Create New User ID ── -->
    <div class="tab-panel <?php echo $active_tab==='create' ? 'active' : ''; ?>" id="tab-create">

        <?php if ($create_success): ?>
            <div class="alert alert-success"><i class="fa fa-check-circle me-1"></i><?php echo $create_success; ?></div>
            <div class="text-center mt-2">
                <a href="login.php" class="back-link">Login par jaayein →</a>
            </div>
        <?php else: ?>
            <?php if ($create_error): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($create_error); ?></div>
            <?php endif; ?>
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>" autocomplete="off">
                <input type="hidden" name="action"      value="create_user">
                <input type="hidden" name="csrf_create" value="<?php echo htmlspecialchars($_SESSION['csrf_create']); ?>">

                <div class="mb-2">
                    <label class="form-label">New User ID</label>
                    <input type="text" class="form-control" name="new_uid" placeholder="Custom User ID (e.g. balimeen2)" required autocomplete="off"
                           value="<?php echo isset($_POST['new_uid']) ? htmlspecialchars($_POST['new_uid']) : ''; ?>">
                    <div class="hint">Letters, numbers, underscore only. Min 3 chars.</div>
                </div>
                <div class="mb-2">
                    <label class="form-label">Password</label>
                    <div class="password-wrapper">
                        <input type="password" class="form-control" id="c1" name="new_uid_pwd" placeholder="Min 6 characters" required>
                        <button type="button" class="eye" onclick="tp('c1','ce1')"><i class="fa fa-eye" id="ce1"></i></button>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Confirm Password</label>
                    <div class="password-wrapper">
                        <input type="password" class="form-control" id="c2" name="new_uid_pwd_con" placeholder="Dobara dalein" required>
                        <button type="button" class="eye" onclick="tp('c2','ce2')"><i class="fa fa-eye" id="ce2"></i></button>
                    </div>
                </div>
                <button type="submit" class="btn btn-success w-100"><i class="fa fa-user-plus me-1"></i>Create New User ID</button>
            </form>
        <?php endif; ?>
    </div>

    <!-- ── Tab 3: Add Email ID ── -->
    <div class="tab-panel <?php echo $active_tab==='addeml' ? 'active' : ''; ?>" id="tab-addeml">
        <p style="color:rgba(255,255,255,0.85);font-size:12px;margin-bottom:10px;">
            Admin account mein email add / update karein.
        </p>
        <?php if ($addeml_msg): ?>
            <div class="alert alert-<?php echo $addeml_type; ?>"><?php echo $addeml_msg; ?></div>
        <?php endif; ?>
        <?php if ($addeml_type !== 'success'): ?>
        <form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>" autocomplete="off">
            <input type="hidden" name="action"      value="add_email">
            <input type="hidden" name="csrf_addeml" value="<?php echo htmlspecialchars($_SESSION['csrf_addeml']); ?>">
            <div class="mb-2">
                <label class="form-label">User ID</label>
                <input type="text" class="form-control" name="ae_uid"
                       placeholder="Apna User ID dalein" required autocomplete="off"
                       value="<?php echo (isset($_POST['ae_uid']) && $addeml_type==='danger') ? htmlspecialchars($_POST['ae_uid']) : ''; ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">Email ID</label>
                <input type="email" class="form-control" name="ae_email"
                       placeholder="e.g. balimeenpvtltd@gmail.com" required autocomplete="off"
                       value="<?php echo (isset($_POST['ae_email']) && $addeml_type==='danger') ? htmlspecialchars($_POST['ae_email']) : ''; ?>">
            </div>
            <button type="submit" class="btn btn-success w-100">
                <i class="fa fa-plus-circle me-1"></i>Add / Update Email ID
            </button>
        </form>
        <?php endif; ?>
    </div>

    <div class="divider"></div>
    <div class="text-center">
        <a href="login.php" class="back-link"><i class="fa fa-arrow-left me-1"></i>Back to Login</a>
    </div>
    <div class="email-info"><i class="fa fa-envelope me-1"></i>balimeenpvtltd@gmail.com</div>
</div>

<script>
function switchTab(tab) {
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById('tab-' + tab).classList.add('active');
    event.currentTarget.classList.add('active');
}
function tp(fid, iid) {
    var f = document.getElementById(fid), i = document.getElementById(iid);
    f.type = f.type === 'password' ? 'text' : 'password';
    i.classList.toggle('fa-eye'); i.classList.toggle('fa-eye-slash');
}
</script>
</body>
</html>
