<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../email/src/Exception.php";
include "../email/src/PHPMailer.php";
include "../email/src/SMTP.php";

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

include "../include/config.php";
include "../../color.php";

$message = '';
$message_type = 'info';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = mysqli_real_escape_string($conn, $_POST['email']);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Please enter a valid email address";
        $message_type = 'danger';
    } else {
        $result = mysqli_query($conn, "SELECT id, studentname, email FROM students WHERE email='$email' AND status='active'");
        $student = mysqli_fetch_assoc($result);

        if ($student) {
            $token = bin2hex(random_bytes(32));
            $expires = date("Y-m-d H:i:s", strtotime('+1 hour'));

            // Delete any existing tokens for this student
            mysqli_query($conn, "DELETE FROM password_resets WHERE student_id = {$student['id']}");
            
            // Insert new token
            mysqli_query($conn, "INSERT INTO password_resets (student_id, token, expires_at, used) 
                                 VALUES ({$student['id']}, '$token', '$expires', 0)");

            $resetLink = "https://unicohsuniversity.com/login/students/login/reset_password.php?token=$token";

            try {
                $mail = new PHPMailer(true);
                
                // Server settings
                $mail->isSMTP();
                $mail->Host       = 'unicohsuniversity.com';
                $mail->SMTPAuth   = true;
                $mail->Username   = 'portal@unicohsuniversity.com';
                $mail->Password   = '@mypass1996';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port       = 587;
                
                // Get admin info
                $query = "SELECT * FROM admin LIMIT 1";
                $result = mysqli_query($conn, $query);
                $row = mysqli_fetch_assoc($result);
                $sname = $row['sname'] ?? 'Unicohs University';

                // Recipients
                $mail->setFrom('portal@unicohsuniversity.com', $sname);
                $mail->addAddress($student['email'], $student['studentname']);

                // Content
                $mail->isHTML(true);
                $mail->Subject = 'Password Reset Request - ' . $sname;
                $mail->Body    = "
                    <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
                        <div style='background-color: #4a6cf7; padding: 20px; text-align: center;'>
                            <h2 style='color: white; margin: 0;'>$sname</h2>
                        </div>
                        <div style='padding: 30px; background-color: #f9f9f9;'>
                            <h3 style='color: #333;'>Password Reset Request</h3>
                            <p>Dear <strong>{$student['studentname']}</strong>,</p>
                            <p>You have requested to reset your password for the student portal.</p>
                            <p>To reset your password, please click the button below:</p>
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='$resetLink' style='background-color: #4a6cf7; color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;'>Reset My Password</a>
                            </div>
                            <p>Or copy and paste this link into your browser:</p>
                            <p style='background-color: #eee; padding: 10px; border-radius: 5px; word-break: break-all;'>
                                $resetLink
                            </p>
                            <p><strong>Important:</strong> This link will expire in 1 hour for security reasons.</p>
                            <p>If you did not request a password reset, please ignore this email.</p>
                        </div>
                    </div>
                ";
                
                $mail->AltBody = "Password Reset Link: $resetLink";

                $mail->send();
                $message = "Password reset link has been sent to your email.";
                $message_type = 'success';
                
            } catch (Exception $e) {
                $message = "Email Error: " . $e->getMessage();
                $message_type = 'danger';
            }
        } else {
            $message = "If this email is registered, a password reset link has been sent.";
            $message_type = 'success';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Login | Secure Access</title>
    
    <!-- Bootstrap 5 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="logo.png">

    <style>
        :root {
            --primary-dark: #3a56d7;
            --text-dark: #2d3748;
            --text-light: #718096;
            --shadow: 0 10px 30px rgba(0,0,0,0.08);
            --shadow-hover: 0 15px 40px rgba(0,0,0,0.12);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            --success-bg: #d1fae5;
            --success-text: #065f46;
            --danger-bg: #fee2e2;
            --danger-text: #991b1b;
            --info-bg: #dbeafe;
            --info-text: #1e40af;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Josefin Sans", sans-serif;
            color: var(--text-dark);
            min-height: 100vh;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            position: relative;
            overflow-x: hidden;
        }

        /* Background decorative elements */
        body::before {
            content: '';
            position: absolute;
            width: 300px;
            height: 300px;
            border-radius: 50%;
            background: linear-gradient(135deg, rgba(74, 108, 247, 0.1) 0%, rgba(74, 108, 247, 0.05) 100%);
            top: -150px;
            right: -150px;
            z-index: 0;
        }

        body::after {
            content: '';
            position: absolute;
            width: 200px;
            height: 200px;
            border-radius: 50%;
            background: linear-gradient(135deg, rgba(74, 108, 247, 0.08) 0%, rgba(74, 108, 247, 0.03) 100%);
            bottom: -100px;
            left: -100px;
            z-index: 0;
        }

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

        .reset-card {
            background: white;
            border-radius: 20px;
            padding: 40px 35px;
            box-shadow: var(--shadow);
            transition: var(--transition);
            border: 1px solid rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
        }

        .reset-card:hover {
            box-shadow: var(--shadow-hover);
            transform: translateY(-5px);
        }

        .logo-container {
            text-align: center;
            margin-bottom: 30px;
        }

        .logo-circle {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: var(--primary);
            margin: 0 auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8px 20px rgba(74, 108, 247, 0.3);
            position: relative;
            overflow: hidden;
        }

        .logo-circle img {
            width: 60px;
            filter: brightness(0) invert(1);
            position: relative;
            z-index: 2;
        }

        .reset-title {
            text-align: center;
            margin-bottom: 30px;
            color: var(--text-dark);
            font-weight: 700;
            font-size: 1.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .reset-title i {
            color: var(--primary);
            font-size: 1.5rem;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-control {
            border-radius: 12px;
            padding: 14px 20px;
            border: 2px solid #e2e8f0;
            background: #f8fafc;
            color: var(--text-dark);
            font-size: 15px;
            transition: var(--transition);
            font-weight: 500;
        }

        .form-control:focus {
            border-color: var(--primary);
            background: white;
            box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
            outline: none;
        }

        .form-control::placeholder {
            color: #a0aec0;
            font-weight: 400;
        }

        .btn-reset {
            width: 100%;
            padding: 14px;
            border-radius: 12px;
            border: none;
            font-weight: 600;
            font-size: 16px;
            background: var(--primary);
            color: white;
            transition: var(--transition);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            letter-spacing: 0.5px;
        }

        .btn-reset:hover {
                        background: var(--primary);

            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(74, 108, 247, 0.3);
        }

        .btn-reset:active {
            transform: translateY(0);
        }

        .btn-reset:disabled {
            background: #cbd5e0;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .links {
            margin-top: 25px;
            text-align: center;
            padding-top: 25px;
            border-top: 1px solid #e2e8f0;
        }

        .links a {
            color: var(--primary);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 5px;
            margin: 0 10px;
        }

        .links a:hover {
            color: var(--primary-dark);
            text-decoration: underline;
        }

        .alert {
            border-radius: 12px;
            border: none;
            padding: 12px 16px;
            margin-bottom: 20px;
            font-size: 14px;
            font-weight: 500;
            animation: fadeIn 0.6s ease-out;
        }

        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-danger {
            background-color: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .alert-info {
            background-color: #dbeafe;
            color: #1e40af;
            border-left: 4px solid #3b82f6;
        }

        .alert i {
            margin-right: 10px;
        }

        .loading-spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .reset-card {
            animation: fadeIn 0.6s ease-out;
        }

        /* Input label effect */
        .input-label {
            position: absolute;
            left: 15px;
            top: -8px;
            background: white;
            padding: 0 8px;
            font-size: 12px;
            color: var(--primary);
            font-weight: 600;
            opacity: 0;
            transition: var(--transition);
        }

        .form-control:focus + .input-label {
            opacity: 1;
        }

        /* Responsive Design */
        @media (max-width: 576px) {
            .reset-card {
                padding: 30px 25px;
            }
            
            .logo-circle {
                width: 80px;
                height: 80px;
            }
            
            .logo-circle img {
                width: 50px;
            }
            
            body {
                padding: 15px;
            }
            
            body::before,
            body::after {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="reset-container">
        <div class="reset-card">
            <div class="logo-container">
                <div class="logo-circle">
                    <img src="logo.png" alt="Company Logo">
                </div>
                <h1 class="reset-title">
                    <i class="fas fa-key"></i> Student Password Reset
                </h1>
            </div>

            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?>">
                    <?php 
                        $icon = '';
                        if ($message_type == 'success') $icon = 'fas fa-check-circle';
                        elseif ($message_type == 'danger') $icon = 'fas fa-exclamation-circle';
                        else $icon = 'fas fa-info-circle';
                    ?>
                    <i class="<?php echo $icon; ?>"></i>
                    <span><?php echo htmlspecialchars($message); ?></span>
                </div>
            <?php endif; ?>

            <form method="POST" id="resetForm">
                <div class="form-group">
                    <input type="email" 
                           name="email" 
                           id="email"
                           class="form-control" 
                           placeholder="Enter your registered student email"
                           required
                           autocomplete="email"
                           autofocus>
                    <span class="input-label">Student Email Address</span>
                </div>

                <button type="submit" class="btn btn-reset" id="resetBtn">
                    <span id="btnText">Send Reset Link</span>
                    <i class="fas fa-paper-plane"></i>
                    <div class="loading-spinner" id="loadingSpinner"></div>
                </button>

                <div class="links">
                    <a href="../index.php">
                        <i class="fas fa-arrow-left"></i> Back to Login
                    </a>
                    <a href="#" onclick="alert('Please contact student support for assistance')">
                        <i class="fas fa-headset"></i> Student Support
                    </a>
                </div>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const resetForm = document.getElementById('resetForm');
            const resetBtn = document.getElementById('resetBtn');
            const btnText = document.getElementById('btnText');
            const btnIcon = resetBtn.querySelector('i');
            const spinner = document.getElementById('loadingSpinner');
            const emailInput = document.getElementById('email');

            // Add floating label effect
            emailInput.addEventListener('focus', function() {
                this.parentElement.querySelector('.input-label').style.opacity = '1';
            });
            
            emailInput.addEventListener('blur', function() {
                if (!this.value) {
                    this.parentElement.querySelector('.input-label').style.opacity = '0';
                }
            });
            
            // Check on page load
            if (emailInput.value) {
                emailInput.parentElement.querySelector('.input-label').style.opacity = '1';
            }

            // Form submission handling
            resetForm.addEventListener('submit', function(e) {
                // Disable button and show loading
                resetBtn.disabled = true;
                btnText.textContent = 'Sending...';
                btnIcon.style.display = 'none';
                spinner.style.display = 'block';
                
                // Add slight delay for better UX
                setTimeout(() => {
                    resetBtn.disabled = false;
                }, 3000);
            });

            // Auto-hide alerts after 8 seconds
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                setTimeout(() => {
                    alert.style.transition = 'opacity 0.5s, transform 0.5s';
                    alert.style.opacity = '0';
                    alert.style.transform = 'translateY(-10px)';
                    setTimeout(() => {
                        if (alert.parentNode) {
                            alert.parentNode.removeChild(alert);
                        }
                    }, 500);
                }, 8000);
            });

            // Focus email input if alert is present
            if (document.querySelector('.alert-danger')) {
                emailInput.focus();
                emailInput.select();
            }
        });
    </script>
</body>
</html>