<?php
include __DIR__ . '/includes/header.php';

// If user is logged in, redirect them from this page
if (isLoggedIn()) {
    redirectTo('index');
}

$token = $_GET['token'] ?? null;
$form_type = 'request'; // 'request' or 'reset'
$page_title = 'Request Password Reset';
$errors = [];
$success_message = '';

if ($token) {
    // We have a token, so this is the password reset form stage
    $form_type = 'reset';
    $page_title = $lang_frontend['PAGE_TITLE_LOGIN_RESET'] ?? 'Reset Your Password';

    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE reset_token = ? AND reset_token_expires_at > NOW()");
        $stmt->execute([$token]);
        $user = $stmt->fetch();

        if (!$user) {
            $errors[] = $lang_alerts['ALERT_ERROR_INVALID_OR_EXPIRED_RESET_LINK'] ?? "Invalid or expired password reset link. Please request a new one.";
            $form_type = 'request'; // Force back to request form if token invalid
            $page_title = $lang_frontend['PAGE_TITLE_REQUEST_PASSWORD_RESET'] ?? 'Request Password Reset'; // Reset page title
        }
    } catch (PDOException $e) {
        error_log("Error verifying reset token: " . $e->getMessage());
        $errors[] = $lang_alerts['ALERT_ERROR_RESET_REQUEST_ERROR'] ?? "An error occurred. Please try again later.";
        $form_type = 'request';
        $page_title = $lang_frontend['PAGE_TITLE_REQUEST_PASSWORD_RESET'] ?? 'Request Password Reset';
    }
}

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $errors[] = 'Invalid CSRF token. Please try again.';
    } else {
        if (isset($_POST['request_reset'])) {
            // --- Handle Email Submission for Reset Link ---
            $email = sanitizeInput($_POST['email'] ?? '');
            if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errors[] = $lang_alerts['ALERT_ERROR_INVALID_EMAIL_ADDRESS_RESET'] ?? "Please enter a valid email address.";
            } else {
                try {
                    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
                    $stmt->execute([$email]);
                    $user = $stmt->fetch();

                    if ($user) {
                        $reset_token = bin2hex(random_bytes(32));
                        // $expires_at = date('Y-m-d H:i:s', time() + 3600); // Token expires in 1 hour // Old way

                        // Calculate expiry time in PHP's current default timezone
                        $expires_timestamp = time() + 3600; // Token expires in 1 hour from now

                        // Create a DateTime object in PHP's default timezone, then convert to UTC for storage
                        try {
                            $dt = new DateTime("@{$expires_timestamp}"); // Create from timestamp, defaults to current PHP timezone
                            $dt->setTimezone(new DateTimeZone('UTC'));    // Convert to UTC
                            $expires_at_utc = $dt->format('Y-m-d H:i:s'); // Format for MySQL DATETIME
                        } catch (Exception $e) {
                            // Fallback or error logging if DateTime fails, though unlikely with a timestamp
                            error_log("DateTime object creation/conversion failed for password reset expiry: " . $e->getMessage());
                            // As a basic fallback, use PHP's default timezone, which might lead to issues if DB is not UTC
                            // but better than failing completely. Ideally, this path isn't hit.
                            $expires_at_utc = date('Y-m-d H:i:s', $expires_timestamp);
                        }

                        $stmt_update = $pdo->prepare("UPDATE users SET reset_token = ?, reset_token_expires_at = ? WHERE id = ?");
                        $stmt_update->execute([$reset_token, $expires_at_utc, $user['id']]);

                        $reset_link = getCleanUrl('login_reset', ['token' => $reset_token]);
                        
                        $email_subject = SITE_NAME . " - Password Reset Request";
                        $email_message = "
                            <p>Hello " . htmlspecialchars($user['name']) . ",</p>
                            <p>We received a request to reset your password for your account at " . SITE_NAME . ".</p>
                            <p>If you did not request this, please ignore this email.</p>
                            <p>To reset your password, please click the link below or copy and paste it into your browser:</p>
                            <p><a href='" . $reset_link . "'>" . $reset_link . "</a></p>
                            <p>This link will expire in 1 hour.</p>
                            <p>Thank you,<br>The " . SITE_NAME . " Team</p>
                        ";

                        // You need to ensure your send_system_email function is robust
                        if(send_system_email($user['email'], $email_subject, $email_message)) {
                             $success_message = $lang_alerts['ALERT_SUCCESS_RESET_LINK_SENT'] ?? "If an account with that email exists, a password reset link has been sent. Please check your inbox (and spam folder).";
                        } else {
                             $errors[] = $lang_alerts['ALERT_ERROR_COULD_NOT_SEND_RESET_EMAIL'] ?? "Could not send the password reset email. Please contact support.";
                             error_log("Failed to send password reset email to: " . $email);
                        }

                    } else {
                        // Email not found, show generic success message to prevent user enumeration
                         $success_message = $lang_alerts['ALERT_SUCCESS_RESET_LINK_SENT'] ?? "If an account with that email exists, a password reset link has been sent. Please check your inbox (and spam folder).";
                    }
                } catch (PDOException $e) {
                    error_log("Password reset request error: " . $e->getMessage());
                    $errors[] = $lang_alerts['ALERT_ERROR_RESET_REQUEST_ERROR'] ?? "An error occurred while processing your request. Please try again.";
                }
            }
        } elseif (isset($_POST['reset_password'])) {
            // --- Handle New Password Submission ---
            $submitted_token = $_POST['token'] ?? '';
            $password = $_POST['password'] ?? '';
            $password_confirm = $_POST['password_confirm'] ?? '';

            if (empty($submitted_token) || empty($password) || empty($password_confirm)) {
                $errors[] = $lang_alerts['ALERT_ERROR_FILL_ALL_REQUIRED_FIELDS'] ?? "Please fill in all fields.";
            } elseif ($password !== $password_confirm) {
                $errors[] = $lang_alerts['ALERT_ERROR_PASSWORDS_DO_NOT_MATCH'] ?? "Passwords do not match.";
            } elseif (mb_strlen($password) < MIN_PASSWORD_LENGTH) {
                 $errors[] = sprintf($lang_alerts['ALERT_ERROR_PASSWORD_TOO_SHORT'] ?? "Password must be at least %d characters long.", MIN_PASSWORD_LENGTH);
            } else {
                try {
                    // Use transaction with row locking to prevent race condition
                    $pdo->beginTransaction();
                    
                    // Lock the user row and verify token is still valid (prevents concurrent use)
                    $stmt_lock = $pdo->prepare("SELECT id, reset_token, reset_token_expires_at FROM users WHERE reset_token = ? AND reset_token_expires_at > NOW() FOR UPDATE");
                    $stmt_lock->execute([$submitted_token]);
                    $user = $stmt_lock->fetch();

                    if ($user) {
                        // Update password and clear token atomically
                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                        $stmt_update = $pdo->prepare("UPDATE users SET password = ?, reset_token = NULL, reset_token_expires_at = NULL WHERE id = ? AND reset_token = ?");
                        $stmt_update->execute([$hashed_password, $user['id'], $submitted_token]);
                        
                        if ($stmt_update->rowCount() === 0) {
                            // Token was cleared by another request
                            $pdo->rollBack();
                            $errors[] = $lang_alerts['ALERT_ERROR_INVALID_OR_EXPIRED_RESET_LINK'] ?? "Invalid or expired password reset link. Please request a new one.";
                            $form_type = 'request';
                            $page_title = $lang_frontend['PAGE_TITLE_REQUEST_PASSWORD_RESET'] ?? 'Request Password Reset';
                        } else {
                            $pdo->commit();
                            
                            // Log successful password reset
                            error_log("Password reset successful for user ID: " . $user['id']);
                            
                            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_PASSWORD_RESET'] ?? 'Your password has been successfully reset. You can now log in with your new password.', 'success');
                            redirectTo(getCleanUrl('login'));
                            exit;
                        }
                    } else {
                        $pdo->rollBack();
                        $errors[] = $lang_alerts['ALERT_ERROR_INVALID_OR_EXPIRED_RESET_LINK'] ?? "Invalid or expired password reset link. Please request a new one.";
                        $form_type = 'request'; // Force back to request form
                        $page_title = $lang_frontend['PAGE_TITLE_REQUEST_PASSWORD_RESET'] ?? 'Request Password Reset';
                    }
                } catch (PDOException $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    error_log("Password reset error: " . $e->getMessage());
                    $errors[] = $lang_alerts['ALERT_ERROR_PASSWORD_RESET_ERROR'] ?? "An error occurred while resetting your password. Please try again.";
                }
            }
             // Ensure token is passed back to the form if there are errors and we are in reset mode
            if (!empty($errors) && $form_type === 'reset' && !$user) {
                // If user became invalid during POST (e.g. token expired), switch form type
                 $form_type = 'request';
                 $page_title = $lang_frontend['PAGE_TITLE_REQUEST_PASSWORD_RESET'] ?? 'Request Password Reset';
            } else {
                 $token = $submitted_token; // Keep token in context for form re-display
            }
        }
    }
}

