<?php
require_once '../core/bootstrap.php';

// --- Security Check ---
// Only allow Super Admin to perform this action
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'super_admin') {
    header('Location: dashboard.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db = new Database();

    try {
        // Disable foreign key checks to allow truncation of tables with relationships
        $db->query('SET FOREIGN_KEY_CHECKS = 0');
        $db->execute();

        // Get list of all tables in the database
        $db->query('SHOW TABLES');
        $result = $db->resultSet();
        
        $tables = [];
        foreach ($result as $row) {
            // Convert object to array and get the first value (table name)
            $rowArray = (array)$row;
            $tables[] = array_values($rowArray)[0];
        }

        // Define tables to exclude from truncation
        // We keep roles, permissions, users, and settings
        $excluded_tables = ['roles', 'permissions', 'role_permissions', 'users', 'settings'];

        foreach ($tables as $table) {
            if (in_array($table, $excluded_tables)) {
                continue;
            }
            
            // Truncate the table
            $db->query("TRUNCATE TABLE `$table`");
            $db->execute();
        }

        // Handle Users table: Delete all users EXCEPT the Super Admin
        // We assume the role 'super_admin' identifies the super admin.
        $db->query("DELETE FROM users WHERE role != 'super_admin'");
        $db->execute();

        // Re-enable foreign key checks
        $db->query('SET FOREIGN_KEY_CHECKS = 1');
        $db->execute();

        // Set success message
        $_SESSION['flash_message'] = 'Database has been reset. All data cleared except Roles, Permissions, and Super Admin.';
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = 'Database reset failed: ' . $e->getMessage();
    }

    // Redirect back to dashboard
    header('Location: dashboard.php');
    exit();
} else {
    // If accessed directly via GET, redirect to dashboard
    header('Location: dashboard.php');
    exit();
}