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

header('Content-Type: application/json');

// Critical security check: Only Superadmins allowed
if (!hasRole('superadmin')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized Access']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? $_GET['action'] ?? '';
$table = $data['table'] ?? $_GET['table'] ?? '';

// Restricted list of tables to prevent arbitrary DB access
$allowed_tables = [
    'dashboards', 'machinery', 'roles', 'skills', 
    'task_statuses', 'users', 'workflow_stages', 'workflow_statuses', 'units', 'companies'
];

if ($action !== 'truncate_database' && !in_array($table, $allowed_tables)) {
    echo json_encode(['success' => false, 'message' => 'Invalid table']);
    exit;
}

switch ($action) {
    case 'list':
        $page = (int)($data['page'] ?? $_GET['page'] ?? 1);
        $limit = (int)($data['limit'] ?? $_GET['limit'] ?? 10);
        $offset = ($page - 1) * $limit;

        $total = fetchValue("SELECT COUNT(*) FROM $table");
        $items = fetchAll("SELECT * FROM $table ORDER BY id ASC LIMIT $limit OFFSET $offset");
        
        echo json_encode([
            'success' => true, 
            'data' => $items,
            'pagination' => [
                'total' => (int)$total,
                'page' => $page,
                'limit' => $limit,
                'pages' => ceil($total / $limit)
            ]
        ]);
        break;

    case 'save':
        $record = $data['data'] ?? [];
        if (empty($record)) {
            echo json_encode(['success' => false, 'message' => 'No data provided']);
            exit;
        }

        $id = $record['id'] ?? null;
        
        // Special handling for users password
        if ($table === 'users' && !empty($record['password'])) {
            // Only hash if it's not already hashed (assuming length 60 for bcrypt)
            if (strlen($record['password']) < 20) {
                $record['password'] = password_hash($record['password'], PASSWORD_DEFAULT);
            }
        }

        unset($record['id'], $record['created_at'], $record['updated_at']);

        try {
            if ($id) {
                $sets = [];
                $values = [];
                foreach ($record as $key => $val) {
                    $sets[] = "$key = ?";
                    $values[] = $val;
                }
                $values[] = $id;
                query("UPDATE $table SET " . implode(', ', $sets) . " WHERE id = ?", $values);
                echo json_encode(['success' => true, 'message' => 'Record updated']);
            } else {
                $cols = implode(', ', array_keys($record));
                $placeholders = implode(', ', array_fill(0, count($record), '?'));
                query("INSERT INTO $table ($cols) VALUES ($placeholders)", array_values($record));
                echo json_encode(['success' => true, 'message' => 'Record created', 'id' => $pdo->lastInsertId()]);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    case 'delete':
        $id = $data['id'] ?? null;
        if ($id) {
            try {
                query("DELETE FROM $table WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Record deleted']);
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'message' => 'Delete failed: ' . $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing ID']);
        }
        break;
    
    case 'truncate_database':
        try {
            // 1. Disable foreign key checks to allow truncating tables with relationships
            query("SET FOREIGN_KEY_CHECKS = 0");
            
            // 2. Get all tables in the current database
            $tables = fetchAll("SHOW TABLES");
            $db_name = fetchValue("SELECT DATABASE()");
            $column_name = "Tables_in_" . $db_name;
            
            $truncated = [];
            foreach ($tables as $row) {
                $tableName = $row[$column_name];
                // Truncate the table
                query("TRUNCATE TABLE `$tableName` ");
                $truncated[] = $tableName;
            }
            
            // 3. Re-enable foreign key checks
            query("SET FOREIGN_KEY_CHECKS = 1");
            
            echo json_encode([
                'success' => true, 
                'message' => 'Database truncated successfully',
                'tables_affected' => count($truncated)
            ]);
        } catch (Exception $e) {
            // Ensure checks are re-enabled even on failure
            query("SET FOREIGN_KEY_CHECKS = 1");
            echo json_encode(['success' => false, 'message' => 'Truncation failed: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
