<?php
$mysqli = require __DIR__ . "/database.php";
$errors = [];
$success = "";

// Only process if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST["email"] ?? null;

    if (!$email) {
        $errors[] = "Email is required.";
    } else {
        // Fetch student info
        $sql = "SELECT student_id, f_name, l_name FROM adminstudent WHERE email = ?";
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $errors[] = "No account found with that email.";
        } else {
            $student = $result->fetch_assoc();
            $student_id = $student['student_id'];
            $full_name = $student['f_name'] . ' ' . $student['l_name'];

            // Generate reset token
            $token = bin2hex(random_bytes(16));
            $token_hash = hash("sha256", $token);
            $expiry = date("Y-m-d H:i:s", time() + 60 * 10);

            // Insert token
            $sql = "INSERT INTO password_resets (student_id, reset_token_hash, reset_token_expires_at) VALUES (?, ?, ?)";
            $stmt = $mysqli->prepare($sql);
            $stmt->bind_param("iss", $student_id, $token_hash, $expiry);
            $stmt->execute();

            if ($stmt->affected_rows === 0) {
                $errors[] = "Failed to create reset token. Try again.";
            } else {
                // Send email
                $mail = require __DIR__ . "/mailer.php";
                try {
                    $mail->setFrom("wsas.cdlb@gmail.com", "WSAS Administrator");
                    $mail->addAddress($email, $full_name);
                    $mail->Subject = "Password Reset";
                    $mail->isHTML(true);
                    $mail->Body = <<<END
                    <p>Hello $full_name,</p>
                    <p>You requested a password reset. Click the link below to reset your password. This link will expire in 10 minutes.</p>
                    <p><a href="http://192.168.0.106/WSAS/login/reset_pass.php?token=$token">Reset Password</a></p>
                    <p>Best regards,<br>WSAS Administrator</p>
                    END;
                    $mail->send();

                    $success = "A password reset link has been sent to your email. Please check your inbox.";

                } catch (Exception $e) {
                    $errors[] = "Message could not be sent. {$mail->ErrorInfo}";
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <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: 16px;
            text-align: center;
            margin: 15px 12px;
            color: #2b5820;
        }

        p {
            font-size: 11px;
            margin-bottom: 20px;
            text-align: center;
        }

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

        input[type="email"],
        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;
            transition: border-color 0.3s ease;
        }

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

        .submit-btn,
        .back-btn {
            width: 40%;
            padding: 8px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 600;
            display: block;
            margin: 10px auto 5px;
            text-align: center;
            box-sizing: border-box;
            border: none;
            transition: all 0.2s ease;
            cursor: pointer;
        }

        .submit-btn {
            background: #012a0d;
            color: #fff;
        }

        .back-btn {
            background: #3b3b3b;
            color: #fff;
            text-decoration: none;
            margin-bottom: 10px;
        }

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

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

        .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;
        }

        .error-message p,
        .success-message p {
            margin: 0;
        }

        /* 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; 
            }

            p {
                font-size: 14px;
            }

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

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

            .submit-btn { 
                max-width: 30%; 
                padding: 12px; 
                font-size: 16px; 
                margin-top: 20px; 
            }
        }
    </style>

</head>
<body>
    <div class="container">
        <div class="form-box">
            <form method="post">
                <h2> Forgot Password </h2>

                <p> Please enter your <strong>email address</strong>. <br>
                    A reset link will be sent to your email. <br>
                    Use it to reset your password. 
                </p>

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

                <?php if ($success): ?>
                    <div class="success-message">
                        <p><?= htmlspecialchars($success) ?></p>
                    </div>
                <?php endif; ?>

                <label for="email"> Email Address </label>
                <input type="email" id="email" name="email" placeholder="Enter your email" required>
                            
                <button type="submit" name="submit" class="submit-btn"> Send Reset Link </button>
                <a href="student_login.php" class="back-btn"> Back To Login </a>
            </form>
        </div>
    </div>
</body>
</html>