?>
<?php if (defined('USE_LOGO_LOGIN') && USE_LOGO_LOGIN && defined('LOGO_LOGIN_URL') && !empty(LOGO_LOGIN_URL)): ?>
                <center><img src="<?php echo LOGO_LOGIN_URL; ?>" alt="" 
                    <?php echo (defined('LOGO_LOGIN_WIDTH') && LOGO_LOGIN_WIDTH) ? 'width="' . LOGO_LOGIN_WIDTH . '"' : ''; ?>><br><br></center>
           
<?php endif; ?>
<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0"><?php echo htmlspecialchars($page_title); ?></h4>
            </div>
            <div class="card-body">
                <?php
                if (!empty($errors)) {
                    foreach ($errors as $error) {
                        echo displayAlert($error, 'danger');
                    }
                }
                if (!empty($success_message)) {
                    echo displayAlert($success_message, 'success');
                }
                ?>

                <?php if ($form_type === 'request' && empty($success_message)): ?>
                    <p><?php echo $lang_frontend['LOGIN_RESET_INSTRUCTION_REQUEST'] ?? 'Please enter your email address below. If an account exists for that email, we will send you a link to reset your password.'; ?></p>
                    <form action="<?php echo getCleanUrl('login_reset'); ?>" method="post">
                        <?php echo get_csrf_input_field(); ?>
                        <div class="mb-3">
                            <label for="email" class="form-label"><?php echo $lang_frontend['LOGIN_RESET_LABEL_EMAIL'] ?? 'Your Email Address'; ?></label>
                            <input type="email" class="form-control" id="email" name="email" required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="request_reset" class="btn btn-primary"><?php echo $lang_frontend['LOGIN_RESET_BUTTON_SEND_LINK'] ?? 'Send Password Reset Link'; ?></button>
                        </div>
                    </form>
                <?php elseif ($form_type === 'reset' && empty($success_message)): ?>
                    <p><?php echo $lang_frontend['LOGIN_RESET_INSTRUCTION_RESET'] ?? 'Please enter your new password below.'; ?></p>
                    <form action="<?php echo getCleanUrl('login_reset?token=' . htmlspecialchars($token)); ?>" method="post">
                        <?php echo get_csrf_input_field(); ?>
                        <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                        <div class="mb-3">
                            <label for="password" class="form-label"><?php echo $lang_frontend['LOGIN_RESET_LABEL_NEW_PASSWORD'] ?? 'New Password'; ?></label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="mb-3">
                            <label for="password_confirm" class="form-label"><?php echo $lang_frontend['LOGIN_RESET_LABEL_CONFIRM_PASSWORD'] ?? 'Confirm New Password'; ?></label>
                            <input type="password" class="form-control" id="password_confirm" name="password_confirm" required>
                        </div>
                        <div class="d-grid">
                            <button type="submit" name="reset_password" class="btn btn-primary"><?php echo $lang_frontend['LOGIN_RESET_BUTTON_RESET_PASSWORD'] ?? 'Reset Password'; ?></button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
            <div class="card-footer text-center">
                <?php echo $lang_frontend['LOGIN_RESET_TEXT_REMEMBER_PASSWORD'] ?? 'Remember your password?'; ?> <a href="<?php echo getCleanUrl('login'); ?>"><?php echo $lang_frontend['LOGIN_RESET_LINK_LOGIN'] ?? 'Login here'; ?></a>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?> 