<?php
include 'db.php';

if (!isset($_GET['type'])) {
    die("Invalid request");
}

$type = $_GET['type'];

// Tables to protect (never clear)
$protected_tables = [
    'branch_info', 'settings', 'setting_categories', 'setting_options',
    'roles', 'role_rights', 'rights', 'uom_groups', 'uoms'
];

if ($type === 'clear_all') {
    // Get all tables in the database
    $tables = [];
    $result = $conn->query("SHOW TABLES");
    while ($row = $result->fetch_array()) {
        $table = $row[0];
        if (!in_array($table, $protected_tables)) {
            $tables[] = $table;
        }
    }
    // Disable foreign key checks
    $conn->query("SET FOREIGN_KEY_CHECKS=0");
    foreach ($tables as $table) {
        $conn->query("TRUNCATE TABLE `$table`");
    }
    $conn->query("SET FOREIGN_KEY_CHECKS=1");
    header("Location: clear_data_panel.php?cleared=all");
    exit;
}

switch ($type) {
    case 'sales':
        $conn->query("DELETE FROM sale_items");
        $conn->query("DELETE FROM sales");
        $conn->query("DELETE FROM shifts");
        $conn->query("DELETE FROM hold_items");
        $conn->query("DELETE FROM hold_orders");
        $conn->query("DELETE FROM cus_outstanding");
        $conn->query("DELETE FROM cus_payments");
        $conn->query("DELETE FROM delivery_orders");
        $conn->query("DELETE FROM fbr_invoices");
        $conn->query("DELETE FROM fbr_logs");
        $conn->query("DELETE FROM sale_returns");
        $conn->query("DELETE FROM sale_return_items");
        break;

    case 'inventory':
        $conn->query("DELETE FROM purchase_items");
        $conn->query("DELETE FROM purchases");
        $conn->query("DELETE FROM inventory_movements");
        $conn->query("DELETE FROM purchase_returns");
        $conn->query("DELETE FROM purchase_return_items");
        $conn->query("DELETE FROM sup_outstanding");
        $conn->query("DELETE FROM sup_payments");
        break;

    case 'expenses':
        $conn->query("DELETE FROM expenses");
        $conn->query("DELETE FROM expense_accounts");
        $conn->query("DELETE FROM expense_categories");
        $conn->query("DELETE FROM expense_subcategories");
        break;

    case 'customer_ledgers':
        $conn->query("DELETE FROM cus_outstanding");
        $conn->query("DELETE FROM cus_payments");
        break;

    case 'supplier_ledgers':
        $conn->query("DELETE FROM sup_outstanding");
        $conn->query("DELETE FROM sup_payments");
        break;

    case 'items':
        $conn->query("DELETE FROM items");
        $conn->query("DELETE FROM categories");
        $conn->query("DELETE FROM sub_categories");
        $conn->query("DELETE FROM bom_master");
        $conn->query("DELETE FROM bom_components");
        $conn->query("DELETE FROM price_history");
        // Add any other item-related tables as needed
        break;

    default:
        die("Invalid type");
}

header("Location: clear_data_panel.php?cleared=$type");
exit;
?>
