<?php
session_start();
$errors = [];
$success = "";
$student_id = null;
$full_name = '';

// Get token from GET (link) or POST (form)
$token = $_POST['token'] ?? $_GET['token'] ?? null;

if (!$token) {
    $errors[] = "Invalid request.";
} else {
    $token_hash = hash("sha256", $token);
    $mysqli = require __DIR__ . "/database.php";

    // Fetch token and student info
    $sql = "SELECT pr.student_id, pr.reset_token_expires_at, a.f_name, a.l_name
            FROM password_resets pr
            JOIN adminstudent a ON pr.student_id = a.student_id
            WHERE pr.reset_token_hash = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("s", $token_hash);
    $stmt->execute();
    $result = $stmt->get_result();
    $record = $result->fetch_assoc();

    if (!$record) {
        $errors[] = "Token not found.";
    } elseif (strtotime($record["reset_token_expires_at"]) <= time()) {
        $errors[] = "Token has expired.";
    } else {
        $student_id = $record['student_id'];
        $full_name = $record['f_name'] . ' ' . $record['l_name'];
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $student_id) {
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validate passwords BEFORE DB update
    if ($password !== $confirm_password) {
        $errors[] = "Passwords must match.";
    }
    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters.";
    }

    // Only update password if no errors
    if (empty($errors)) {
        $password_hash = password_hash($password, PASSWORD_DEFAULT);

        // Update student password
        $sql = "UPDATE adminstudent SET pword = ? WHERE student_id = ?";
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("si", $password_hash, $student_id);
        $stmt->execute();

        // Delete used token
        $sql = "DELETE FROM password_resets WHERE student_id = ?";
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("i", $student_id);
        $stmt->execute();

        // Log in student
        $_SESSION['student_id'] = $student_id;
        $_SESSION['student_name'] = $full_name;

        // Redirect to Student Dashboard
        header("Location: ../studentpanel/Student_Dashboard.php");
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> DWSAS </title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-image: url('../images/bg.jpg');
            background-size: 100% 100%;   
            background-repeat: no-repeat;
            background-position: center;   
            background-attachment: fixed;
            color: #333;
            position: relative; 
            z-index: 1;
            padding: 20px;
        }

        body::before {
            content: "";
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(43, 88, 32, 0.5);
            z-index: 0;
        }


        .container {
            position: relative;
            z-index: 1;
            width: 100%;
            max-width: 320px;
        }

        .form-box {
            width: 100%;
            padding: 10px 15px; 
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            opacity: 0.8;
        }

        h2 {
            font-size: 22px;
            text-align: center;
            margin: 15px 12px;
            color: #2b5820;
        }

        label {
            font-weight: 400;
            color: black;
            display: block;
            margin-bottom: 8px;
            font-size: 11px;
        }

        input[type="password"] {
            width: 100%;
            padding: 8px 12px;
            background: #f5f5f5;
            border: 2px solid #2b5820; 
            border-radius: 6px;       
            font-size: 11px;
            color: #333;
            margin-bottom: 20px;
        }

        input[type="password"]:focus {
            border-color: #5f7e62;
            outline: none;
        }

        .reset-btn {
            width: 40%;
            padding: 8px;
            background: #012a0d;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            font-size: 11px;
            color: #fff;
            font-weight: 600;
            display: block;
            margin: 15px auto 5px;
            text-align: center;
        }

        .reset-btn:hover {
            background: #1a4a1a;
        }

        .error-message {
            color: #dc3545;
            text-align: center;
            margin-bottom: 12px;
            font-size: 11px;
            padding: 8px;
            background-color: #f8d7da;
            border-radius: 5px;
            border: 1px solid #f5c6cb;
        }

        .success-message {
            color: #155724;
            text-align: center;
            margin-bottom: 12px;
            font-size: 11px;
            padding: 8px;
            background-color: #d4edda;
            border-radius: 5px;
            border: 1px solid #c3e6cb;
        }

        .password-container {
            position: relative;
            width: 100%;
        }

        .password-container input {
            width: 100%;
            padding-right: 45px;
        }

        .toggle-icon {
            position: absolute;
            top: 30%;
            right: 15px;
            transform: translateY(-50%);
            font-size: 18px;
            cursor: pointer;
            color: #2b5820;
        }

        .back-btn {
            display: inline-block;
            width: 40%;
            margin: 5px 10px;
            font-size: 11px;
            font-weight: 600;
            padding: 6px 10px;
            background: #3b3b3b;
            color: #fff;
            border-radius: 5px;
            text-decoration: none;
        }

        .back-btn:hover {
            background: #2a2a2a;
        }

        /* Tablet */
        @media screen and (max-width: 768px) {
            body { 
                padding: 15px; 
            }

            .form-box { 
                padding: 30px 25px; 
            }

            h2 { 
                font-size: 16px; 
                margin-bottom: 25px; 
            }

            label {
                color: black;
                font-size: 20px;
            }

            input[type="email"], 
            input[type="password"] { 
                padding: 12px; 
                font-size: 20px; 
                margin-bottom: 15px; 
            }

            .reset-btn { 
                max-width: 70%; 
                padding: 12px; 
                font-size: 22px; 
                margin-top: 20px; 
            }
        }

        /* Mobile phone */
        @media screen and (max-width: 576px) {
            body { 
                padding: 10px; 
                align-items: center;      
                padding-top: 20px;
            }

            .form-box { 
                padding: 25px 20px; 
            }

            h2 { 
                font-size: 22px; 
                margin-bottom: 20px; 
            }

            label {
                color: black;
                font-size: 14px;
            }

            input[type="email"], 
            input[type="password"] { 
                padding: 10px 12px; 
                font-size: 14px; 
                margin-bottom: 12px; 
            }

            .reset-btn { 
                max-width: 50%; 
                padding: 12px; 
                font-size: 16px; 
                margin-top: 20px; 
            }
        }

        /* Small phone */
        @media screen and (max-width: 400px) {
            .form-box { 
                padding: 20px 15px; 
            }
            
            h2 { 
                font-size: 18px; 
                margin-bottom: 20px; 
            }

            p {
                text-align: center;
                color: #333;
                font-size: 12px; 
            }

            label {
                color: black;
                font-size: 12px;
            }

            input[type="email"], 
            input[type="password"] { 
                padding: 10px; 
                font-size: 12px; 
            }

            .reset-btn { 
                max-width: 30%; 
                padding: 11px; 
                font-size: 12px; 
                margin-top: 20px; 
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="form-box">
            <form method="post" action="">
                <h2>Reset Password</h2>

                <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

                <?php if (!empty($errors)): ?>
                    <div class="error-message">
                        <?php foreach($errors as $error): ?>
                            <p><?= htmlspecialchars($error) ?></p>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <?php if ($student_id): ?>
                    <label for="password">New Password</label>
                    <input type="password" id="password" name="password" placeholder="Enter password" required>

                    <label for="pword"> Confirm Password </label>
                    <div class="password-container">
                        <input type="password" id="pword" name="confirm_password" placeholder="Confirm your password" required>
                        
                        <ion-icon name="eye-outline" id="togglePassword" class="toggle-icon"></ion-icon>
                    </div>
                    <button type="submit" class="reset-btn">Reset Password</button>

                    <div style="text-align:center; margin-top:10px;">
                        <a href="forgot_pass.php" class="back-btn"> Back </a>
                    </div>
                <?php endif; ?>

                <?php if (!empty($success)): ?>
                    <div class="success-message">
                        <p><?= htmlspecialchars($success) ?></p>
                    </div>
                    <script>
                        setTimeout(() => {
                            window.location.href = '../studentpanel/Student_Dashboard.php';
                        }, 2000);
                    </script>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <script>
        const togglePassword = document.getElementById("togglePassword");
        const password = document.getElementById("pword");

        let timeout; 

        togglePassword.addEventListener("click", function () {

            if (password.type === "password") {
                // SHOW password
                password.type = "text";
                this.setAttribute("name", "eye-off-outline");

                clearTimeout(timeout);

                // Auto hide after 2 seconds
                timeout = setTimeout(() => {
                    password.type = "password";
                    togglePassword.setAttribute("name", "eye-outline");
                }, 2000);

            } else {
                // HIDE immediately the password if the icon been clicked again
                password.type = "password";
                this.setAttribute("name", "eye-outline");

                clearTimeout(timeout); // stop timer
            }
        });
    </script>
    
    <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
</body>
</html>