<?php
/**
 * Run Salary Components Migration
 * Creates salary_components and employee_salary_structure tables
 */

require_once __DIR__ . '/../includes/init.php';
requireLogin();

// Only allow Super Admin or HR Admin
if (!isSuperAdmin() && !isHRAdmin()) {
    die('Access denied. Only Super Admin and HR Admin can run migrations.');
}

$db = getDB();
$migrationFile = __DIR__ . '/migrations/create_salary_components_migration.sql';

if (!file_exists($migrationFile)) {
    die("Migration file not found: {$migrationFile}");
}

echo "<h2>Running Salary Components Migration</h2>";
echo "<pre>";

try {
    // Read migration file
    $sql = file_get_contents($migrationFile);
    
    if (empty($sql)) {
        throw new Exception("Migration file is empty");
    }
    
    // Split by semicolon and execute each statement
    $statements = array_filter(
        array_map('trim', explode(';', $sql)),
        function($stmt) {
            return !empty($stmt) && 
                   !preg_match('/^--/', $stmt) && 
                   !preg_match('/^SELECT/i', $stmt);
        }
    );
    
    $executed = 0;
    $errors = [];
    
    foreach ($statements as $statement) {
        if (empty(trim($statement))) {
            continue;
        }
        
        try {
            $db->exec($statement);
            $executed++;
            echo "✓ Executed statement #{$executed}\n";
        } catch (PDOException $e) {
            // Ignore "table already exists" errors
            if (strpos($e->getMessage(), 'already exists') === false && 
                strpos($e->getMessage(), 'Duplicate entry') === false) {
                $errors[] = $e->getMessage();
                echo "⚠ Warning: " . $e->getMessage() . "\n";
            } else {
                echo "ℹ Info: " . $e->getMessage() . "\n";
            }
        }
    }
    
    // Execute SELECT statements separately to show results
    echo "\n--- Migration Results ---\n";
    
    try {
        $stmt = $db->query("SELECT COUNT(*) as total FROM salary_components");
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "Total Salary Components: " . $result['total'] . "\n";
    } catch (Exception $e) {
        echo "Could not count salary components: " . $e->getMessage() . "\n";
    }
    
    try {
        $stmt = $db->query("SELECT COUNT(*) as total FROM employee_salary_structure");
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "Total Employee Salary Structures: " . $result['total'] . "\n";
    } catch (Exception $e) {
        echo "Could not count salary structures: " . $e->getMessage() . "\n";
    }
    
    echo "\n✅ Migration completed successfully!\n";
    echo "Executed {$executed} statements.\n";
    
    if (!empty($errors)) {
        echo "\n⚠ Warnings:\n";
        foreach ($errors as $error) {
            echo "  - {$error}\n";
        }
    }
    
} catch (Exception $e) {
    echo "❌ Migration failed: " . $e->getMessage() . "\n";
    echo "Stack trace: " . $e->getTraceAsString() . "\n";
}

echo "</pre>";
echo "<p><a href='" . BASE_URL . "/modules/employee/list.php'>Go to Employee List</a></p>";

