<?php
/**
 * Migration Runner - Add Ledger Permissions
 * This script adds the new supplier and customer ledger permissions to the permissions table
 * Access this file in your browser: http://localhost/TellerPro/run_ledger_permissions_migration.php
 */

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

echo '<!DOCTYPE html>
<html>
<head>
    <title>Running Ledger Permissions 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>Ledger Permissions Migration</h1>';

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

    $permissions = [
        ['name' => 'supplier_ledger.view', 'display_name' => 'View Supplier Ledger', 'description' => 'View supplier ledger entries', 'category' => 'ledger'],
        ['name' => 'supplier_ledger.create', 'display_name' => 'Create Supplier Ledger Entry', 'description' => 'Create manual supplier ledger entries', 'category' => 'ledger'],
        ['name' => 'supplier_ledger.manage', 'display_name' => 'Manage Supplier Ledger', 'description' => 'Manage supplier ledger operations', 'category' => 'ledger'],
        ['name' => 'customer_ledger.view', 'display_name' => 'View Customer Ledger', 'description' => 'View customer ledger entries', 'category' => 'ledger'],
        ['name' => 'customer_ledger.create', 'display_name' => 'Create Customer Ledger Entry', 'description' => 'Create manual customer ledger entries', 'category' => 'ledger'],
        ['name' => 'customer_ledger.manage', 'display_name' => 'Manage Customer Ledger', 'description' => 'Manage customer ledger operations', 'category' => 'ledger'],
    ];

    $added = 0;
    foreach ($permissions as $perm) {
        $sql = "INSERT IGNORE INTO permissions (name, display_name, description, category) VALUES (?, ?, ?, ?)";
        $stmt = db()->prepare($sql);
        $stmt->execute([$perm['name'], $perm['display_name'], $perm['description'], $perm['category']]);
        if ($stmt->rowCount() > 0) {
            $added++;
            echo "<p class='success'>Added permission: {$perm['display_name']}</p>";
        }
    }

    echo '<h2 class="success">Migration completed successfully!</h2>';
    echo "<p>Added {$added} new permissions.</p>";
    echo '<p><a href="' . APP_URL . '/roles/create">Go to Create New Role</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>';
