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

declare(strict_types=1);

// PhaiERP command line:  php bin/phai <command>

use Phai\Core\App;
use Phai\Install\Demo;
use Phai\Install\InstallInput;
use Phai\Install\Installer;

if (PHP_SAPI !== 'cli') {
    exit(1);
}
require dirname(__DIR__) . '/src/bootstrap.php';
restore_error_handler();
restore_exception_handler();

$command = $argv[1] ?? 'help';

try {
    switch ($command) {
        case 'version':
            echo 'PhaiERP ', App::VERSION, "\n";
            break;

        case 'demo':
            if (!App::installed()) {
                throw new RuntimeException('Not installed yet: open the web installer first.');
            }
            Demo::load();
            echo "Sample data loaded.\n";
            break;

        case 'install':
            // install without the web wizard (Phai Server's first boot): php bin/phai install <setup.json> [app url]
            // The database is the one install.defaults.php names; the first user comes as a bcrypt hash.
            if (App::installed()) {
                throw new RuntimeException('Already installed.');
            }
            $setup = json_decode((string) @file_get_contents($argv[2] ?? ''), true);
            $company = is_array($setup['erp']['company'] ?? null) ? $setup['erp']['company'] : [];
            $admin = is_array($setup['erp']['admin'] ?? null) ? $setup['erp']['admin'] : [];
            if (!is_array($setup) || ($company['name'] ?? '') === '' || ($admin['userid'] ?? '') === ''
                || ($admin['name'] ?? '') === '' || ($admin['email'] ?? '') === '' || ($admin['password_hash'] ?? '') === '') {
                throw new RuntimeException('Usage: php bin/phai install <setup.json> [app url]  (erp.company.name, erp.admin.userid, name, email, password_hash; erp.demo loads the sample data)');
            }
            $d = Installer::defaults();
            $in = new InstallInput(
                db_host: $d['db_host'], db_port: $d['db_port'], db_name: $d['db_name'], db_user: $d['db_user'],
                db_pass: Installer::presetPassword(),
                co_name: (string) $company['name'],
                co_tax_id: ($company['tax_id'] ?? '') !== '' ? (string) $company['tax_id'] : null,
                co_phone: ($company['phone'] ?? '') !== '' ? (string) $company['phone'] : null,
                us_userid: (string) $admin['userid'], us_name: (string) $admin['name'],
                us_email: (string) $admin['email'],
                demo: ($setup['erp']['demo'] ?? false) === true,
            );
            $in->password_hash = (string) $admin['password_hash'];
            $result = Installer::install($in, $argv[3] ?? 'http://' . gethostname());
            echo "PhaiERP installed. Sign in as {$in->us_userid}.\n";
            // the installation stands even when the sample data could not be loaded
            if (isset($result['demo_error'])) {
                fwrite(STDERR, $result['demo_error'] . "\n");
            }
            break;

        case 'password':
            // forgotten password: set a new one from the server's own command line
            $userid = $argv[2] ?? '';
            $db = App::db();
            if ($userid === '' || !$db->value('SELECT 1 FROM us_mstr WHERE us_userid = ?', [$userid])) {
                throw new RuntimeException('Usage: php bin/phai password <user>  (users: '
                    . implode(', ', array_column($db->all('SELECT us_userid FROM us_mstr ORDER BY us_userid'), 'us_userid')) . ')');
            }
            echo "New password for $userid (at least 8 characters): ";
            $password = rtrim((string) fgets(STDIN), "\r\n");
            if (mb_strlen($password) < 8) {
                throw new RuntimeException('Password too short: nothing changed.');
            }
            $db->update('us_mstr', ['us_password_hash' => \Phai\Core\Auth\Auth::hash($password), 'updated_by' => 'cli'], ['us_userid' => $userid]);
            $db->run('DELETE FROM lg_hist WHERE lg_userid = ? AND lg_ok = 0', [$userid]);
            echo "Password changed. You can sign in as $userid now.\n";
            break;

        case 'esign-sync':
            // outside signers: push their steps to Phai Sign and pull results back (Phai Server runs this on a timer)
            if (!App::installed()) {
                throw new RuntimeException('Not installed yet.');
            }
            echo json_encode(\Phai\Modules\Esign\EnvelopeRemote::sync()), "\n";
            break;

        default:
            echo "PhaiERP ", App::VERSION, "\n\n",
                "  php bin/phai version              show the version\n",
                "  php bin/phai install <setup.json> install without the web wizard (see Phai Server)\n",
                "  php bin/phai password <user>      set a new password for a user (forgotten password)\n",
                "  php bin/phai esign-sync           send outside signers to Phai Sign and pull their results back\n",
                "  php bin/phai demo                 load sample data into an empty system (it stays: install again to start without it)\n";
    }
} catch (Throwable $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
}
