<?php
require_once 'config.php';

if (isset($_GET['email']) && !isset($_GET['token'])) {
    $email = trim($_GET['email']);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Invalid email']);
        exit;
    }
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 0) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Email not registered']);
        exit;
    }
    $stmt->close();

    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', time() + 3600);
    $stmt = $conn->prepare("DELETE FROM password_resets WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->close();

    $stmt = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $email, $token, $expires);
    if (!$stmt->execute()) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Failed to generate link']);
        exit;
    }
    $stmt->close();

    $base = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
    $base .= rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
    $link = $base . '/reset_password.php?token=' . $token;
    $subject = "Password Reset";
    $body = "Click the link to reset your password:\n\n" . $link . "\n\nThis link expires in 1 hour.";
    $googleUrl = "https://script.google.com/macros/s/AKfycbygswhFT-3wlHCQ65j9DJsnadpNIBSswL05k7WZV7dx7emJOza-v8nl_GbiGlQDwGEuNw/exec?email=" . urlencode($email) . "&title=" . urlencode($subject) . "&body=" . urlencode($body) . "&appname=" . urlencode("SKM Esports");
    @file_get_contents($googleUrl);

    header('Content-Type: application/json');
    echo json_encode(['status' => 'success', 'message' => 'Reset link sent to your email']);
    exit;
}

if (isset($_GET['token'])) {
    $token = trim($_GET['token']);
    $stmt = $conn->prepare("SELECT email FROM password_resets WHERE token = ? AND expires_at > NOW() LIMIT 1");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 0) {
        die("<h2 style='font-family:sans-serif;text-align:center;margin-top:40px;'>Invalid or expired reset link.</h2>");
    }
    $row = $res->fetch_assoc();
    $email = $row['email'];
    $stmt->close();
    ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reset Password</title>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: 'Segoe UI', sans-serif; background:#f0f2f5; display:flex; justify-content:center; align-items:center; min-height:100vh; }
.card { background:#fff; padding:40px; border-radius:16px; box-shadow:0 8px 30px rgba(0,0,0,0.1); width:100%; max-width:420px; }
h2 { color:#1a1a2e; margin-bottom:8px; }
.sub { color:#6c6f82; margin-bottom:24px; font-size:14px; }
label { font-weight:500; display:block; margin:16px 0 6px; color:#2d2d3f; }
input[type="password"] { width:100%; padding:12px 16px; border:1px solid #d0d5dd; border-radius:10px; font-size:16px; transition:0.2s; }
input:focus { outline:none; border-color:#7B2CBF; box-shadow:0 0 0 3px rgba(123,44,191,0.2); }
button { width:100%; padding:14px; background:#7B2CBF; color:#fff; border:none; border-radius:10px; font-size:16px; font-weight:600; margin-top:24px; cursor:pointer; transition:0.2s; }
button:hover { background:#5a1f8a; }
.msg { font-size:14px; margin-top:8px; display:none; }
.error { color:#d32f2f; }
.success { color:#2e7d32; }
.loader { display:none; text-align:center; margin-top:12px; }
.loader::after { content:""; display:inline-block; width:20px; height:20px; border:3px solid #ddd; border-top-color:#7B2CBF; border-radius:50%; animation:spin 0.8s linear infinite; }
@keyframes spin { to { transform:rotate(360deg); } }
</style>
</head>
<body>
<div class="card">
<h2>🔐 Reset Password</h2>
<p class="sub">Enter new password for <strong><?php echo htmlspecialchars($email); ?></strong></p>
<form id="resetForm" onsubmit="submitReset(event)">
<label for="password">New Password</label>
<input type="password" id="password" required minlength="6" placeholder="Min 6 characters">
<label for="confirm">Confirm Password</label>
<input type="password" id="confirm" required minlength="6" placeholder="Re-enter password">
<div id="errorMsg" class="msg error"></div>
<div id="successMsg" class="msg success"></div>
<button type="submit" id="submitBtn">Update Password</button>
<div id="loader" class="loader"></div>
</form>
</div>
<script>
function submitReset(e) {
e.preventDefault();
const pw = document.getElementById('password').value;
const conf = document.getElementById('confirm').value;
const err = document.getElementById('errorMsg');
const suc = document.getElementById('successMsg');
const btn = document.getElementById('submitBtn');
const loader = document.getElementById('loader');
err.style.display = 'none';
suc.style.display = 'none';
if (pw.length < 6) { err.textContent = 'Password must be at least 6 characters.'; err.style.display = 'block'; return; }
if (pw !== conf) { err.textContent = 'Passwords do not match.'; err.style.display = 'block'; return; }
btn.disabled = true;
loader.style.display = 'block';
fetch('reset_password.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'action=reset&token=<?php echo urlencode($token); ?>&password=' + encodeURIComponent(pw)
})
.then(res => res.json())
.then(data => {
loader.style.display = 'none';
btn.disabled = false;
if (data.status === 'success') {
suc.textContent = data.message;
suc.style.display = 'block';
btn.textContent = 'Done!';
btn.style.background = '#2e7d32';
setTimeout(() => { window.location.href = 'https://skmesports.fun'; }, 2000);
} else {
err.textContent = data.message || 'Something went wrong.';
err.style.display = 'block';
}
})
.catch(() => {
loader.style.display = 'none';
btn.disabled = false;
err.textContent = 'Network error. Please try again.';
err.style.display = 'block';
});
}
</script>
</body>
</html>
    <?php
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reset') {
    $token = trim($_POST['token'] ?? '');
    $password = trim($_POST['password'] ?? '');
    if (empty($token) || strlen($password) < 6) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Invalid input']);
        exit;
    }
    $stmt = $conn->prepare("SELECT email FROM password_resets WHERE token = ? AND expires_at > NOW() LIMIT 1");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 0) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Invalid or expired reset link']);
        exit;
    }
    $row = $res->fetch_assoc();
    $email = $row['email'];
    $stmt->close();

    $hashed = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
    $stmt->bind_param("ss", $hashed, $email);
    if ($stmt->execute()) {
        $stmt->close();
        $stmt = $conn->prepare("DELETE FROM password_resets WHERE token = ?");
        $stmt->bind_param("s", $token);
        $stmt->execute();
        $stmt->close();
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'message' => 'Password updated successfully. Redirecting...']);
    } else {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Database error. Please try again.']);
    }
    exit;
}

header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
?>