#!/usr/bin/env php
<?php
/**
 * Setup Assignment Notification System
 * 
 * This script sets up everything needed for the assignment notification system:
 * 1. Runs database migrations
 * 2. Creates necessary directories
 * 3. Sets proper permissions
 * 4. Verifies email configuration
 */

// Define the root path
define('ROOT_PATH', dirname(__DIR__, 1));

echo "Setting up Assignment Notification System...\n";

// 1. Run database migrations
echo "\n[1/4] Running database migrations...\n";
try {
    // Include database connection
    require_once ROOT_PATH . '/config/database.php';
    
    // Get migration SQL
    $migrationSql = file_get_contents(ROOT_PATH . '/database/migrations/assignment_reminder_schema.sql');
    
    // Split into individual statements
    $statements = array_filter(array_map('trim', explode(';', $migrationSql)));
    
    // Execute each statement
    $conn = $db->getConnection();
    $success = true;
    
    foreach ($statements as $statement) {
        if (!empty($statement)) {
            try {
                $result = $conn->exec($statement);
                echo "  - Executed: " . substr($statement, 0, 50) . "...\n";
            } catch (PDOException $e) {
                echo "  - Error executing: " . substr($statement, 0, 50) . "...\n";
                echo "    " . $e->getMessage() . "\n";
                $success = false;
            }
        }
    }
    
    if ($success) {
        echo "  ✓ Database migration completed successfully.\n";
    } else {
        echo "  ✗ Database migration completed with errors.\n";
    }
} catch (Exception $e) {
    echo "  ✗ Database migration failed: " . $e->getMessage() . "\n";
}

// 2. Create necessary directories
echo "\n[2/4] Creating necessary directories...\n";
$directories = [
    ROOT_PATH . '/logs/email',
    ROOT_PATH . '/services/email/templates/cache'
];

foreach ($directories as $dir) {
    if (!file_exists($dir)) {
        if (mkdir($dir, 0755, true)) {
            echo "  ✓ Created directory: $dir\n";
        } else {
            echo "  ✗ Failed to create directory: $dir\n";
        }
    } else {
        echo "  - Directory already exists: $dir\n";
    }
}

// 3. Set proper permissions
echo "\n[3/4] Setting proper permissions...\n";
$permissions = [
    [ROOT_PATH . '/logs/email', 0755],
    [ROOT_PATH . '/logs/email_log.txt', 0666],
    [ROOT_PATH . '/scripts/send_assignment_reminders.php', 0755]
];

foreach ($permissions as $perm) {
    list($path, $mode) = $perm;
    
    // Create the file if it doesn't exist
    if (!file_exists($path) && strpos($path, '.') !== false) {
        touch($path);
        echo "  - Created file: $path\n";
    }
    
    if (file_exists($path)) {
        if (chmod($path, $mode)) {
            echo "  ✓ Set permissions " . decoct($mode) . " on: $path\n";
        } else {
            echo "  ✗ Failed to set permissions on: $path\n";
        }
    } else {
        echo "  - Path does not exist, skipping: $path\n";
    }
}

// 4. Verify email configuration
echo "\n[4/4] Verifying email configuration...\n";
$configFile = ROOT_PATH . '/config/email_config.php';

if (file_exists($configFile)) {
    echo "  - Email configuration file exists.\n";
    
    // Check if constants are defined
    require_once $configFile;
    
    $constants = [
        'EMAIL_FROM',
        'EMAIL_FROM_NAME',
        'EMAIL_REPLY_TO',
        'SITE_NAME',
        'SITE_URL',
        'EMAIL_DEBUG_MODE',
        'ENABLE_ASSIGNMENT_NOTIFICATIONS'
    ];
    
    $allDefined = true;
    foreach ($constants as $constant) {
        if (defined($constant)) {
            echo "  ✓ $constant is defined as: " . constant($constant) . "\n";
        } else {
            echo "  ✗ $constant is not defined.\n";
            $allDefined = false;
        }
    }
    
    if ($allDefined) {
        echo "  ✓ Email configuration is complete.\n";
    } else {
        echo "  ✗ Email configuration is incomplete. Please update $configFile\n";
    }
} else {
    echo "  ✗ Email configuration file does not exist. Creating template...\n";
    
    $template = <<<'PHP'
<?php
/**
 * Email Configuration
 */

// Email settings
define('EMAIL_FROM', 'noreply@kso-chandigarh.org');
define('EMAIL_FROM_NAME', 'KSO Chandigarh Admin Panel');
define('EMAIL_REPLY_TO', 'support@kso-chandigarh.org');
define('SITE_NAME', 'KSO Chandigarh');
define('SITE_URL', 'https://admin.kso-chandigarh.org');

// Email debug mode (set to true to log emails instead of sending them)
define('EMAIL_DEBUG_MODE', true);

// Enable/disable specific notification types
define('ENABLE_ASSIGNMENT_NOTIFICATIONS', true);
define('ENABLE_ASSIGNMENT_REMINDERS', true);
define('ENABLE_SUPERVISOR_ESCALATIONS', true);
PHP;
    
    if (file_put_contents($configFile, $template)) {
        echo "  ✓ Created email configuration template. Please update with your settings.\n";
    } else {
        echo "  ✗ Failed to create email configuration template.\n";
    }
}

echo "\nSetup completed. Please review any errors above.\n";
echo "To enable scheduled reminders, set up a daily cron job or scheduled task for:\n";
echo "php " . ROOT_PATH . "/scripts/send_assignment_reminders.php\n";
