<?php
session_start();
require_once '../db.php';
require_once 'language_handler.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['language_code'])) {
    $language_code = $_POST['language_code'];
    
    // Initialize language handler
    $language_handler = new LanguageHandler($conn);
    
    // Set the new language
    if ($language_handler->setLanguage($language_code)) {
        // Get the referring page or default to index
        $referer = $_SERVER['HTTP_REFERER'] ?? 'index.php';
        
        // Redirect back to the referring page
        header('Location: ' . $referer);
        exit;
    } else {
        // Language not found or invalid
        $_SESSION['error'] = 'Invalid language selected';
        header('Location: index.php');
        exit;
    }
} else {
    // Invalid request
    header('Location: index.php');
    exit;
}
?>
