<?php
session_start();
include 'config/db.php';

$error = '';
$success = '';
$show_form = false;
$email = '';
$token = '';

// Get token from URL
$token = isset($_GET['token']) ? $_GET['token'] : '';

if (empty($token)) {
    $error = "Invalid reset link. Please request a new password reset.";
} else {
    // Verify token
    $result = $conn->query("SELECT * FROM password_resets WHERE token='$token' AND used=0 AND expires_at > NOW()");
    if ($result->num_rows > 0) {
        $reset = $result->fetch_assoc();
        $email = $reset['email'];
        $show_form = true;
    } else {
        $error = "This reset link has expired or already been used. Please request a new password reset.";
    }
}

// Process password reset
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['reset_password'])) {
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    $token = $_POST['token'];
    
    if (strlen($new_password) < 6) {
        $error = "Password must be at least 6 characters long.";
    } elseif ($new_password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        // Verify token again
        $result = $conn->query("SELECT * FROM password_resets WHERE token='$token' AND used=0 AND expires_at > NOW()");
        if ($result->num_rows > 0) {
            $reset = $result->fetch_assoc();
            $email = $reset['email'];
            
            // Update password
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password=? WHERE email=?");
            $stmt->bind_param("ss", $hashed_password, $email);
            
            if ($stmt->execute()) {
                // Mark token as used
                $conn->query("UPDATE password_resets SET used=1 WHERE token='$token'");
                $success = "Password has been reset successfully! You can now login with your new password.";
                $show_form = false;
            } else {
                $error = "Error resetting password. Please try again.";
            }
            $stmt->close();
        } else {
            $error = "Invalid or expired reset link.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Reset Password - BMYA-SHELDANG</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 500px;
        }

        .card {
            background: white;
            border-radius: 24px;
            padding: 40px 32px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
            position: relative;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .back-home-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            background: #f0f0f0;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            color: #666;
            transition: all 0.3s;
        }

        .back-home-btn:hover {
            background: #667eea;
            color: white;
            transform: translateX(-3px);
        }

        .logo-section {
            text-align: center;
            margin-bottom: 32px;
        }

        .logo-image {
            width: 70px;
            height: 70px;
            object-fit: contain;
            margin: 0 auto 16px;
            display: block;
        }

        .logo-section h2 {
            font-size: 1.5rem;
            color: #333;
            font-weight: 600;
        }

        .logo-section p {
            font-size: 0.85rem;
            color: #666;
            margin-top: 5px;
        }

        .alert {
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.85rem;
            animation: slideIn 0.3s ease;
        }

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

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

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

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

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 0.85rem;
            font-weight: 500;
            color: #333;
        }

        .form-group label i {
            margin-right: 6px;
            color: #667eea;
        }

        .input-wrapper {
            position: relative;
        }

        .input-wrapper i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
            font-size: 1rem;
        }

        .input-wrapper input {
            width: 100%;
            padding: 12px 12px 12px 42px;
            border: 1px solid #e0e0e0;
            border-radius: 12px;
            font-size: 0.9rem;
            font-family: 'Poppins', sans-serif;
            transition: all 0.3s;
            outline: none;
        }

        .input-wrapper input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .password-toggle {
            position: absolute;
            right: 14px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #999;
            transition: color 0.3s;
            z-index: 10;
        }

        .password-toggle:hover {
            color: #667eea;
        }

        .btn-submit {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .btn-login {
            display: block;
            text-align: center;
            margin-top: 20px;
            color: #667eea;
            text-decoration: none;
            font-size: 0.85rem;
        }

        .btn-login:hover {
            text-decoration: underline;
        }

        .password-requirements {
            font-size: 0.7rem;
            color: #999;
            margin-top: 5px;
        }

        @media (max-width: 480px) {
            .card {
                padding: 32px 24px;
            }
            
            .logo-image {
                width: 55px;
                height: 55px;
            }
            
            .logo-section h2 {
                font-size: 1.3rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <a href="login.php" class="back-home-btn" title="Back to Login">
                <i class="fas fa-arrow-left"></i>
            </a>

            <div class="logo-section">
                <img src="assets/images/logo.png" 
                     alt="BMYA-SHELDANG Logo" 
                     class="logo-image"
                     onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3E%3Ccircle cx=%2750%27 cy=%2750%27 r=%2745%27 fill=%27%23667eea%27/%3E%3Ctext x=%2750%27 y=%2770%27 text-anchor=%27middle%27 fill=%27white%27 font-size=%2740%27 font-weight=%27bold%27%3EB%3C/text%3E%3C/svg%3E'">
                <h2>Reset Password</h2>
                <p>Create a new password for your account</p>
            </div>

            <?php if($error): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?= $error ?></span>
            </div>
            <?php endif; ?>

            <?php if($success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?= $success ?></span>
            </div>
            <div style="text-align: center; margin-top: 20px;">
                <a href="login.php" class="btn-submit" style="display: inline-block; width: auto; padding: 10px 20px;">
                    <i class="fas fa-sign-in-alt"></i> Go to Login
                </a>
            </div>
            <?php endif; ?>

            <?php if($show_form && !$success): ?>
            <form method="POST">
                <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
                
                <div class="form-group">
                    <label><i class="fas fa-lock"></i> New Password</label>
                    <div class="input-wrapper">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="new_password" id="new_password" required placeholder="Enter new password">
                        <i class="fas fa-eye password-toggle" id="toggleNewPassword"></i>
                    </div>
                    <div class="password-requirements">
                        <i class="fas fa-info-circle"></i> Password must be at least 6 characters
                    </div>
                </div>

                <div class="form-group">
                    <label><i class="fas fa-check-circle"></i> Confirm Password</label>
                    <div class="input-wrapper">
                        <i class="fas fa-check-circle"></i>
                        <input type="password" name="confirm_password" id="confirm_password" required placeholder="Confirm new password">
                        <i class="fas fa-eye password-toggle" id="toggleConfirmPassword"></i>
                    </div>
                </div>

                <button type="submit" name="reset_password" class="btn-submit">
                    <i class="fas fa-save"></i>
                    Reset Password
                </button>
            </form>

            <a href="login.php" class="btn-login">
                <i class="fas fa-arrow-left"></i> Back to Login
            </a>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Password visibility toggle for new password
        const toggleNewPassword = document.getElementById('toggleNewPassword');
        const newPassword = document.getElementById('new_password');
        
        if (toggleNewPassword && newPassword) {
            toggleNewPassword.addEventListener('click', function() {
                const type = newPassword.getAttribute('type') === 'password' ? 'text' : 'password';
                newPassword.setAttribute('type', type);
                this.classList.toggle('fa-eye');
                this.classList.toggle('fa-eye-slash');
            });
        }
        
        // Password visibility toggle for confirm password
        const toggleConfirmPassword = document.getElementById('toggleConfirmPassword');
        const confirmPassword = document.getElementById('confirm_password');
        
        if (toggleConfirmPassword && confirmPassword) {
            toggleConfirmPassword.addEventListener('click', function() {
                const type = confirmPassword.getAttribute('type') === 'password' ? 'text' : 'password';
                confirmPassword.setAttribute('type', type);
                this.classList.toggle('fa-eye');
                this.classList.toggle('fa-eye-slash');
            });
        }
    </script>
</body>
</html>