#!/usr/bin/env php
<?php

/**
 * Staff Chat Channel Initialization Script
 *
 * Creates the default public channel for each active store.
 * This script is idempotent - safe to run multiple times.
 *
 * Per PRD Business Rule 1: "Every store has exactly one 'Public' channel created automatically"
 *
 * Usage:
 *   php userfrosting/bin/staff-chat-init-channels           # Initialize all stores
 *   php userfrosting/bin/staff-chat-init-channels --store=ou00  # Initialize specific store
 *   php userfrosting/bin/staff-chat-init-channels --dry-run # Show what would be done
 *
 * @package BuyerKiosk\StaffChat
 * @see docs/specs/024-staff-chat-backend/implementation-plan.md Phase 15
 */

// Prevent web access
if (php_sapi_name() !== 'cli') {
    die('This script must be run from the command line.');
}

// Set up error reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Ensure Slim environment bootstrap has required server keys in CLI context
$_SERVER['REQUEST_METHOD'] ??= 'CLI';
$_SERVER['REMOTE_ADDR'] ??= '127.0.0.1';
$_SERVER['REQUEST_URI'] ??= '/';

// Change to the userfrosting directory for proper path resolution
$ufDir = dirname(__DIR__);
chdir($ufDir);

// Load the application bootstrap (initializes autoloading, environment, DB connections)
require_once $ufDir . '/initialize.php';

// Now database functions are available (defined in models/BaseModel.php, loaded by initialize.php)
// $db_name is set to kiosk_buykiosk in lib/config.php (contains the stores table)

// Parse command-line arguments
$options = getopt('', ['store:', 'dry-run', 'help']);

if (isset($options['help'])) {
    echo <<<HELP
Staff Chat Channel Initialization Script

Creates the default public channel for each active store.
This script is idempotent - safe to run multiple times.

Usage:
  php userfrosting/bin/staff-chat-init-channels           # Initialize all stores
  php userfrosting/bin/staff-chat-init-channels --store=ou00  # Initialize specific store
  php userfrosting/bin/staff-chat-init-channels --dry-run # Show what would be done
  php userfrosting/bin/staff-chat-init-channels --help    # Show this help

Options:
  --store=TYPENUM  Initialize only the specified store
  --dry-run        Show what would be done without making changes
  --help           Show this help message

HELP;
    exit(0);
}

$dryRun = isset($options['dry-run']);
$specificStore = $options['store'] ?? null;

// Get central database connection
// The stores table is in kiosk_buykiosk (set via $db_name in lib/config.php)
global $db_name;
$centralDb = dbConnectByName($db_name);

echo "Staff Chat Channel Initialization\n";
echo "==================================\n\n";

if ($dryRun) {
    echo "[DRY RUN MODE - No changes will be made]\n\n";
}

// Get list of active stores
if ($specificStore) {
    // Validate store format
    if (!preg_match('/^[a-z]{2}\d+$/', $specificStore)) {
        echo "ERROR: Invalid store format '{$specificStore}'. Expected format: [a-z][a-z][0-9]+ (e.g., ou00)\n";
        exit(1);
    }

    $stmt = $centralDb->prepare("SELECT id, typeNum FROM stores WHERE typeNum = :typeNum AND active = 1");
    $stmt->execute(['typeNum' => $specificStore]);
    $stores = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($stores)) {
        echo "ERROR: Store '{$specificStore}' not found or not active.\n";
        exit(1);
    }
} else {
    $stmt = $centralDb->query("SELECT id, typeNum FROM stores WHERE active = 1 ORDER BY typeNum");
    $stores = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$totalStores = count($stores);
$created = 0;
$skipped = 0;
$errors = 0;

echo "Processing {$totalStores} store(s)...\n\n";

foreach ($stores as $store) {
    $typeNum = $store['typeNum'];

    // Validate typeNum format even from DB (defense in depth)
    if (!preg_match('/^[a-z]{2}\d+$/', $typeNum)) {
        echo "  [{$typeNum}] SKIPPED - Invalid typeNum format in database\n";
        $skipped++;
        continue;
    }

    try {
        // Connect to store database
        $storeDbName = "kiosk_{$typeNum}";
        $storeDb = dbConnectByName($storeDbName);

        if ($storeDb === null) {
            echo "  [{$typeNum}] ERROR - Could not connect to database\n";
            $errors++;
            continue;
        }

        // Check if channels table exists (migration may not have run)
        $tableCheck = $storeDb->query("SHOW TABLES LIKE 'staff_chat_channels'");
        if ($tableCheck->fetch() === false) {
            echo "  [{$typeNum}] SKIPPED - staff_chat_channels table does not exist (run migrations first)\n";
            $skipped++;
            continue;
        }

        // Check if Public channel already exists (by name, canonical identifier)
        $checkStmt = $storeDb->prepare("SELECT id, name, isDefault FROM staff_chat_channels WHERE typeNum = :typeNum AND name = 'Public'");
        $checkStmt->execute(['typeNum' => $typeNum]);
        $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            echo "  [{$typeNum}] EXISTS - Default channel '{$existing['name']}' (ID: {$existing['id']})\n";
            $skipped++;
            continue;
        }

        // Create default channel using repository (reuses logic, handles race conditions)
        if ($dryRun) {
            echo "  [{$typeNum}] WOULD CREATE - Default 'Public' channel\n";
            $created++;
        } else {
            // Use repository to ensure consistent defaults and race condition handling
            $repo = new \BuyerKiosk\StaffChat\Repositories\ChannelRepository($storeDb);
            $channel = $repo->getOrCreateDefaultChannel($typeNum, null); // null = system-created

            echo "  [{$typeNum}] CREATED - Default 'Public' channel (ID: {$channel->getId()})\n";
            $created++;
        }
    } catch (PDOException $e) {
        echo "  [{$typeNum}] ERROR - " . $e->getMessage() . "\n";
        $errors++;
    } catch (Exception $e) {
        echo "  [{$typeNum}] ERROR - " . $e->getMessage() . "\n";
        $errors++;
    }
}

// Summary
echo "\n";
echo "Summary\n";
echo "-------\n";
echo "Total stores processed: {$totalStores}\n";
echo "Channels created: {$created}\n";
echo "Channels already existed: {$skipped}\n";
echo "Errors: {$errors}\n";

if ($dryRun) {
    echo "\n[DRY RUN COMPLETE - Run without --dry-run to apply changes]\n";
}

exit($errors > 0 ? 1 : 0);
