<?php
session_start();
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';

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

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

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

$companyId = (int) ($_POST['company_id'] ?? 0);

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

try {
    $pdo = getPDO();
    
    // Get company data
    $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
    $_SESSION['current_company_id'] = $companyId;
    $_SESSION['current_company'] = $company;
    
    // Redirect to index.php instead of returning JSON
    header('Location: /index.php');
    exit;
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
