<?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',
    // Report sub-permissions (only view + export apply)
    'reports_sales'           => 'Sales Report',
    'reports_purchase'        => 'Purchase Report',
    'reports_gst'             => 'GST Report',
    'reports_gstr1'           => 'GSTR1 Report',
    'reports_profit'          => 'Profit Report',
    'reports_ledger_customer' => 'Customer Ledger',
    'reports_ledger_vendor'   => 'Vendor Ledger',
    'reports_stock'           => 'Stock Movement',
    'reports_consolidated'    => 'Consolidated Profit',
    'reports_master_profit'   => 'Master Sales Profit',
    'ledgers'                 => 'Ledgers',
    'settings'                => 'Settings',
];

// Report sub-modules: only view + export are meaningful
$reportSubModules = [
    'reports_sales', 'reports_purchase', 'reports_gst', 'reports_gstr1',
    'reports_profit', 'reports_ledger_customer', 'reports_ledger_vendor',
    'reports_stock', 'reports_consolidated', 'reports_master_profit',
];
$firstReportModule = 'reports_sales';

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

// 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;
            $cr  = isset($_POST['perms'][$module]['can_revert'])   ? 1 : 0;

            $stmt = $conn->prepare("
                INSERT INTO role_permissions (role_id, module, can_view, can_create, can_edit, can_delete, can_export, can_finalize, can_revert)
                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),
                    can_revert=VALUES(can_revert)
            ");
            $stmt->bind_param("isiiiiiii", $id, $module, $cv, $cc, $ce, $cd, $cex, $cf, $cr);
            $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] ?? [];
                $isReport = in_array($module, $reportSubModules);
            ?>
            <?php if ($module === $firstReportModule): ?>
            <tr style="background:#eff6ff;">
                <td colspan="<?= count($actions) + 2 ?>" style="padding:8px 14px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#2563eb;">
                    <i class="fas fa-chart-bar" style="margin-right:6px;"></i>Reports — select which reports this role can access
                </td>
            </tr>
            <?php endif; ?>
            <tr class="perm-row" style="border-bottom:1px solid #f1f5f9;<?= $isReport ? 'background:#fafcff;' : '' ?>">
                <td style="padding:10px 14px;font-weight:500;<?= $isReport ? 'padding-left:28px;color:#374151;' : '' ?>">
                    <?php if ($isReport): ?><i class="fas fa-angle-right" style="color:#93c5fd;margin-right:6px;font-size:11px;"></i><?php endif; ?>
                    <?= $moduleLabel ?>
                </td>
                <?php foreach ($actions as $action => $_):
                    $reportOnly = $isReport && !in_array($action, ['can_view', 'can_export']);
                ?>
                <td style="text-align:center;padding:10px;">
                    <?php if ($reportOnly): ?>
                        <span style="color:#d1d5db;font-size:13px;">—</span>
                    <?php else: ?>
                    <input type="checkbox" class="perm-cb module-<?= $module ?>"
                           name="perms[<?= $module ?>][<?= $action ?>]"
                           value="1"
                           <?= !empty($p[$action]) ? 'checked' : '' ?>>
                    <?php endif; ?>
                </td>
                <?php endforeach; ?>
                <td style="text-align:center;padding:10px;">
                    <?php
                    $relevantActions = $isReport ? ['can_view', 'can_export'] : array_keys($actions);
                    $checkedCount = count(array_filter(array_map(fn($a) => !empty($p[$a]), $relevantActions)));
                    $allChecked = $checkedCount === count($relevantActions);
                    ?>
                    <input type="checkbox" class="row-toggle" data-module="<?= $module ?>"
                           title="Toggle all for <?= $moduleLabel ?>"
                           <?= $allChecked ? '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>
var reportSubModules = <?= json_encode($reportSubModules) ?>;

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 isReport = reportSubModules.indexOf(module) !== -1;
        var selector = isReport
            ? '.module-' + module + '[name*="can_view"], .module-' + module + '[name*="can_export"]'
            : '.module-' + module;
        var all     = document.querySelectorAll(selector);
        var checked = document.querySelectorAll(selector + ':checked');
        var toggle  = document.querySelector('[data-module="' + module + '"]');
        if (toggle) toggle.checked = (all.length > 0 && 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'; ?>
