<?php
/**
 * Reset Password Page
 * Allows users to set a new password using reset token
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';
require_once 'includes/mailer.php';

initSecureSession();

// Redirect if already logged in
if(isAuthenticated() && validateSession()) {
    header('Location: dashboard');
    exit;
}

$error = '';
$success = '';
$validToken = false;
$tokenData = null;

// Get token from URL
$token = $_GET['token'] ?? $_POST['token'] ?? '';

if (empty($token)) {
    $error = 'Invalid or missing reset token. Please request a new password reset.';
} else {
    // Verify token
    $tokenData = verifyPasswordResetToken($conn, $token);
    if ($tokenData) {
        $validToken = true;
    } else {
        $error = 'This password reset link has expired or is invalid. Please request a new one.';
    }
}

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST' && $validToken) {
    // Verify CSRF token
    $csrf_token = $_POST['csrf_token'] ?? '';
    if (!verifyCSRFToken($csrf_token)) {
        $error = 'Security token expired. Please try again.';
    } else {
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        // Validate password strength
        $password_errors = validatePasswordStrength($password);
        if (!empty($password_errors)) {
            $error = implode('. ', $password_errors);
        } elseif ($password !== $confirm_password) {
            $error = 'Passwords do not match.';
        } else {
            // Update password
            $user_id = $tokenData['user_id'];
            $new_hash = hashPassword($password);
            $new_hash_escaped = mysqli_real_escape_string($conn, $new_hash);

            if (mysqli_query($conn, "UPDATE users SET password = '$new_hash_escaped' WHERE id = $user_id")) {
                // Mark token as used
                markPasswordResetTokenUsed($conn, $token);

                // Log the action
                $ip = getClientIP();
                $ip_escaped = mysqli_real_escape_string($conn, $ip);
                mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address)
                                     VALUES ($user_id, 'password_reset', 'Password was reset', '$ip_escaped')");

                // Clean up old tokens
                cleanupExpiredTokens($conn);

                $success = 'Your password has been reset successfully. You can now log in with your new password.';
                $validToken = false; // Hide form after success
            } else {
                $error = 'Failed to reset password. Please try again.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body {
            background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .reset-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 420px;
        }
        .reset-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .reset-header i {
            font-size: 60px;
            color: #1a3a6e;
        }
        .reset-header h2 {
            color: #1a3a6e;
            margin-top: 15px;
        }
        .form-control {
            border-radius: 25px;
            padding: 12px 20px;
            border: 2px solid #e0e0e0;
        }
        .form-control:focus {
            border-color: #1a3a6e;
            box-shadow: none;
        }
        .btn-reset {
            background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%);
            border: none;
            border-radius: 25px;
            padding: 12px;
            font-weight: bold;
            width: 100%;
            color: white;
        }
        .btn-reset:hover {
            background: linear-gradient(135deg, #2d5a3d 0%, #1a3a6e 100%);
            color: white;
        }
        .back-link {
            text-align: center;
            margin-top: 20px;
        }
        .back-link a {
            color: #1a3a6e;
            font-weight: bold;
        }
        .password-requirements {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            font-size: 13px;
        }
        .password-requirements h6 {
            color: #1a3a6e;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .password-requirements ul {
            margin: 0;
            padding-left: 20px;
        }
        .password-requirements li {
            color: #666;
            margin-bottom: 5px;
        }
        .user-info {
            background: #e7f3ff;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
        }
        .user-info i {
            font-size: 30px;
            color: #0d6efd;
            margin-bottom: 10px;
        }
        .toggle-password {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #999;
        }
        .password-field {
            position: relative;
        }
    </style>
</head>
<body>
    <div class="reset-container">
        <div class="reset-header">
            <i class="fas fa-lock"></i>
            <h2>Reset Password</h2>
            <p class="text-muted">Create a new secure password</p>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo htmlspecialchars($error); ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <?php if($success): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($success); ?>
        </div>
        <div class="text-center mt-4">
            <a href="login" class="btn btn-reset">
                <i class="fas fa-sign-in-alt mr-2"></i>Go to Login
            </a>
        </div>
        <?php elseif($validToken): ?>

        <div class="user-info">
            <i class="fas fa-user-circle d-block"></i>
            <strong><?php echo htmlspecialchars($tokenData['full_name'] ?: $tokenData['username']); ?></strong>
            <br><small class="text-muted"><?php echo htmlspecialchars($tokenData['email']); ?></small>
        </div>

        <div class="password-requirements">
            <h6><i class="fas fa-shield-alt mr-2"></i>Password Requirements:</h6>
            <ul>
                <li>At least <?php echo PASSWORD_MIN_LENGTH; ?> characters long</li>
                <?php if(PASSWORD_REQUIRE_MIXED_CASE): ?>
                <li>Both uppercase and lowercase letters</li>
                <?php endif; ?>
                <?php if(PASSWORD_REQUIRE_NUMBERS): ?>
                <li>At least one number</li>
                <?php endif; ?>
            </ul>
        </div>

        <form action="" method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">

            <div class="form-group password-field">
                <input type="password" name="password" id="password" class="form-control"
                       placeholder="New Password" required minlength="<?php echo PASSWORD_MIN_LENGTH; ?>">
                <i class="fas fa-eye toggle-password" onclick="togglePassword('password', this)"></i>
            </div>

            <div class="form-group password-field">
                <input type="password" name="confirm_password" id="confirm_password" class="form-control"
                       placeholder="Confirm New Password" required>
                <i class="fas fa-eye toggle-password" onclick="togglePassword('confirm_password', this)"></i>
            </div>

            <button type="submit" class="btn btn-reset">
                <i class="fas fa-save mr-2"></i>Reset Password
            </button>
        </form>
        <?php else: ?>
        <div class="text-center">
            <a href="forgot-password" class="btn btn-reset">
                <i class="fas fa-redo mr-2"></i>Request New Reset Link
            </a>
        </div>
        <?php endif; ?>

        <div class="back-link">
            <p><a href="login"><i class="fas fa-arrow-left mr-2"></i>Back to Login</a></p>
        </div>
    </div>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function togglePassword(fieldId, icon) {
            const field = document.getElementById(fieldId);
            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');
            }
        }
    </script>
</body>
</html>
