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

try {
    // 1. Jobs
    $db->exec("CREATE TABLE IF NOT EXISTS jobs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        quantity INT DEFAULT 1,
        due_date DATE DEFAULT NULL,
        serial_number VARCHAR(100) UNIQUE,
        status ENUM('planned', 'in_progress', 'completed') DEFAULT 'planned',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    // 2. Components (BOM structure)
    $db->exec("CREATE TABLE IF NOT EXISTS components (
        id INT AUTO_INCREMENT PRIMARY KEY,
        job_id INT NOT NULL,
        parent_id INT DEFAULT NULL,
        name VARCHAR(255) NOT NULL,
        status ENUM('pending', 'in_progress', 'completed') DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (job_id) REFERENCES jobs(id) ON DELETE CASCADE,
        FOREIGN KEY (parent_id) REFERENCES components(id) ON DELETE CASCADE
    )");

    // 3. Operations
    $db->exec("CREATE TABLE IF NOT EXISTS operations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        component_id INT NOT NULL,
        name VARCHAR(255) NOT NULL,
        process_type VARCHAR(100) NOT NULL, -- e.g. cutting, welding
        status ENUM('pending', 'in_progress', 'stalled', 'completed') DEFAULT 'pending',
        assigned_worker_id INT DEFAULT NULL,
        priority INT DEFAULT 0,
        start_time DATETIME DEFAULT NULL,
        end_time DATETIME DEFAULT NULL,
        stall_reason TEXT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (component_id) REFERENCES components(id) ON DELETE CASCADE,
        FOREIGN KEY (assigned_worker_id) REFERENCES users(id) ON DELETE SET NULL
    )");

    // 4. Inventory
    $db->exec("CREATE TABLE IF NOT EXISTS inventory (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        category ENUM('material', 'consumable', 'hardware') NOT NULL,
        stock_level DECIMAL(10,2) DEFAULT 0,
        reorder_level DECIMAL(10,2) DEFAULT 0,
        unit VARCHAR(50) DEFAULT 'pcs',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    // 5. Inventory Transactions
    $db->exec("CREATE TABLE IF NOT EXISTS inventory_transactions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        inventory_id INT NOT NULL,
        type ENUM('in', 'out') NOT NULL,
        quantity DECIMAL(10,2) NOT NULL,
        user_id INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (inventory_id) REFERENCES inventory(id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES users(id)
    )");

    // 6. Time Study Events
    $db->exec("CREATE TABLE IF NOT EXISTS time_study_events (
        id INT AUTO_INCREMENT PRIMARY KEY,
        operation_id INT NOT NULL,
        user_id INT NOT NULL,
        event_type ENUM('start', 'stalled', 'completed', 'resume') NOT NULL,
        reason TEXT DEFAULT NULL,
        timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (operation_id) REFERENCES operations(id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES users(id)
    )");

    echo "Manufacturing core tables created successfully.\n";

    // Seed some initial data if empty
    $stmt = $db->query("SELECT COUNT(*) FROM jobs");
    if ($stmt->fetchColumn() == 0) {
        // Sample Job
        $db->exec("INSERT INTO jobs (name, quantity, due_date, serial_number, status) VALUES ('Project ALPHA', 10, '2026-03-15', 'SN-001', 'planned')");
        $jobId = $db->lastInsertId();

        // Sample Component
        $db->exec("INSERT INTO components (job_id, name, status) VALUES ($jobId, 'Main Chassis', 'pending')");
        $compId = $db->lastInsertId();

        // Sample Operations
        $db->exec("INSERT INTO operations (component_id, name, process_type, status, priority) VALUES ($compId, 'Cut steel plate', 'cutting', 'pending', 1)");
        $db->exec("INSERT INTO operations (component_id, name, process_type, status, priority) VALUES ($compId, 'Weld corners', 'welding', 'pending', 2)");

        // Sample Inventory
        $db->exec("INSERT INTO inventory (name, category, stock_level, reorder_level) VALUES ('Steel Plate 5mm', 'material', 50, 10)");
        $db->exec("INSERT INTO inventory (name, category, stock_level, reorder_level) VALUES ('Welding Rods', 'consumable', 100, 20)");

        echo "Sample manufacturing data seeded.\n";
    }

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

