<?php
require_once '../../includes/auth.php';
require_once '../../db.php';

if (($_SESSION['user_role'] ?? '') !== 'admin') {
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$id     = (int)($_GET['id'] ?? 0);
$isEdit = $id > 0;
$errors = [];

// Module list with display labels
$modules = [
    'dashboard'        => 'Dashboard',
    'master_sales'     => 'Master Sales',
    'products'         => 'Products',
    'vendors'          => 'Vendors',
    'clients'          => 'Clients',
    'purchases'        => 'Purchases',
    'purchase_returns' => 'Purchase Returns',
    'sales'            => 'Sales',
    'sales_returns'    => 'Sales Returns',
    'inventory'        => 'Inventory',
    'reports'          => 'Reports',
    'ledgers'          => 'Ledgers',
    'settings'         => 'Settings',
];

$actions = [
    'can_view'     => 'View',
    'can_create'   => 'Create',
    'can_edit'     => 'Edit',
    'can_delete'   => 'Delete',
    'can_export'   => 'Export',
    'can_finalize' => 'Finalize',
];

// Load existing role
$role = ['name' => '', 'description' => '', 'is_system' => 0];
$existingPerms = [];

if ($isEdit) {
    $r = $conn->query("SELECT * FROM roles WHERE id = $id");
    if (!$r || !($role = $r->fetch_assoc())) die("Role not found.");

    $perms = $conn->query("SELECT * FROM role_permissions WHERE role_id = $id");
    while ($p = $perms->fetch_assoc()) {
        $existingPerms[$p['module']] = $p;
    }
}

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $desc = trim($_POST['description'] ?? '');

    if (!$name) $errors[] = "Role name is required.";

    if (empty($errors)) {
        if ($isEdit) {
            $stmt = $conn->prepare("UPDATE roles SET name=?, description=? WHERE id=?");
            $stmt->bind_param("ssi", $name, $desc, $id);
            $stmt->execute();
        } else {
            $stmt = $conn->prepare("INSERT INTO roles (name, description, is_system) VALUES (?,?,0)");
            $stmt->bind_param("ss", $name, $desc);
            $stmt->execute();
            $id = $conn->insert_id;
        }

        // Upsert permissions
        foreach ($modules as $module => $_label) {
            $cv  = isset($_POST['perms'][$module]['can_view'])     ? 1 : 0;
            $cc  = isset($_POST['perms'][$module]['can_create'])   ? 1 : 0;
            $ce  = isset($_POST['perms'][$module]['can_edit'])     ? 1 : 0;
            $cd  = isset($_POST['perms'][$module]['can_delete'])   ? 1 : 0;
            $cex = isset($_POST['perms'][$module]['can_export'])   ? 1 : 0;
            $cf  = isset($_POST['perms'][$module]['can_finalize']) ? 1 : 0;

            $stmt = $conn->prepare("
                INSERT INTO role_permissions (role_id, module, can_view, can_create, can_edit, can_delete, can_export, can_finalize)
                VALUES (?,?,?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE
                    can_view=VALUES(can_view), can_create=VALUES(can_create),
                    can_edit=VALUES(can_edit), can_delete=VALUES(can_delete),
                    can_export=VALUES(can_export), can_finalize=VALUES(can_finalize)
            ");
            $stmt->bind_param("isiiiiii", $id, $module, $cv, $cc, $ce, $cd, $cex, $cf);
            $stmt->execute();
        }

        header('Location: index.php?success=1');
        exit;
    }

    // Re-populate from POST on validation failure
    $role['name']        = $_POST['name'] ?? '';
    $role['description'] = $_POST['description'] ?? '';
    foreach ($modules as $module => $_) {
        $existingPerms[$module] = $_POST['perms'][$module] ?? [];
    }
}

require_once '../../includes/header.php';
require_once '../../includes/sidebar.php';
?>

<div class="page-header">
    <h2>
        <i class="fas fa-shield-alt" style="color:var(--primary);margin-right:8px;"></i>
        <?= $isEdit ? 'Edit Role' : 'New Role' ?>
    </h2>
    <a href="index.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<?php if ($errors): ?>
<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:12px 16px;margin-bottom:16px;color:#991b1b;">
    <i class="fas fa-exclamation-triangle"></i>
    <?php foreach ($errors as $e): ?><div><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
</div>
<?php endif; ?>

<form method="post">
<div class="panel" style="margin-bottom:20px;">
    <div class="panel-header"><span class="panel-title">Role Details</span></div>
    <div class="panel-body" style="display:grid;grid-template-columns:1fr 2fr;gap:16px;padding:20px;">
        <div class="form-group" style="margin:0;">
            <label>Role Name <span style="color:red;">*</span></label>
            <input type="text" name="name" value="<?= htmlspecialchars($role['name']) ?>" required
                   <?= $role['is_system'] ? 'readonly style="background:#f1f5f9;"' : '' ?>>
        </div>
        <div class="form-group" style="margin:0;">
            <label>Description</label>
            <input type="text" name="description" value="<?= htmlspecialchars($role['description'] ?? '') ?>"
                   placeholder="Optional description">
        </div>
    </div>
</div>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">Permissions</span>
        <button type="button" class="btn btn-outline btn-sm" onclick="toggleAll(true)">Select All</button>
        <button type="button" class="btn btn-outline btn-sm" style="margin-left:6px;" onclick="toggleAll(false)">Clear All</button>
    </div>
    <div style="overflow-x:auto;">
        <table style="width:100%;border-collapse:collapse;">
            <thead>
                <tr style="background:#f1f5f9;">
                    <th style="padding:10px 14px;text-align:left;font-size:11px;text-transform:uppercase;color:#64748b;font-weight:600;border-bottom:1px solid #e2e8f0;">Module</th>
                    <?php foreach ($actions as $key => $label): ?>
                    <th style="padding:10px 10px;text-align:center;font-size:11px;text-transform:uppercase;color:#64748b;font-weight:600;border-bottom:1px solid #e2e8f0;">
                        <?= $label ?>
                    </th>
                    <?php endforeach; ?>
                    <th style="padding:10px 10px;text-align:center;font-size:11px;text-transform:uppercase;color:#64748b;font-weight:600;border-bottom:1px solid #e2e8f0;">All</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($modules as $module => $moduleLabel):
                $p = $existingPerms[$module] ?? [];
            ?>
            <tr class="perm-row" style="border-bottom:1px solid #f1f5f9;">
                <td style="padding:10px 14px;font-weight:500;"><?= $moduleLabel ?></td>
                <?php foreach ($actions as $action => $_): ?>
                <td style="text-align:center;padding:10px;">
                    <input type="checkbox" class="perm-cb module-<?= $module ?>"
                           name="perms[<?= $module ?>][<?= $action ?>]"
                           value="1"
                           <?= !empty($p[$action]) ? 'checked' : '' ?>>
                </td>
                <?php endforeach; ?>
                <td style="text-align:center;padding:10px;">
                    <input type="checkbox" class="row-toggle" data-module="<?= $module ?>"
                           title="Toggle all for <?= $moduleLabel ?>"
                           <?= count(array_filter(array_intersect_key($p, array_flip(array_keys($actions))))) === count($actions) ? 'checked' : '' ?>>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div style="margin-top:20px;display:flex;gap:10px;">
    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Role</button>
    <a href="index.php" class="btn btn-outline">Cancel</a>
</div>
</form>

<script>
document.querySelectorAll('.row-toggle').forEach(function(toggle) {
    toggle.addEventListener('change', function() {
        var module = this.dataset.module;
        document.querySelectorAll('.module-' + module).forEach(function(cb) {
            cb.checked = toggle.checked;
        });
    });
});

document.querySelectorAll('.perm-cb').forEach(function(cb) {
    cb.addEventListener('change', function() {
        var cls = Array.from(this.classList).find(c => c.startsWith('module-'));
        if (!cls) return;
        var module = cls.replace('module-', '');
        var all = document.querySelectorAll('.module-' + module);
        var checked = document.querySelectorAll('.module-' + module + ':checked');
        var toggle = document.querySelector('[data-module="' + module + '"]');
        if (toggle) toggle.checked = (all.length === checked.length);
    });
});

function toggleAll(state) {
    document.querySelectorAll('.perm-cb, .row-toggle').forEach(function(cb) {
        cb.checked = state;
    });
}
</script>

<?php require_once '../../includes/footer.php'; ?>
