<?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();
}

$error = '';
$success = '';
$token = $_GET['token'] ?? '';
$valid_token = false;
$user_id = null;

// Verify token
if (!empty($token)) {
    try {
        $db = new Database();
        $conn = $db->getConnection();
        
        $stmt = $conn->prepare("
            SELECT pr.user_id, u.username, u.full_name 
            FROM password_resets pr
            JOIN users u ON pr.user_id = u.id
            WHERE pr.token = ? AND pr.expires_at > NOW() AND pr.used = 0
        ");
        $stmt->execute([$token]);
        $reset_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($reset_data) {
            $valid_token = true;
            $user_id = $reset_data['user_id'];
        } else {
            $error = __('invalid_expired_link');
        }
    } catch (PDOException $e) {
        $error = __('system_error_try_later');
        error_log("Reset password error: " . $e->getMessage());
    }
} else {
    $error = __('invalid_link');
}

// Process password reset
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $valid_token) {
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    if (empty($new_password) || empty($confirm_password)) {
        $error = __('enter_password_and_confirm');
    } elseif (strlen($new_password) < 6) {
        $error = __('password_min_6_chars');
    } elseif ($new_password !== $confirm_password) {
        $error = __('passwords_not_match');
    } else {
        try {
            // Update password
            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->execute([$new_password, $user_id]);
            
            // Mark token as used
            $stmt = $conn->prepare("UPDATE password_resets SET used = 1 WHERE token = ?");
            $stmt->execute([$token]);
            
            // Log activity
            $stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, ip_address) VALUES (?, ?, ?)");
            $stmt->execute([$user_id, __('password_reset_activity'), $_SERVER['REMOTE_ADDR'] ?? null]);
            
            $success = __('password_changed_success');
            $valid_token = false; // Prevent further submissions
            
        } catch (PDOException $e) {
            $error = __('error_updating_password');
            error_log("Password update 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 __('reset_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;
        }
        
        .reset-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;
        }
        
        .reset-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);
        }
        
        .key-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);
        }
        
        .input-group .form-control {
            border-left: none;
        }
        
        .input-group .btn {
            border-radius: 0 10px 10px 0;
            border: 2px solid #e9ecef;
            border-left: none;
        }
        
        .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;
        }
        
        .alert {
            border-radius: 10px;
            border: none;
            font-size: 0.9rem;
            padding: 12px 15px;
        }
        
        .password-requirements {
            font-size: 0.8rem;
            color: #6c757d;
            margin-top: 8px;
        }
        
        .password-requirements ul {
            margin: 5px 0 0 0;
            padding-right: 20px;
        }
        
        .password-strength {
            height: 5px;
            border-radius: 3px;
            margin-top: 8px;
            background: #e9ecef;
            overflow: hidden;
        }
        
        .password-strength-bar {
            height: 100%;
            transition: all 0.3s ease;
            width: 0%;
        }
        
        .strength-weak { background: #dc3545; width: 33%; }
        .strength-medium { background: #ffc107; width: 66%; }
        .strength-strong { background: #28a745; width: 100%; }
        
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .reset-password-form {
                padding: 30px 25px;
            }
            
            .page-title {
                font-size: 1.3rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="reset-password-container">
            <div class="row g-0 justify-content-center">
                <div class="col-lg-6 col-md-8 col-sm-10">
                    <div class="reset-password-form">
                        <div class="text-center mb-4">
                            <div class="logo-container">
                                <div class="logo-circle">
                                    <i class="fas fa-key key-icon"></i>
                                </div>
                            </div>
                            <h2 class="page-title"><?php echo __('reset_password_page'); ?></h2>
                            <p class="page-subtitle">
                                <?php echo __('reset_password_subtitle'); ?>
                            </p>
                        </div>
                        
                        <?php if ($error): ?>
                            <div class="alert alert-danger" role="alert">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <?php echo htmlspecialchars($error); ?>
                            </div>
                            <div class="text-center mt-3">
                                <a href="forgot_password.php" class="btn btn-primary">
                                    <?php echo __('request_new_link'); ?>
                                </a>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                            <div class="alert alert-success" role="alert">
                                <i class="fas fa-check-circle me-2"></i>
                                <?php echo htmlspecialchars($success); ?>
                            </div>
                            <div class="text-center mt-3">
                                <a href="login.php" class="btn btn-reset">
                                    <i class="fas fa-sign-in-alt me-2"></i>
                                    <?php echo __('login'); ?>
                                </a>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($valid_token && !$success): ?>
                        <form method="POST" class="needs-validation" novalidate>
                            <div class="mb-3">
                                <label for="new_password" class="form-label">
                                    <i class="fas fa-lock me-2"></i><?php echo __('new_password_label'); ?>
                                </label>
                                <div class="input-group">
                                    <input type="password" class="form-control" id="new_password" name="new_password" 
                                           required minlength="6" autocomplete="new-password">
                                    <button class="btn btn-outline-secondary" type="button" id="toggleNewPassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <div class="password-strength">
                                    <div class="password-strength-bar" id="strengthBar"></div>
                                </div>
                                <div class="password-requirements">
                                    <small><?php echo __('password_requirements_title'); ?></small>
                                    <ul>
                                        <li><?php echo __('min_6_chars'); ?></li>
                                        <li><?php echo __('uppercase_lowercase'); ?></li>
                                        <li><?php echo __('numbers_symbols'); ?></li>
                                    </ul>
                                </div>
                                <div class="invalid-feedback">
                                    <?php echo __('password_min_6_chars'); ?>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="confirm_password" class="form-label">
                                    <i class="fas fa-lock me-2"></i><?php echo __('confirm_password_label'); ?>
                                </label>
                                <div class="input-group">
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" 
                                           required minlength="6" autocomplete="new-password">
                                    <button class="btn btn-outline-secondary" type="button" id="toggleConfirmPassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <div class="invalid-feedback">
                                    <?php echo __('enter_password_and_confirm'); ?>
                                </div>
                            </div>
                            
                            <div class="d-grid mb-3">
                                <button type="submit" class="btn btn-reset">
                                    <i class="fas fa-check me-2"></i>
                                    <?php echo __('change_password_button'); ?>
                                </button>
                            </div>
                        </form>
                        <?php endif; ?>
                        
                        <div class="text-center mt-3">
                            <small class="text-muted">
                                <a href="login.php" style="color: #667eea; text-decoration: none;">
                                    <i class="fas fa-arrow-<?php echo $dir == 'rtl' ? 'right' : 'left'; ?> me-1"></i>
                                    <?php echo __('back_to_login'); ?>
                                </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) {
                        const newPassword = document.getElementById('new_password').value;
                        const confirmPassword = document.getElementById('confirm_password').value;
                        
                        if (newPassword !== confirmPassword) {
                            event.preventDefault();
                            event.stopPropagation();
                            alert('<?php echo __('passwords_not_match'); ?>');
                            return false;
                        }
                        
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
        
        // Toggle password visibility
        document.getElementById('toggleNewPassword')?.addEventListener('click', function() {
            togglePasswordVisibility('new_password', this);
        });
        
        document.getElementById('toggleConfirmPassword')?.addEventListener('click', function() {
            togglePasswordVisibility('confirm_password', this);
        });
        
        function togglePasswordVisibility(fieldId, button) {
            const field = document.getElementById(fieldId);
            const icon = button.querySelector('i');
            
            if (field.type === 'password') {
                field.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                field.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }
        
        // Password strength indicator
        document.getElementById('new_password')?.addEventListener('input', function() {
            const password = this.value;
            const strengthBar = document.getElementById('strengthBar');
            
            let strength = 0;
            if (password.length >= 6) strength++;
            if (password.length >= 10) strength++;
            if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
            if (/\d/.test(password)) strength++;
            if (/[^a-zA-Z0-9]/.test(password)) strength++;
            
            strengthBar.className = 'password-strength-bar';
            if (strength <= 2) {
                strengthBar.classList.add('strength-weak');
            } else if (strength <= 4) {
                strengthBar.classList.add('strength-medium');
            } else {
                strengthBar.classList.add('strength-strong');
            }
        });
        
        // Auto-focus on new password field
        document.getElementById('new_password')?.focus();
    </script>
</body>
</html>

