<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();

$pageLink = 'organization/terminal-license-activation.php';
$errors = [];
$flash = $_SESSION['flash_terminal_license'] ?? null;
unset($_SESSION['flash_terminal_license']);

function tla_stmt(mysqli $con, string $sql): mysqli_stmt
{
    $stmt = $con->prepare($sql);
    if (!$stmt) {
        throw new RuntimeException('Unable to prepare terminal license query.');
    }
    return $stmt;
}

function tla_col_exists(mysqli $con, string $table, string $column): bool
{
    $stmt = tla_stmt($con, 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?');
    $stmt->bind_param('ss', $table, $column);
    $stmt->execute();
    $exists = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0) > 0;
    $stmt->close();
    return $exists;
}

function tla_table_exists(mysqli $con, string $table): bool
{
    $stmt = tla_stmt($con, 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?');
    $stmt->bind_param('s', $table);
    $stmt->execute();
    $exists = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0) > 0;
    $stmt->close();
    return $exists;
}

function tla_ensure_menu(mysqli $con): void
{
    foreach ([
        'parent_id' => 'INT UNSIGNED NOT NULL DEFAULT 0',
        'show_in_menu' => 'TINYINT(1) NOT NULL DEFAULT 1',
        'url' => 'VARCHAR(255) NULL',
        'section' => 'VARCHAR(100) NULL',
        'sort_order' => 'INT NOT NULL DEFAULT 0',
    ] as $column => $definition) {
        if (!tla_col_exists($con, 'jos_admin_menus', $column)) {
            $con->query('ALTER TABLE jos_admin_menus ADD COLUMN `' . $column . '` ' . $definition);
        }
    }

    $parentId = 0;
    $stmt = tla_stmt($con, "SELECT id FROM jos_admin_menus WHERE menu_link='#organisation-settings' OR url='#organisation-settings' OR menu_name IN ('Organisation Settings','Organization Settings') ORDER BY id ASC LIMIT 1");
    $stmt->execute();
    $parent = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($parent) {
        $parentId = (int)$parent['id'];
        $stmt = tla_stmt($con, "UPDATE jos_admin_menus SET menu_name='Organisation Settings', menu_link='#organisation-settings', url='#organisation-settings', section='D. Masters', icon='fa-solid fa-building', remarks='Company and organisation masters', status=1, show_in_menu=1, can_view=1, sort_order=115, orderby=115 WHERE id=?");
        $stmt->bind_param('i', $parentId);
        $stmt->execute();
        $stmt->close();
    } else {
        $stmt = tla_stmt($con, "INSERT INTO jos_admin_menus (menu_name,menu_link,parent_id,icon,orderby,status,show_in_menu,can_view,remarks,url,section,sort_order) VALUES ('Organisation Settings','#organisation-settings',0,'fa-solid fa-building',115,1,1,1,'Company and organisation masters','#organisation-settings','D. Masters',115)");
        $stmt->execute();
        $parentId = (int)$con->insert_id;
        $stmt->close();
    }

    $link = $GLOBALS['pageLink'];
    $stmt = tla_stmt($con, 'SELECT id FROM jos_admin_menus WHERE menu_link=? OR url=? ORDER BY id ASC LIMIT 1');
    $stmt->bind_param('ss', $link, $link);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($row) {
        $menuId = (int)$row['id'];
        $stmt = tla_stmt($con, "UPDATE jos_admin_menus SET menu_name='Terminal License Activation', parent_id=?, menu_link=?, url=?, icon='fa-solid fa-key', remarks='Activate and manage terminal license keys.', section='Organisation Settings', status=1, show_in_menu=1, can_view=1, sort_order=119, orderby=119 WHERE id=?");
        $stmt->bind_param('issi', $parentId, $link, $link, $menuId);
        $stmt->execute();
        $stmt->close();
    } else {
        $stmt = tla_stmt($con, "INSERT INTO jos_admin_menus (menu_name,menu_link,parent_id,icon,orderby,status,show_in_menu,can_view,remarks,url,section,sort_order) VALUES ('Terminal License Activation',?,?,'fa-solid fa-key',119,1,1,1,'Activate and manage terminal license keys.',?,'Organisation Settings',119)");
        $stmt->bind_param('sis', $link, $parentId, $link);
        $stmt->execute();
        $menuId = (int)$con->insert_id;
        $stmt->close();
    }

    $roleIds = [1];
    if (tla_table_exists($con, 'jos_admin_roles')) {
        $roleNameColumn = tla_col_exists($con, 'jos_admin_roles', 'role_name') ? 'role_name' : (tla_col_exists($con, 'jos_admin_roles', 'name') ? 'name' : '');
        if ($roleNameColumn !== '') {
            $stmt = tla_stmt($con, "SELECT id FROM jos_admin_roles WHERE status=1 AND (id=1 OR LOWER(`$roleNameColumn`) IN ('administrator','admin','super admin'))");
            $stmt->execute();
            $result = $stmt->get_result();
            while ($role = $result->fetch_assoc()) {
                $roleIds[] = (int)$role['id'];
            }
            $stmt->close();
        }
    }

    foreach (array_values(array_unique($roleIds)) as $roleId) {
        $stmt = tla_stmt($con, 'SELECT id FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1');
        $stmt->bind_param('ii', $roleId, $menuId);
        $stmt->execute();
        $existing = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($existing) {
            $id = (int)$existing['id'];
            $stmt = tla_stmt($con, 'UPDATE jos_admin_rolemenus SET can_view=1, can_add=1, can_edit=1, can_delete=1, status=1 WHERE id=?');
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();
        } else {
            $stmt = tla_stmt($con, 'INSERT INTO jos_admin_rolemenus (role_id, menu_id, can_view, can_add, can_edit, can_delete, status) VALUES (?, ?, 1, 1, 1, 1, 1)');
            $stmt->bind_param('ii', $roleId, $menuId);
            $stmt->execute();
            $stmt->close();
        }
    }
}

