<?php
require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/Auth/AuthManager.php';
require_once __DIR__ . '/../../src/MultiTenant/TenantManager.php';

header('Content-Type: application/json');

// Require authentication
if (!AuthManager::isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Get request data (handle both JSON and form data)
if (strpos($_SERVER['CONTENT_TYPE'] ?? '', 'application/json') !== false) {
    $data = json_decode(file_get_contents('php://input'), true);
    $companyId = (int) ($data['company_id'] ?? 0);
} else {
    // Form data
    $companyId = (int) ($_POST['company_id'] ?? 0);
}

if (!$companyId) {
    echo json_encode(['success' => false, 'error' => 'Company ID required']);
    exit;
}

try {
    // Switch workspace
    $success = TenantManager::switchCompany($companyId);
    
    if ($success) {
        // Get the new company data
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
        $stmt->execute([$companyId]);
        $company = $stmt->fetch();
        
        if (!$company) {
            echo json_encode(['success' => false, 'error' => 'Company not found']);
            exit;
        }
        
        // Update session with complete company data
        $_SESSION['current_company_id'] = $companyId;
        $_SESSION['current_company'] = $company;
        
        // Debug: Log session update
        error_log("Switch Debug - Updated Session Company ID: " . $companyId);
        error_log("Switch Debug - Updated Session Company Name: " . $company['name']);
        error_log("Switch Debug - Complete company data: " . json_encode($company));
        
        // For local development, always redirect to index.php
        $redirectUrl = '/index.php';
        
        // In production, you might want to redirect to subdomain
        if ($company && $company['subdomain'] !== 'default' && strpos($_SERVER['HTTP_HOST'], 'localhost') === false) {
            $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
            $host = $company['subdomain'] . '.' . TenantManager::getBaseDomain();
            $redirectUrl = $protocol . $host . '/index.php';
        }
        
        // For regular form submission, redirect instead of returning JSON
        if (strpos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') === false) {
            // Regular form submission - redirect
            header('Location: ' . $redirectUrl);
            exit;
        }
        
        // AJAX submission - return JSON
        echo json_encode([
            'success' => true,
            'redirect_url' => $redirectUrl
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to switch workspace']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
