<?php
/**
 * Seed All Module Permissions - Complete
 * Adds all missing permissions for Payroll, Petty Cash, DFC, Fortnight, and other modules
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Only Super Admin can run this
if (!isSuperAdmin()) {
    $_SESSION['error'] = 'Only Super Admin can seed permissions.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Seed All Module Permissions';
$currentModule = 'settings';

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['seed'])) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // All permissions organized by module
        $permissions = [
            // ============================================
            // PAYROLL MODULE - Detailed Permissions
            // ============================================
            ['PAYROLL_HOME', 'Payroll Home', 'payroll', 'Access payroll home/dashboard'],
            ['PAYROLL_INSTRUCTIONS', 'Payroll Instructions', 'payroll', 'View payroll instructions'],
            ['PAYROLL_EMPLOYEE_MASTER', 'Employee Master Sheet', 'payroll', 'View and manage employee master sheet'],
            ['PAYROLL_EMPLOYEE_MASTER_CHANGE', 'Employee Master Change', 'payroll', 'Create and manage employee master changes'],
            ['PAYROLL_ATTENDANCE', 'Payroll Attendance', 'payroll', 'View attendance in payroll module'],
            ['PAYROLL_SALARY_REGISTER', 'Salary Register', 'payroll', 'View and manage salary register'],
            ['PAYROLL_SALARY_REGISTER_CREATE', 'Create Salary Register', 'payroll', 'Create new salary register entries'],
            ['PAYROLL_SALARY_REGISTER_EDIT', 'Edit Salary Register', 'payroll', 'Edit salary register entries'],
            ['PAYROLL_SALARY_REGISTER_DELETE', 'Delete Salary Register', 'payroll', 'Delete salary register entries'],
            ['PAYROLL_NEW_JOINEE_STATUTORY', 'New Joinee Statutory', 'payroll', 'Manage new joinee statutory information'],
            ['PAYROLL_OVERTIME', 'Payroll Overtime', 'payroll', 'View overtime in payroll'],
            ['PAYROLL_RESIGNED_ABSCONDEE', 'Resigned & Abscondee', 'payroll', 'View resigned and abscondee employees'],
            ['PAYROLL_LEAVE_FORM', 'Payroll Leave Form', 'payroll', 'View leave forms in payroll'],
            ['PAYROLL_VIEW', 'View Payroll', 'payroll', 'View payroll records'],
            ['PAYROLL_CREATE', 'Create Payroll', 'payroll', 'Create payroll records'],
            ['PAYROLL_CALCULATE', 'Calculate Payroll', 'payroll', 'Calculate payroll for employees'],
            ['PAYROLL_APPROVE', 'Approve Payroll', 'payroll', 'Approve payroll records'],
            ['PAYROLL_LOCK', 'Lock Payroll', 'payroll', 'Lock payroll records'],
            ['PAYROLL_EDIT', 'Edit Payroll', 'payroll', 'Edit payroll records'],
            ['PAYROLL_DELETE', 'Delete Payroll', 'payroll', 'Delete payroll records'],
            ['PAYROLL_EXPORT', 'Export Payroll', 'payroll', 'Export payroll to Excel/PDF'],
            ['PAYROLL_PAYSLIP', 'View Payslip', 'payroll', 'View and generate payslips'],
            ['PAYROLL_PAYSLIP_EXPORT', 'Export Payslip', 'payroll', 'Export payslips to PDF/Excel'],
            
            // ============================================
            // PETTY CASH MODULE
            // ============================================
            ['PETTY_CASH_VIEW', 'View Petty Cash', 'petty_cash', 'View petty cash transactions'],
            ['PETTY_CASH_CREATE', 'Create Petty Cash', 'petty_cash', 'Create petty cash transactions'],
            ['PETTY_CASH_EDIT', 'Edit Petty Cash', 'petty_cash', 'Edit petty cash transactions'],
            ['PETTY_CASH_DELETE', 'Delete Petty Cash', 'petty_cash', 'Delete petty cash transactions'],
            ['PETTY_CASH_CLOSE', 'Close Petty Cash', 'petty_cash', 'Close petty cash day/period'],
            ['PETTY_CASH_APPROVE', 'Approve Petty Cash', 'petty_cash', 'Approve petty cash transactions'],
            ['PETTY_CASH_REPORT', 'Petty Cash Reports', 'petty_cash', 'View petty cash reports'],
            ['PETTY_CASH_EXPORT', 'Export Petty Cash', 'petty_cash', 'Export petty cash to Excel/PDF'],
            
            // ============================================
            // DFC MODULE (Daily Food Cost)
            // ============================================
            ['DFC_VIEW', 'View DFC', 'dfc', 'View DFC records'],
            ['DFC_CREATE', 'Create DFC', 'dfc', 'Create DFC entries'],
            ['DFC_EDIT', 'Edit DFC', 'dfc', 'Edit DFC records'],
            ['DFC_DELETE', 'Delete DFC', 'dfc', 'Delete DFC records'],
            ['DFC_REPORT', 'DFC Reports', 'dfc', 'View DFC reports'],
            ['DFC_EXPORT', 'Export DFC', 'dfc', 'Export DFC to Excel/PDF'],
            
            // ============================================
            // FORTNIGHT MODULE
            // ============================================
            ['FORTNIGHT_VIEW', 'View Fortnight', 'fortnight', 'View fortnight records'],
            ['FORTNIGHT_CREATE', 'Create Fortnight', 'fortnight', 'Create fortnight entries'],
            ['FORTNIGHT_EDIT', 'Edit Fortnight', 'fortnight', 'Edit fortnight records'],
            ['FORTNIGHT_DELETE', 'Delete Fortnight', 'fortnight', 'Delete fortnight records'],
            ['FORTNIGHT_LOCK', 'Lock Fortnight', 'fortnight', 'Lock fortnight records'],
            ['FORTNIGHT_UNLOCK', 'Unlock Fortnight', 'fortnight', 'Unlock fortnight records'],
            ['FORTNIGHT_REPORT', 'Fortnight Reports', 'fortnight', 'View fortnight reports'],
            ['FORTNIGHT_EXPORT', 'Export Fortnight', 'fortnight', 'Export fortnight to Excel/PDF'],
            
            // ============================================
            // MIS MODULE (Already exists but ensuring)
            // ============================================
            ['MIS_VIEW', 'MIS - View', 'mis', 'View MIS reports'],
            ['MIS_CREATE', 'MIS - Create', 'mis', 'Create new MIS reports'],
            ['MIS_EDIT', 'MIS - Edit', 'mis', 'Edit MIS reports'],
            ['MIS_EXPORT', 'MIS - Export', 'mis', 'Export MIS reports to Excel/PDF'],
            ['MIS_DELETE', 'MIS - Delete', 'mis', 'Delete MIS reports'],
            ['MIS_LOCK', 'MIS - Lock', 'mis', 'Lock MIS reports'],
            ['MIS_COMPREHENSIVE', 'MIS Comprehensive', 'mis', 'View comprehensive MIS reports'],
            
            // ============================================
            // EMPLOYEE MODULE
            // ============================================
            ['EMPLOYEE_VIEW', 'View Employees', 'employee', 'View employee list and details'],
            ['EMPLOYEE_CREATE', 'Create Employee', 'employee', 'Create new employee records'],
            ['EMPLOYEE_EDIT', 'Edit Employee', 'employee', 'Edit existing employee records'],
            ['EMPLOYEE_DELETE', 'Delete Employee', 'employee', 'Delete employee records'],
            ['EMPLOYEE_ROLE_ASSIGN', 'Assign Role to Employee', 'employee', 'Assign roles to employees'],
            ['EMPLOYEE_STATUS_CHANGE', 'Change Employee Status', 'employee', 'Change employee employment status'],
            ['EMPLOYEE_EXPORT', 'Export Employees', 'employee', 'Export employee data to Excel'],
            
            // ============================================
            // ATTENDANCE MODULE
            // ============================================
            ['ATTENDANCE_VIEW', 'View Attendance', 'attendance', 'View attendance records'],
            ['ATTENDANCE_CREATE', 'Create Attendance', 'attendance', 'Mark attendance for employees'],
            ['ATTENDANCE_EDIT', 'Edit Attendance', 'attendance', 'Edit attendance records'],
            ['ATTENDANCE_DELETE', 'Delete Attendance', 'attendance', 'Delete attendance records'],
            ['ATTENDANCE_APPROVE', 'Approve Attendance', 'attendance', 'Approve attendance records'],
            ['ATTENDANCE_EXPORT', 'Export Attendance', 'attendance', 'Export attendance to Excel'],
            ['ATTENDANCE_REPORT', 'Attendance Reports', 'attendance', 'View attendance reports'],
            
            // ============================================
            // LEAVE MODULE
            // ============================================
            ['LEAVE_VIEW', 'View Leaves', 'leave', 'View leave applications'],
            ['LEAVE_CREATE', 'Create Leave', 'leave', 'Create leave applications'],
            ['LEAVE_EDIT', 'Edit Leave', 'leave', 'Edit leave applications'],
            ['LEAVE_DELETE', 'Delete Leave', 'leave', 'Delete leave applications'],
            ['LEAVE_APPROVE', 'Approve Leave', 'leave', 'Approve leave applications'],
            ['LEAVE_REJECT', 'Reject Leave', 'leave', 'Reject leave applications'],
            ['LEAVE_EXPORT', 'Export Leave', 'leave', 'Export leave data to Excel'],
            
            // ============================================
            // OVERTIME MODULE
            // ============================================
            ['OVERTIME_VIEW', 'View Overtime', 'overtime', 'View overtime records'],
            ['OVERTIME_CREATE', 'Create Overtime', 'overtime', 'Create overtime entries'],
            ['OVERTIME_EDIT', 'Edit Overtime', 'overtime', 'Edit overtime records'],
            ['OVERTIME_DELETE', 'Delete Overtime', 'overtime', 'Delete overtime records'],
            ['OVERTIME_RATES_MANAGE', 'Manage Overtime Rates', 'overtime', 'Manage overtime rates and configurations'],
            ['OVERTIME_EXPORT', 'Export Overtime', 'overtime', 'Export overtime to Excel'],
            
            // ============================================
            // TRANSFER MODULE
            // ============================================
            ['TRANSFER_VIEW', 'View Transfer', 'transfer', 'View employee transfer records'],
            ['TRANSFER_CREATE', 'Create Transfer', 'transfer', 'Create employee transfers'],
            ['TRANSFER_EDIT', 'Edit Transfer', 'transfer', 'Edit transfer records'],
            ['TRANSFER_DELETE', 'Delete Transfer', 'transfer', 'Delete transfer records'],
            ['TRANSFER_APPROVE', 'Approve Transfer', 'transfer', 'Approve employee transfers'],
            ['TRANSFER_EXPORT', 'Export Transfer', 'transfer', 'Export transfer data to Excel'],
            
            // ============================================
            // EXIT MODULE
            // ============================================
            ['EXIT_VIEW', 'View Exit', 'exit', 'View employee exit records'],
            ['EXIT_CREATE', 'Create Exit', 'exit', 'Create employee exit records'],
            ['EXIT_EDIT', 'Edit Exit', 'exit', 'Edit exit records'],
            ['EXIT_DELETE', 'Delete Exit', 'exit', 'Delete exit records'],
            ['EXIT_APPROVE', 'Approve Exit', 'exit', 'Approve employee exit'],
            ['EXIT_EXPORT', 'Export Exit', 'exit', 'Export exit data to Excel'],
            
            // ============================================
            // REPORTS MODULE
            // ============================================
            ['REPORTS_VIEW', 'View Reports', 'reports', 'View all reports'],
            ['REPORTS_EXPORT', 'Export Reports', 'reports', 'Export reports to Excel/PDF'],
            ['REPORTS_ANALYTICS', 'View Analytics', 'reports', 'Access analytics and insights'],
            ['REPORTS_ATTENDANCE', 'Attendance Reports', 'reports', 'View attendance reports'],
            ['REPORTS_LEAVE', 'Leave Reports', 'reports', 'View leave reports'],
            ['REPORTS_PAYROLL', 'Payroll Reports', 'reports', 'View payroll reports'],
            ['REPORTS_EMPLOYEE', 'Employee Reports', 'reports', 'View employee reports'],
            
            // ============================================
            // DASHBOARD MODULE
            // ============================================
            ['DASHBOARD_VIEW', 'View Dashboard', 'dashboard', 'Access to view dashboard and statistics'],
            
            // ============================================
            // SETTINGS MODULE
            // ============================================
            ['SETTINGS_VIEW', 'View Settings', 'settings', 'View system settings'],
            ['SETTINGS_EDIT', 'Edit Settings', 'settings', 'Edit system settings'],
            ['SETTINGS_DEPARTMENTS_MANAGE', 'Manage Departments', 'settings', 'Manage departments and designations'],
            ['SETTINGS_LEAVE_TYPES_MANAGE', 'Manage Leave Types', 'settings', 'Manage leave types'],
            ['SETTINGS_SALARY_COMPONENTS_MANAGE', 'Manage Salary Components', 'settings', 'Manage salary components'],
            ['SETTINGS_INVENTORY_MANAGE', 'Manage Inventory Items', 'settings', 'Manage inventory items'],
            ['SETTINGS_EXPENSE_HEADS_MANAGE', 'Manage Expense Heads', 'settings', 'Manage expense heads'],
            ['SETTINGS_SUPPLIERS_MANAGE', 'Manage Suppliers', 'settings', 'Manage suppliers'],
            
            // ============================================
            // USER MODULE
            // ============================================
            ['USER_MANAGE', 'Manage Users', 'user', 'Create, edit, and manage users'],
            ['USER_VIEW', 'View Users', 'user', 'View user list'],
            ['USER_CREATE', 'Create User', 'user', 'Create new users'],
            ['USER_EDIT', 'Edit User', 'user', 'Edit user details'],
            ['USER_DELETE', 'Delete User', 'user', 'Delete users'],
            
            // ============================================
            // SITE MODULE
            // ============================================
            ['SITE_MANAGE', 'Manage Sites', 'site', 'Create, edit, and manage sites'],
            ['SITE_VIEW', 'View Sites', 'site', 'View site list'],
            ['SITE_CREATE', 'Create Site', 'site', 'Create new sites'],
            ['SITE_EDIT', 'Edit Site', 'site', 'Edit site details'],
            ['SITE_DELETE', 'Delete Site', 'site', 'Delete sites'],
            
            // ============================================
            // ROLE MODULE
            // ============================================
            ['ROLE_VIEW', 'View Roles', 'role', 'View roles and permissions'],
            ['ROLE_CREATE', 'Create Role', 'role', 'Create custom roles'],
            ['ROLE_EDIT', 'Edit Role', 'role', 'Edit roles and permissions'],
            ['ROLE_DELETE', 'Delete Role', 'role', 'Delete custom roles'],
            ['ROLE_ASSIGN', 'Assign Role', 'role', 'Assign roles to users'],
        ];
        
        $stmt = $db->prepare("
            INSERT INTO permissions (permission_code, permission_name, permission_module, permission_description)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                permission_name = VALUES(permission_name),
                permission_module = VALUES(permission_module),
                permission_description = VALUES(permission_description)
        ");
        
        $added = 0;
        $updated = 0;
        $skipped = 0;
        
        foreach ($permissions as $perm) {
            try {
                $stmt->execute($perm);
                if ($db->lastInsertId() > 0) {
                    $added++;
                } else {
                    $updated++;
                }
            } catch (Exception $e) {
                // Skip if duplicate or error
                $skipped++;
                error_log("Permission seed error for {$perm[0]}: " . $e->getMessage());
            }
        }
        
        $db->commit();
        
        $message = "✅ Permissions seeded successfully!<br>";
        $message .= "📊 Added: <strong>$added</strong> new permissions<br>";
        $message .= "🔄 Updated: <strong>$updated</strong> existing permissions<br>";
        $message .= "⏭️ Skipped: <strong>$skipped</strong> permissions<br>";
        $message .= "📦 Total: <strong>" . count($permissions) . "</strong> permissions processed";
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $error = "❌ Error: " . $e->getMessage();
        error_log("Permission seed error: " . $e->getMessage());
    }
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Seed All Module Permissions</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/admin/role_management_dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Role Management</a>
        </div>
    </div>
    
    <?php if ($message): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        <?php echo $message; ?>
    </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>
    
    <div style="margin-top: 20px; padding: 20px; background: #f9fafb; border-radius: 8px;">
        <h3 style="margin-bottom: 15px;">📋 Modules Covered</h3>
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
            <div>
                <h4 style="margin-bottom: 10px; color: var(--primary-color);">💰 Payroll Module</h4>
                <ul style="margin-left: 20px; font-size: 14px;">
                    <li>Payroll Home</li>
                    <li>Instructions</li>
                    <li>Employee Master Sheet</li>
                    <li>Employee Master Change</li>
                    <li>Attendance</li>
                    <li>Salary Register</li>
                    <li>New Joinee Statutory</li>
                    <li>Overtime</li>
                    <li>Resigned & Abscondee</li>
                    <li>Leave Form</li>
                    <li>Payslip</li>
                </ul>
            </div>
            
            <div>
                <h4 style="margin-bottom: 10px; color: var(--primary-color);">📦 Stock Group</h4>
                <ul style="margin-left: 20px; font-size: 14px;">
                    <li>💵 Petty Cash</li>
                    <li>🍽️ DFC</li>
                    <li>📊 Fortnight</li>
                    <li>📊 MIS Reports</li>
                </ul>
            </div>
            
            <div>
                <h4 style="margin-bottom: 10px; color: var(--primary-color);">👥 Other Modules</h4>
                <ul style="margin-left: 20px; font-size: 14px;">
                    <li>Employee Management</li>
                    <li>Attendance</li>
                    <li>Leave</li>
                    <li>Overtime</li>
                    <li>Transfer</li>
                    <li>Exit</li>
                    <li>Reports</li>
                    <li>Settings</li>
                </ul>
            </div>
        </div>
        
        <p style="margin-top: 20px; padding: 15px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
            <strong>⚠️ Important:</strong> This will add all missing permissions to your database. 
            Existing permissions will be updated. After running this, you'll be able to see all module permissions 
            when creating custom roles.
        </p>
    </div>
    
    <form method="POST" style="margin-top: 30px;">
        <div style="text-align: center; padding: 20px;">
            <button type="submit" name="seed" class="btn btn-primary" style="font-size: 16px; padding: 12px 30px;">
                🌱 Seed All Module Permissions
            </button>
        </div>
    </form>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

