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

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

$token = $_GET['token'] ?? '';
if(!$token) die("Invalid or missing reset link");

// Check token validity
$result = mysqli_query($conn, "SELECT student_id, expires_at, used FROM password_resets WHERE token='$token'");
$reset = mysqli_fetch_assoc($result);

if(!$reset || $reset['used'] || strtotime($reset['expires_at']) < time()){
    die("This link is invalid or expired.");
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $password = $_POST['password'];
    $confirm = $_POST['confirm_password'];

    if ($password !== $confirm) {
        $message = "Passwords do not match.";
        $message_type = 'danger';
    } elseif (strlen($password) < 6) {
        $message = "Password must be at least 6 characters.";
        $message_type = 'danger';
    } else {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        if (mysqli_query($conn, "UPDATE students SET pass='$hashed' WHERE id={$reset['student_id']}")) {
            mysqli_query($conn, "UPDATE password_resets SET used=1 WHERE token='$token'");
            $message = "Password reset successfully! You can now <a href='../index.php' style='color: var(--primary); font-weight: 600;'>login</a>.";
            $message_type = 'success';
        } else {
            $message = "Error updating password. Please try again.";
            $message_type = 'danger';
        }
    }
}
?>

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

        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #a0aec0;
            cursor: pointer;
            padding: 5px;
        }

        .password-toggle:hover {
            color: var(--primary);
        }

        .checkbox-container {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 25px;
            cursor: pointer;
            user-select: none;
            font-size: 14px;
            color: var(--text-light);
        }

        .checkbox-container input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: var(--primary);
        }

        .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-lock"></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 $message; ?></span>
                </div>
            <?php endif; ?>

            <form method="POST" id="resetForm">
                <div class="form-group">
                    <input type="password" 
                           name="password" 
                           id="password"
                           class="form-control" 
                           placeholder="New password (min 6 characters)"
                           required
                           autocomplete="new-password"
                           minlength="6">
                    <span class="input-label">New Password</span>
                    <button type="button" class="password-toggle" onclick="togglePassword('password')" aria-label="Toggle password visibility">
                        <i class="far fa-eye"></i>
                    </button>
                </div>
                
                <div class="form-group">
                    <input type="password" 
                           name="confirm_password" 
                           id="confirm_password"
                           class="form-control" 
                           placeholder="Confirm new password"
                           required
                           autocomplete="new-password"
                           minlength="6">
                    <span class="input-label">Confirm Password</span>
                    <button type="button" class="password-toggle" onclick="togglePassword('confirm_password')" aria-label="Toggle password visibility">
                        <i class="far fa-eye"></i>
                    </button>
                </div>

                <div class="checkbox-container">
                    <input type="checkbox" id="showPassword" onclick="toggleAllPasswords()">
                    <label for="showPassword">Show Passwords</label>
                </div>

                <button type="submit" class="btn btn-reset" id="resetBtn">
                    <span id="btnText">Reset Password</span>
                    <i class="fas fa-sync-alt"></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>
        function togglePassword(inputId) {
            const passwordInput = document.getElementById(inputId);
            const toggleIcon = passwordInput.parentElement.querySelector('.password-toggle i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleIcon.classList.remove('fa-eye');
                toggleIcon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                toggleIcon.classList.remove('fa-eye-slash');
                toggleIcon.classList.add('fa-eye');
            }
        }

        function toggleAllPasswords() {
            const showPasswordCheckbox = document.getElementById('showPassword');
            const passwordInputs = [
                document.getElementById('password'),
                document.getElementById('confirm_password')
            ];
            
            passwordInputs.forEach(input => {
                if (input) {
                    const toggleIcon = input.parentElement.querySelector('.password-toggle i');
                    if (showPasswordCheckbox.checked) {
                        input.type = 'text';
                        toggleIcon.classList.remove('fa-eye');
                        toggleIcon.classList.add('fa-eye-slash');
                    } else {
                        input.type = 'password';
                        toggleIcon.classList.remove('fa-eye-slash');
                        toggleIcon.classList.add('fa-eye');
                    }
                }
            });
        }

        // Form submission handling
        document.getElementById('resetForm').addEventListener('submit', function(e) {
            const resetBtn = document.getElementById('resetBtn');
            const btnText = document.getElementById('btnText');
            const arrowIcon = document.querySelector('.btn-reset i');
            const spinner = document.getElementById('loadingSpinner');
            
            // Validate passwords match
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (password !== confirmPassword) {
                e.preventDefault();
                alert('Passwords do not match!');
                return;
            }
            
            if (password.length < 6) {
                e.preventDefault();
                alert('Password must be at least 6 characters long!');
                return;
            }
            
            // Disable button and show loading
            resetBtn.disabled = true;
            btnText.textContent = 'Processing...';
            arrowIcon.style.display = 'none';
            spinner.style.display = 'block';
            
            // Prevent form resubmission
            setTimeout(() => {
                resetBtn.disabled = false;
            }, 3000);
        });

        // Auto-hide alerts after 5 seconds
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                setTimeout(() => {
                    alert.style.opacity = '0';
                    alert.style.transform = 'translateY(-10px)';
                    setTimeout(() => alert.remove(), 300);
                }, 5000);
            });

            // Add floating label effect on focus
            const inputs = document.querySelectorAll('.form-control');
            inputs.forEach(input => {
                input.addEventListener('focus', function() {
                    this.parentElement.querySelector('.input-label').style.opacity = '1';
                });
                
                input.addEventListener('blur', function() {
                    if (!this.value) {
                        this.parentElement.querySelector('.input-label').style.opacity = '0';
                    }
                });
                
                // Check on page load
                if (input.value) {
                    input.parentElement.querySelector('.input-label').style.opacity = '1';
                }
            });

            // Real-time password validation
            const passwordInput = document.getElementById('password');
            const confirmInput = document.getElementById('confirm_password');
            
            function validatePasswords() {
                if (passwordInput.value && confirmInput.value) {
                    if (passwordInput.value === confirmInput.value) {
                        confirmInput.style.borderColor = '#10b981';
                        confirmInput.parentElement.querySelector('.input-label').style.color = '#10b981';
                    } else {
                        confirmInput.style.borderColor = '#ef4444';
                        confirmInput.parentElement.querySelector('.input-label').style.color = '#ef4444';
                    }
                }
            }
            
            passwordInput.addEventListener('input', validatePasswords);
            confirmInput.addEventListener('input', validatePasswords);
        });
    </script>
</body>
</html>