<?php
session_start();
require_once 'config/database.php';
require_once 'includes/translation.php';

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "index.php");
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = trim($_POST['email']);
    
    if (empty($email)) {
        $message = __('please_enter_email');
        $message_type = 'danger';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = __('invalid_email');
        $message_type = 'danger';
    } else {
        try {
            $db = new Database();
            $conn = $db->getConnection();
            
            // Check if email exists
            $stmt = $conn->prepare("SELECT id, username, full_name FROM users WHERE email = ? AND is_active = 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                // Generate reset token
                $token = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                // Store token in database
                $stmt = $conn->prepare("INSERT INTO password_resets (user_id, token, expires_at) VALUES (?, ?, ?)");
                $stmt->execute([$user['id'], $token, $expires]);
                
                // In a real application, send email here
                // For now, we'll just show a success message
                $message = __('reset_link_sent');
                $message_type = 'success';
                
                // Log the activity
                $stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, ip_address) VALUES (?, ?, ?)");
                $stmt->execute([$user['id'], __('password_reset_request'), $_SERVER['REMOTE_ADDR'] ?? null]);
                
            } else {
                // Don't reveal if email exists or not for security
                $message = __('email_check_message');
                $message_type = 'info';
            }
        } catch (PDOException $e) {
            $message = __('system_error_try_later');
            $message_type = 'danger';
            error_log("Forgot password error: " . $e->getMessage());
        }
    }
}

$lang = Translation::getLanguage();
$dir = Translation::getDirection();
?>

<!DOCTYPE html>
<html lang="<?php echo $lang; ?>" dir="<?php echo $dir; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo __('forgot_password_page'); ?> - <?php echo __('system_name'); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        .forgot-password-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            max-width: 450px;
            width: 100%;
            margin: 0 auto;
        }
        
        .forgot-password-form {
            padding: 40px 30px;
        }
        
        .logo-container {
            width: 80px;
            height: 80px;
            margin: 0 auto 20px;
            position: relative;
        }
        
        .logo-circle {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .lock-icon {
            font-size: 2rem;
            color: white;
        }
        
        .page-title {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2c3e50;
            margin: 15px 0 10px;
        }
        
        .page-subtitle {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 25px;
            line-height: 1.5;
        }
        
        .form-label {
            font-weight: 500;
            color: #495057;
            margin-bottom: 8px;
            font-size: 0.9rem;
        }
        
        .form-control {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 12px 15px;
            font-size: 15px;
            transition: all 0.3s ease;
            height: auto;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-reset {
            background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-size: 15px;
            font-weight: 600;
            color: white;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .btn-reset:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
            color: white;
        }
        
        .btn-back {
            background: #6c757d;
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-size: 15px;
            font-weight: 600;
            color: white;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .btn-back:hover {
            background: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.4);
            color: white;
        }
        
        .alert {
            border-radius: 10px;
            border: none;
            font-size: 0.9rem;
            padding: 12px 15px;
        }
        
        .back-to-login {
            font-size: 0.9rem;
            margin-top: 20px;
        }
        
        .back-to-login a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }
        
        .back-to-login a:hover {
            text-decoration: underline;
        }
        
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .forgot-password-form {
                padding: 30px 25px;
            }
            
            .page-title {
                font-size: 1.3rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="forgot-password-container">
            <div class="row g-0 justify-content-center">
                <div class="col-lg-6 col-md-8 col-sm-10">
                    <div class="forgot-password-form">
                        <div class="text-center mb-4">
                            <div class="logo-container">
                                <div class="logo-circle">
                                    <i class="fas fa-lock lock-icon"></i>
                                </div>
                            </div>
                            <h2 class="page-title"><?php echo __('forgot_password_page'); ?></h2>
                            <p class="page-subtitle">
                                <?php echo __('forgot_password_subtitle'); ?>
                            </p>
                        </div>
                        
                        <?php if ($message): ?>
                            <div class="alert alert-<?php echo $message_type; ?>" role="alert">
                                <i class="fas fa-<?php echo $message_type == 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
                                <?php echo htmlspecialchars($message); ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" class="needs-validation" novalidate>
                            <div class="mb-4">
                                <label for="email" class="form-label">
                                    <i class="fas fa-envelope me-2"></i><?php echo __('email'); ?>
                                </label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" 
                                       required placeholder="example@hospital.com">
                                <div class="invalid-feedback">
                                    <?php echo __('enter_valid_email'); ?>
                                </div>
                            </div>
                            
                            <div class="d-grid mb-3">
                                <button type="submit" class="btn btn-reset">
                                    <i class="fas fa-paper-plane me-2"></i>
                                    <?php echo __('send_reset_link'); ?>
                                </button>
                            </div>
                            
                            <div class="d-grid">
                                <a href="login.php" class="btn btn-back">
                                    <i class="fas fa-arrow-<?php echo $dir == 'rtl' ? 'right' : 'left'; ?> me-2"></i>
                                    <?php echo __('back_to_login'); ?>
                                </a>
                            </div>
                        </form>
                        
                        <div class="text-center back-to-login">
                            <small class="text-muted">
                                <?php echo __('remembered_password'); ?> 
                                <a href="login.php"><?php echo __('login_now'); ?></a>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Form validation
        (function() {
            'use strict';
            window.addEventListener('load', function() {
                var forms = document.getElementsByClassName('needs-validation');
                var validation = Array.prototype.filter.call(forms, function(form) {
                    form.addEventListener('submit', function(event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
        
        // Auto-focus on email field
        document.getElementById('email').focus();
    </script>
</body>
</html>

