<?php
// --- Debugging ON (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once __DIR__ . '/../includes/database.php'; // ✅ DB Path

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userid'])) {

    $userid = base64_decode($_POST['userid']);
    $userid = trim($userid);
    if (empty($userid)) die("⚠️ Invalid user ID.");

    // Get emailid
    $stmt = $conn->prepare("SELECT emailid FROM usertable WHERE userid = ?");
    $stmt->bind_param("s", $userid);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows === 0) die("❌ User not found.");
    $stmt->bind_result($user_emailid);
    $stmt->fetch();
    $stmt->close();

    // Generate password
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $new_password_plain = substr(str_shuffle($chars), 0, 10);
    $new_password_hashed = password_hash($new_password_plain, PASSWORD_DEFAULT);

    // Update DB
    $update = $conn->prepare("UPDATE usertable SET password = ? WHERE userid = ?");
    $update->bind_param("ss", $new_password_hashed, $userid);
    $success = $update->execute();
    $update->close();
    $conn->close();

    if ($success) {
        // Send emailid
        $subject = "🔑 Your Password Has Been Reset";
        $message = "
        <html><body>
        <h2 style='color:#4CAF50;'>Password Reset Successful // Powered by - Ruby Aadhaar (ADMIN- 9913613860)</h2>
        <p>Hello <strong>$userid</strong>,</p>
        <p>Your new password is:</p>
        <p style='font-size:18px;font-weight:bold;background:#f1f1f1;padding:10px;border-radius:5px;display:inline-block;'>$new_password_plain</p>
        <p>Please login and change your password immediately.</p>
        <br><p>Best Regards,<br><strong>Admin Team</strong></p>
        </body></html>";
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\n";
        $headers .= "From: Admin <no-reply@" . $_SERVER['SERVER_NAME'] . ">\r\n";
        @mail($user_emailid, $subject, $message, $headers);

        // ✅ Stylish Glow Success Page
        echo "
        <!DOCTYPE html>
        <html lang='en'>
        <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <title>Password Reset Success</title>
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
            body {
                margin: 0;
                height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                background: linear-gradient(135deg, #6a11cb, #2575fc, #ff4b2b);
                background-size: 400% 400%;
                animation: gradientBG 8s ease infinite;
                font-family: 'Poppins', sans-serif;
            }
            @keyframes gradientBG {
                0% {background-position: 0% 50%;}
                50% {background-position: 100% 50%;}
                100% {background-position: 0% 50%;}
            }
            .card {
                background: rgba(255,255,255,0.1);
                padding: 30px;
                border-radius: 20px;
                text-align: center;
                max-width: 420px;
                width: 90%;
                backdrop-filter: blur(10px);
                box-shadow: 0 0 25px rgba(255,255,255,0.4);
                animation: fadeUp 0.8s ease;
            }
            @keyframes fadeUp {
                from {opacity:0; transform: translateY(50px);}
                to {opacity:1; transform: translateY(0);}
            }
            .glow-icon {
                font-size: 90px;
                color: #fff;
                text-shadow: 0 0 10px #fff, 0 0 20px #00e6e6, 0 0 40px #00e6e6;
                animation: pop 0.7s ease;
            }
            @keyframes pop {
                0% {transform: scale(0);}
                70% {transform: scale(1.2);}
                100% {transform: scale(1);}
            }
            h2 {
                color: #fff;
                margin: 10px 0;
                font-size: 22px;
            }
            p {
                color: #f1f1f1;
                margin: 5px 0;
            }
            .password-box {
                margin: 15px 0;
                display: flex;
                justify-content: center;
                align-items: center;
                background: rgba(255,255,255,0.2);
                padding: 10px;
                border-radius: 10px;
                box-shadow: 0 0 10px rgba(255,255,255,0.3);
            }
            .password-text {
                color: #fff;
                font-weight: 600;
                letter-spacing: 1px;
                font-size: 16px;
            }
            .copy-btn {
                margin-left: 10px;
                background: #00e6e6;
                color: #000;
                border: none;
                padding: 7px 12px;
                border-radius: 6px;
                cursor: pointer;
                font-weight: 600;
                transition: 0.3s;
            }
            .copy-btn:hover {
                background: #fff;
                color: #000;
            }
            .timer {
                margin-top: 15px;
                color: #fff;
                font-size: 14px;
            }
            .back-link {
                display: inline-block;
                margin-top: 10px;
                color: #00e6e6;
                text-decoration: none;
                font-weight: 600;
            }
        </style>
        </head>
        <body>
        <div class='card'>
            <div class='glow-icon'>✨</div>
            <h2>Password Reset Successful!</h2>
            <p><strong>User ID:</strong> $userid</p>
            <p><strong>Email:</strong> $user_emailid</p>
            <div class='password-box'>
                <span class='password-text' id='pw'>$new_password_plain</span>
                <button class='copy-btn' onclick='copyPw()'>Copy</button>
            </div>
            <div class='timer'>⏱ Redirecting in <span id='sec'>60</span> seconds...</div>
            <a href='userlist.php' class='back-link'>⬅ Go Back Now</a>
        </div>

        <script>
            function copyPw(){
                navigator.clipboard.writeText(document.getElementById('pw').innerText);
                alert('✅ Password copied!');
            }
            let s=60;
            const timer=document.getElementById('sec');
            const t=setInterval(()=>{
                s--;
                timer.textContent=s;
                if(s<=0){
                    clearInterval(t);
                    window.location.href='userlist.php';
                }
            },1000);
        </script>
        </body>
        </html>
        ";
    } else {
        echo "❌ Password reset failed.";
    }
} else {
    echo "⚠️ Invalid request.";
}
?>
