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

$tables = [
    'dashboards', 
    'machinery', 
    'roles', 
    'skills', 
    'task_statuses', 
    'users', 
    'workflow_stages', 
    'workflow_statuses', 
    'units'
];

foreach ($tables as $table) {
    try {
        // Check if table exists
        $tableExists = fetch("SHOW TABLES LIKE '$table'");
        if (!$tableExists) {
            echo "-- Table '$table' does not exist.\n\n";
            continue;
        }

        $rows = fetchAll("SELECT * FROM $table");
        if (empty($rows)) {
            echo "-- No data found in '$table'.\n\n";
            continue;
        }

        echo "-- Data for table '$table'\n";
        foreach ($rows as $row) {
            $cols = array_keys($row);
            $vals = array_values($row);
            
            $escaped_vals = array_map(function($v) use ($pdo) {
                if ($v === null) return 'NULL';
                return $pdo->quote($v);
            }, $vals);

            echo "INSERT INTO `$table` (`" . implode("`, `", $cols) . "`) VALUES (" . implode(", ", $escaped_vals) . ");\n";
        }
        echo "\n";
    } catch (Exception $e) {
        echo "-- Error dumping '$table': " . $e->getMessage() . "\n\n";
    }
}
