<?php
/**
 * Migration Runner - Supplier and Customer Ledger Tables
 * Access this file in your browser: http://localhost/TellerPro/run_ledger_migration.php
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';

echo '<!DOCTYPE html>
<html>
<head>
    <title>Running Ledger Migration</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; max-width: 800px; margin: 0 auto; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
    </style>
</head>
<body>';

echo '<h1>Supplier & Customer Ledger Migration</h1>';

try {
    echo '<p class="info">Starting migration...</p>';

    // Read the ledger schema file
    $sqlFile = __DIR__ . '/database/ledger_schema.sql';
    if (!file_exists($sqlFile)) {
        throw new Exception('Ledger schema file not found: ' . $sqlFile);
    }

    $sql = file_get_contents($sqlFile);
    
    // Split by semicolons to get individual statements
    $statements = array_filter(array_map('trim', explode(';', $sql)));

    // Execute each statement
    foreach ($statements as $statement) {
        if (!empty($statement)) {
            db()->exec($statement);
        }
    }

    echo '<h2 class="success">Migration completed successfully!</h2>';
    echo '<p>The supplier_ledger and customer_ledger tables have been created.</p>';
    echo '<p><a href="' . APP_URL . '/supplier-ledger">Go to Supplier Ledger</a></p>';
    echo '<p><a href="' . APP_URL . '/customer-ledger">Go to Customer Ledger</a></p>';

} catch (Exception $e) {
    echo '<h2 class="error">Migration failed</h2>';
    echo '<pre class="error">' . htmlspecialchars($e->getMessage()) . '</pre>';
    echo '<p>Please check your database configuration and try again.</p>';
}

echo '</body>
</html>';
