<?php
require 'db/config.php';
$db = db();

try {
    $db->exec("CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        role ENUM('worker', 'admin') NOT NULL,
        pin_hash VARCHAR(255) DEFAULT NULL,
        assigned_processes JSON DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    $stmt = $db->query("SELECT COUNT(*) FROM users");
    if ($stmt->fetchColumn() == 0) {
        $db->prepare("INSERT INTO users (name, role, assigned_processes) VALUES (?, ?, ?)")
           ->execute(['John Operator', 'worker', json_encode(['cutting', 'welding'])]);
        $db->prepare("INSERT INTO users (name, role, assigned_processes) VALUES (?, ?, ?)")
           ->execute(['Sarah Smith', 'worker', json_encode(['bending', 'assembly'])]);
        // Admin user
        $db->prepare("INSERT INTO users (name, role) VALUES (?, ?)")
           ->execute(['Mike Manager', 'admin']);
        echo "Users table created and seeded.\n";
    } else {
        echo "Users table already exists and is not empty.\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

