#!/usr/bin/env php
<?php
/**
 * Restless Dreamers - Weekend Sessions App
 * Lightweight Artisan CLI Runner (Addendum 1 Compliant)
 * 
 * Works out-of-the-box on standard shared hosts with cron:
 * - * * * * * cd /path/to/app && php artisan schedule:run >> /dev/null 2>&1
 * - php artisan queue:work --stop-when-empty
 * - php artisan admin:create <email> <name>
 */

declare(strict_types=1);

if (php_sapi_name() !== 'cli') {
    exit("This script can only be run from the command line.\n");
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/core/Database.php';
require_once __DIR__ . '/core/Schema.php';
require_once __DIR__ . '/core/Auth.php';
require_once __DIR__ . '/core/TOTP.php';
require_once __DIR__ . '/core/Queue.php';
require_once __DIR__ . '/includes/CashfreeWebhook.php';

use RD\Core\Database;
use RD\Core\Schema;
use RD\Core\Auth;
use RD\Core\TOTP;
use RD\Core\Queue;
use RD\Includes\CashfreeWebhook;

// Parse command arguments
$argv = $_SERVER['argv'] ?? [];
$command = $argv[1] ?? 'help';

switch ($command) {
    case 'schedule:run':
        echo "[" . date('Y-m-d H:i:s') . "] Running Weekend Sessions Scheduler...\n";
        
        // 1. Process Database Queue (stop when empty)
        $processed = Queue::workStopWhenEmpty('default', 3);
        echo " - Processed {$processed} queue jobs.\n";

        // 2. Expire old pending reservations (> 20 min)
        $expired = CashfreeWebhook::expireOldReservations();
        echo " - Expired {$expired} abandoned reservations.\n";

        echo "[" . date('Y-m-d H:i:s') . "] Scheduler finished successfully.\n";
        break;

    case 'queue:work':
        $stopWhenEmpty = in_array('--stop-when-empty', $argv, true);
        echo "[" . date('Y-m-d H:i:s') . "] Processing queue jobs (stop-when-empty: " . ($stopWhenEmpty ? 'true' : 'false') . ")...\n";
        $count = Queue::workStopWhenEmpty('default', 3);
        echo "[" . date('Y-m-d H:i:s') . "] Processed {$count} jobs from queue.\n";
        break;

    case 'admin:create':
        $email = strtolower(trim($argv[2] ?? ''));
        $name = trim($argv[3] ?? 'Administrator');
        $password = trim($argv[4] ?? '');

        if (empty($email)) {
            echo "Usage: php artisan admin:create <email> [name] [password]\n";
            echo "Example: php artisan admin:create ayush@restlessdreamers.in Ayush CuratorAdmin2026!\n";
            exit(1);
        }

        if (empty($password)) {
            $password = 'CuratorAdmin' . bin2hex(random_bytes(3)) . '!';
        }

        if (strlen($password) < 12) {
            echo "Error: Password must be at least 12 characters (Argon2id).\n";
            exit(1);
        }

        $algo = defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_DEFAULT;
        $hash = password_hash($password, $algo);
        $totpSecret = TOTP::generateSecret();
        $recoveryCodes = TOTP::generateRecoveryCodes(8);

        $pdo = Database::getConnection();
        $existing = Database::fetch("SELECT id FROM users WHERE LOWER(email) = :email", ['email' => $email]);

        if ($existing) {
            Database::update('users', [
                'role' => 'admin',
                'name' => $name,
                'password_hash' => $hash,
                'totp_secret' => $totpSecret,
                'totp_enabled' => 1,
                'totp_recovery_codes' => json_encode($recoveryCodes),
                'updated_at' => date('Y-m-d H:i:s')
            ], 'id = :id', ['id' => $existing['id']]);
            echo "Successfully updated user #{$existing['id']} to Administrator.\n";
        } else {
            $id = Database::insert('users', [
                'email' => $email,
                'name' => $name,
                'role' => 'admin',
                'password_hash' => $hash,
                'totp_secret' => $totpSecret,
                'totp_enabled' => 1,
                'totp_recovery_codes' => json_encode($recoveryCodes),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            echo "Successfully created Administrator #{$id}.\n";
        }

        echo "\n--------------------------------------------------\n";
        echo "Email:       {$email}\n";
        echo "Password:    {$password}\n";
        echo "TOTP Secret: {$totpSecret}\n";
        echo "Recovery Codes:\n";
        foreach ($recoveryCodes as $code) {
            echo "  - {$code}\n";
        }
        echo "--------------------------------------------------\n";
        break;

    case 'admin:invite':
        $email = strtolower(trim($argv[2] ?? ''));
        $role = strtolower(trim($argv[3] ?? 'curator'));

        if (empty($email)) {
            echo "Usage: php artisan admin:invite <email> [role]\n";
            exit(1);
        }

        $token = bin2hex(random_bytes(24));
        $expires = date('Y-m-d H:i:s', time() + 172800); // 48 hours

        $id = Database::insert('admin_invitations', [
            'email' => $email,
            'role' => in_array($role, ['admin', 'curator']) ? $role : 'curator',
            'token' => $token,
            'expires_at' => $expires,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        $appUrl = defined('APP_URL') ? APP_URL : 'http://localhost:8000';
        echo "Invitation generated for {$email} ({$role}):\n";
        echo "{$appUrl}/login.html?invite={$token}\n";
        break;

    case 'migrate':
        echo "Initializing / upgrading schema...\n";
        $pdo = Database::getConnection();
        Schema::initSchema($pdo, 'sqlite');
        Schema::seedData($pdo);
        echo "Database schema up-to-date.\n";
        break;

    default:
        echo "Restless Dreamers - Weekend Sessions CLI Tool\n";
        echo "Available commands:\n";
        echo "  schedule:run                     Run scheduled queue & cleanup tasks (cron)\n";
        echo "  queue:work --stop-when-empty     Process pending database queue jobs and exit\n";
        echo "  admin:create <email> [name]      Create or promote an administrator account\n";
        echo "  admin:invite <email> [role]      Generate an invitation link for a curator\n";
        echo "  migrate                          Initialize database tables and schema\n";
        break;
}

