<?php
// Fix company session variables in all company files

$company_files = [
    'company/post-job.php',
    'company/applications.php', 
    'company/view-application.php',
    'company/schedule-interview.php',
    'company/interviews.php'
];

foreach ($company_files as $file) {
    if (file_exists($file)) {
        echo "Processing $file...\n";
        
        $content = file_get_contents($file);
        
        // Replace $_SESSION['user_id'] used as company_id with $_SESSION['company_id']
        // But be careful about SQL INSERT statements that need both
        
        // First, handle the case where we need both company_id and company_user_id in INSERT
        if (strpos($content, 'INSERT INTO jobs') !== false) {
            // For job posting, we need both values
            $content = str_replace(
                "\$company_id = \$_SESSION['user_id'];",
                "\$company_id = \$_SESSION['company_id'];\n\$company_user_id = \$_SESSION['user_id'];",
                $content
            );
            
            // Update the INSERT statement to include company_user_id
            $content = preg_replace(
                '/INSERT INTO jobs \([^)]*\) VALUES \([^)]*\$_SESSION\[\'user_id\'\][^)]*\)/',
                'INSERT INTO jobs (company_id, company_user_id, category_id, title, description, requirements, salary_min, salary_max, location, employment_type, experience_level, deadline, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                $content
            );
            
            // Update the execute parameters
            $content = str_replace(
                '$_SESSION[\'user_id\'],',
                '$company_id, $company_user_id,',
                $content
            );
        } else {
            // For other files, just replace user_id with company_id for company identification
            $content = preg_replace(
                '/\$company_id = \$_SESSION\[\'user_id\'\];/',
                '$company_id = $_SESSION[\'company_id\'];',
                $content
            );
            
            // Replace other instances where user_id is used as company_id in WHERE clauses
            $content = str_replace(
                'j.company_id = ?',
                'j.company_id = ?',
                $content
            );
        }
        
        file_put_contents($file, $content);
        echo "Updated $file successfully.\n";
    } else {
        echo "File $file not found.\n";
    }
}

echo "\nAll company files have been updated to use the new session structure.\n";
?>