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

try {
    $pdo = db();
    
    echo "Starting database setup...\n";

    // 1. People table (unified table for users and contacts)
    $pdo->exec("CREATE TABLE IF NOT EXISTS `people` (
        `id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `first_name` VARCHAR(255) NOT NULL,
        `last_name` VARCHAR(255) NOT NULL,
        `email` VARCHAR(255) NOT NULL UNIQUE,
        `password` VARCHAR(255) NULL,
        `company_name` VARCHAR(255) DEFAULT NULL,
        `phone` VARCHAR(50) DEFAULT NULL,
        `role` ENUM('admin', 'team_member', 'member', 'guest') NOT NULL DEFAULT 'guest',
        `is_user` BOOLEAN NOT NULL DEFAULT FALSE,
        `active` BOOLEAN NOT NULL DEFAULT TRUE,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    echo "People table created or already exists.\n";

    // Seed default admin user
    $stmt = $pdo->prepare("SELECT id FROM people WHERE email = ?");
    $stmt->execute(['admin@example.com']);
    if ($stmt->fetchColumn() === false) {
        $password = password_hash('password', PASSWORD_DEFAULT);
        $insert_stmt = $pdo->prepare(
            "INSERT INTO people (email, password, role, first_name, last_name, is_user, active) VALUES (?, ?, 'admin', 'Admin', 'User', TRUE, TRUE)"
        );
        $insert_stmt->execute(['admin@example.com', $password]);
        echo "Default admin user created. Email: admin@example.com, Password: password\n";
    }

    // 2. Process Definitions table
    $pdo->exec("CREATE TABLE IF NOT EXISTS `process_definitions` (
        `id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `code` VARCHAR(255) NOT NULL UNIQUE,
        `name` VARCHAR(255) NOT NULL,
        `description` TEXT,
        `version` INT NOT NULL DEFAULT 1,
        `is_active` BOOLEAN NOT NULL DEFAULT TRUE,
        `start_node_id` VARCHAR(255),
        `definition_json` TEXT,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    echo "Process definitions table created or already exists.\n";

    // Seed process_definitions
    $processes = [
        ['code' => 'mentoring', 'name' => 'Mentoring nowego czlonka', 'description' => 'Proces wdrozenia nowego czlonka do organizacji.'],
        ['code' => 'meeting_preparation', 'name' => 'Przygotowanie spotkania grupy', 'description' => 'Proces przygotowania do spotkania grupy, w tym agenda, materialy, etc.'],
        ['code' => 'guest_handling', 'name' => 'Obsluga goscia', 'description' => 'Proces obslugi gosci odwiedzajacych organizacje.']
    ];
    $stmt = $pdo->prepare("SELECT id FROM process_definitions WHERE code = ?");
    $insert_stmt = $pdo->prepare("INSERT INTO process_definitions (code, name, description) VALUES (?, ?, ?)");
    foreach ($processes as $process) {
        $stmt->execute([$process['code']]);
        if ($stmt->fetchColumn() === false) {
            $insert_stmt->execute([$process['code'], $process['name'], $process['description']]);
            echo "Seeded process: " . $process['name'] . "\n";
        }
    }

    // 3. Process Instances table (updated FK)
    $pdo->exec("CREATE TABLE IF NOT EXISTS `process_instances` (
        `id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `person_id` INT(11) UNSIGNED NOT NULL,
        `process_definition_id` INT(11) UNSIGNED NOT NULL,
        `current_status` VARCHAR(255) NOT NULL DEFAULT 'none',
        `current_node_id` VARCHAR(255),
        `current_reason` TEXT,
        `suggested_next_step` TEXT,
        `data_json` TEXT,
        `last_activity_at` TIMESTAMP NULL,
        FOREIGN KEY (person_id) REFERENCES people(id) ON DELETE CASCADE,
        FOREIGN KEY (process_definition_id) REFERENCES process_definitions(id) ON DELETE CASCADE,
        UNIQUE KEY `person_process` (`person_id`, `process_definition_id`)
    )");
    echo "Process instances table created or already exists.\n";

    // 4. Process Events table (updated FK)
    $pdo->exec("CREATE TABLE IF NOT EXISTS `process_events` (
        `id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `process_instance_id` INT(11) UNSIGNED NOT NULL,
        `event_type` VARCHAR(50) NOT NULL,
        `message` TEXT,
        `node_id` VARCHAR(255),
        `payload_json` TEXT,
        `created_by` INT(11) UNSIGNED NOT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (process_instance_id) REFERENCES process_instances(id) ON DELETE CASCADE,
        FOREIGN KEY (created_by) REFERENCES people(id) ON DELETE CASCADE
    )");
    echo "Process events table created or already exists.\n";
    
    // MIGRATIONS
    echo "Starting migrations...\n";

    // Migration: Rename `processId` to `processDefinitionId` in `process_instances`
    $stmt = $pdo->query("SHOW COLUMNS FROM `process_instances` LIKE 'processId'");
    if ($stmt->fetch()) {
        $checkFk = $pdo->query("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = SCHEMA() AND TABLE_NAME = 'process_instances' AND COLUMN_NAME = 'processId';")->fetch();
        if ($checkFk) {
             $pdo->exec("ALTER TABLE `process_instances` DROP FOREIGN KEY `{$checkFk['CONSTRAINT_NAME']}`;");
        }
        $pdo->exec("ALTER TABLE `process_instances` CHANGE `processId` `process_definition_id` INT(11) UNSIGNED NOT NULL;");
        $pdo->exec("ALTER TABLE `process_instances` ADD FOREIGN KEY (`process_definition_id`) REFERENCES `process_definitions`(`id`) ON DELETE CASCADE;");
        echo "Migrated process_instances: processId -> processDefinitionId.\n";
    }

    // Migration: Rename `contactId` to `personId` and update foreign key in `process_instances`
    $stmt = $pdo->query("SHOW COLUMNS FROM `process_instances` LIKE 'contactId'");
    if ($stmt->fetch()) {
        $checkFk = $pdo->query("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = SCHEMA() AND TABLE_NAME = 'process_instances' AND COLUMN_NAME = 'contactId';")->fetch();
        if ($checkFk) {
             $pdo->exec("ALTER TABLE `process_instances` DROP FOREIGN KEY `{$checkFk['CONSTRAINT_NAME']}`;");
        }
        $pdo->exec("ALTER TABLE `process_instances` CHANGE `contactId` `person_id` INT(11) UNSIGNED NOT NULL;");
        echo "Migrated process_instances: contactId -> personId.\n";
    }

    
    // Drop old tables if they exist
    $pdo->exec("DROP TABLE IF EXISTS `users`, `contacts`;");
    echo "Dropped old 'users' and 'contacts' tables.\n";

    echo "\nDatabase setup/update completed successfully.\n";

} catch (PDOException $e) {
    die("Database setup failed: " . $e->getMessage());
}