function tla_text(array $row, string $key, string $default = ''): string
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (string)$row[$key] : $default;
}

function tla_int(array $row, string $key, int $default = 0): int
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (int)$row[$key] : $default;
}

function tla_options(mysqli $con, string $sql): array
{
    $rows = [];
    $result = $con->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        $result->free();
    }
    return $rows;
}

function tla_terminal_exists(mysqli $con, int $id): bool
{
    if ($id <= 0) {
        return false;
    }
    $stmt = tla_stmt($con, 'SELECT id FROM jos_app_orglocation WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function tla_existing_license_id(mysqli $con, int $terminalId): int
{
    $stmt = tla_stmt($con, 'SELECT id FROM jos_app_license_key WHERE orglocation=? ORDER BY id ASC LIMIT 1');
    $stmt->bind_param('i', $terminalId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ? (int)$row['id'] : 0;
}

function tla_save(mysqli $con, int $terminalId, string $licenseKey): void
{
    $existingId = tla_existing_license_id($con, $terminalId);
    if ($existingId > 0) {
        $stmt = tla_stmt($con, 'UPDATE jos_app_license_key SET `date`=NOW(), license_key=?, status=1 WHERE id=?');
        $stmt->bind_param('si', $licenseKey, $existingId);
    } else {
        $stmt = tla_stmt($con, 'INSERT INTO jos_app_license_key (`date`, orglocation, license_key, status) VALUES (NOW(), ?, ?, 1)');
        $stmt->bind_param('is', $terminalId, $licenseKey);
    }
    $stmt->execute();
    $stmt->close();
}

try {
    tla_ensure_menu($con);
} catch (Throwable $e) {
    $errors[] = 'Terminal License Activation menu setup could not be completed.';
}

$acl = require_acl('can_view', $pageLink);
$mode = (string)($_GET['mode'] ?? '');
$showForm = $mode === 'add';
$formValues = [
    'orglocation' => 0,
    'license_key' => '',
];

if ($showForm && empty($acl['can_add']) && empty($acl['can_edit'])) {
    http_response_code(403);
    exit('Access denied.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'save') {
        if (empty($acl['can_add']) && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to add terminal licenses.';
        }

        $terminalId = max(0, (int)($_POST['orglocation'] ?? 0));
        $licenseKey = trim((string)($_POST['license_key'] ?? ''));

        if ($terminalId <= 0 || !tla_terminal_exists($con, $terminalId)) {
            $errors[] = 'Orgnisation Location is required.';
        }
        if ($licenseKey === '') {
            $errors[] = 'License Key is required.';
        } elseif (strlen($licenseKey) > 250) {
            $errors[] = 'License Key must be 250 characters or fewer.';
        } elseif (preg_match('/[\x00-\x1F\x7F]/', $licenseKey) || strpos($licenseKey, '<') !== false || strpos($licenseKey, '>') !== false) {
            $errors[] = 'License Key contains invalid characters.';
        }

        $formValues = [
            'orglocation' => $terminalId,
            'license_key' => $licenseKey,
        ];

        if (!$errors) {
            try {
                $con->begin_transaction();
                tla_save($con, $terminalId, $licenseKey);
                $con->commit();
                $_SESSION['flash_terminal_license'] = 'Terminal License Activation saved successfully.';
                redirect('/organization/terminal-license-activation.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save terminal license. No changes were committed.';
            }
        }
        $showForm = true;
    }
}

$rows = [];
$stmt = tla_stmt($con, 'SELECT lk.id, lk.orglocation, lk.license_key, ol.name AS organisation_name FROM jos_app_license_key lk LEFT JOIN jos_app_orglocation ol ON ol.id=lk.orglocation ORDER BY lk.id ASC');
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}
$stmt->close();

$terminals = tla_options($con, 'SELECT id, name FROM jos_app_orglocation ORDER BY name ASC, id ASC');
$value = static function (string $key, $default = '') use (&$formValues) {
    return $formValues[$key] ?? $default;
};
$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';

console_header('Terminal License Activation', $pageLink);
?>
<div class="mb-6">
  <div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>D. Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Organisation Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Terminal License Activation</span></div>
  <h1 class="text-2xl font-bold text-slate-900">Terminal License Activation</h1>
  <p class="mt-1 text-sm text-slate-500">Activate and manage license keys for terminal locations.</p>
</div>

<?php if ($flash): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($flash) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><div class="font-bold">Please fix the following</div><ul class="mt-2 list-inside list-disc"><?php foreach ($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<?php if ($showForm): ?>
<form method="post">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save">
  <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
    <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
      <div class="flex items-center gap-3">
        <span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="fa-solid fa-key"></i></span>
        <div>
        <h2 class="text-lg font-bold text-slate-800">Terminal License Activation</h2>
        <p class="mt-1 text-sm font-medium text-slate-400">License key is saved against the selected organisation location.</p>
        </div>
      </div>
      <a href="/organization/terminal-license-activation.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a>
    </div>
    <div class="grid gap-x-6 gap-y-5 p-5 md:grid-cols-2">
      <label class="text-sm font-bold text-slate-700">Orgnisation Location<select name="orglocation" required class="<?= $input ?>"><option value="">-Select Location-</option><?php foreach ($terminals as $terminal): ?><option value="<?= (int)$terminal['id'] ?>" <?= (int)$value('orglocation') === (int)$terminal['id'] ? 'selected' : '' ?>><?= h((string)$terminal['name']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-bold text-slate-700">License Key<input type="text" name="license_key" required maxlength="250" value="<?= h((string)$value('license_key')) ?>" class="<?= $input ?>" placeholder="License Key"></label>
    </div>
    <div class="flex justify-center gap-3 px-5 pb-5"><button class="rounded-lg bg-brand-600 px-8 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Submit</button><a href="/organization/terminal-license-activation.php" class="rounded-lg border border-slate-200 bg-white px-8 py-2.5 text-sm font-bold text-slate-600 hover:bg-slate-50">Cancel</a></div>
  </section>
</form>
<?php else: ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
    <div>
      <h2 class="text-lg font-bold text-slate-800">Terminal Activation Key List</h2>
      <p class="mt-1 text-sm font-medium text-slate-400">Activation keys are shown in the same columns as the old page.</p>
    </div>
    <?php if (!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>Add</a><?php endif; ?>
  </div>
  <div class="overflow-x-auto"><table class="w-full min-w-[760px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600"><tr><th class="px-5 py-4">Sr No</th><th class="px-5 py-4">Organisations</th><th class="px-5 py-4">Activation Keys</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if (!$rows): ?><tr><td colspan="3" class="px-6 py-14 text-center font-semibold text-slate-400">&nbsp;</td></tr><?php endif; ?>
    <?php foreach ($rows as $index => $row): ?>
      <tr class="align-top hover:bg-slate-50/70">
        <td class="px-5 py-5 font-semibold text-slate-500"><?= $index + 1 ?></td>
        <td class="px-5 py-5 font-bold text-slate-800"><?= h(tla_text($row, 'organisation_name', 'Terminal #' . tla_int($row, 'orglocation'))) ?></td>
        <td class="px-5 py-5 break-all font-mono text-sm font-semibold text-slate-700"><?= h(tla_text($row, 'license_key', '-')) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody></table></div>
</section>
<?php endif; ?>
<?php console_footer(); ?>
