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

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

$pageLink = 'organization/employee-count.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_employee_count'] ?? null;
unset($_SESSION['flash_employee_count']);

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

function empc_table_exists(mysqli $con, string $table): bool
{
    $stmt = empc_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 empc_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) {
        return $cache[$table];
    }
    $safeTable = preg_replace('/[^A-Za-z0-9_]/', '', $table);
    $columns = [];
    $result = $con->query('SHOW COLUMNS FROM `' . $safeTable . '`');
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $columns[] = (string)$row['Field'];
        }
        $result->free();
    }
    $cache[$table] = $columns;
    return $columns;
}

function empc_has(array $columns, string $column): bool
{
    return in_array($column, $columns, true);
}

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

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

function empc_current_user_id(): int
{
    $user = current_user() ?: [];
    foreach (['id', 'user_id', 'admin_id'] as $key) {
        if (!empty($user[$key])) {
            return (int)$user[$key];
        }
    }
    return 0;
}

function empc_clean_int(string $label, $value, array &$errors): int
{
    $text = trim((string)$value);
    if ($text === '' || !preg_match('/^\d+$/', $text)) {
        $errors[] = $label . ' must be a whole number.';
        return 0;
    }
    $number = (int)$text;
    if ($number < 0 || $number > 999999) {
        $errors[] = $label . ' must be between 0 and 999999.';
    }
    return $number;
}

function empc_latest_totals(mysqli $con): array
{
    $stmt = empc_stmt($con, 'SELECT total, total_tracking FROM jos_emp_license_log ORDER BY id DESC LIMIT 1');
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: [];
    $stmt->close();
    return [
        'total' => empc_int($row, 'total'),
        'total_tracking' => empc_int($row, 'total_tracking'),
    ];
}

function empc_fetch_logs(mysqli $con): array
{
    $stmt = empc_stmt($con, 'SELECT id, employee_count, total, live_tracking_count, total_tracking, approved_by FROM jos_emp_license_log ORDER BY id DESC LIMIT 100');
    $stmt->execute();
    $rows = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

if (!empc_table_exists($con, 'jos_emp_license_log')) {
    console_header('Employee License Activation', $pageLink);
    echo '<div class="rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700">Employee License Activation table is not available.</div>';
    console_footer();
    exit;
}

$licenseColumns = empc_columns($con, 'jos_emp_license_log');
foreach (['id', 'userid', 'date', 'employee_count', 'total', 'live_tracking_count', 'total_tracking', 'approved_by'] as $requiredColumn) {
    if (!empc_has($licenseColumns, $requiredColumn)) {
        console_header('Employee License Activation', $pageLink);
        echo '<div class="rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700">Required Employee License Activation column is missing: ' . h($requiredColumn) . '.</div>';
        console_footer();
        exit;
    }
}

$mode = (string)($_GET['mode'] ?? 'list');
$isForm = $mode === 'add';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Session expired. Please try again.';
    }
    if (empty($acl['can_add'])) {
        $errors[] = 'You do not have permission to save Employee License Activation.';
    }

    $employeeCount = empc_clean_int('Employee License Count', $_POST['employee_count'] ?? '', $errors);
    $liveTrackingCount = empc_clean_int('Live Tracking Count', $_POST['live_tracking_count'] ?? '', $errors);
    $approvedBy = trim((string)($_POST['approved_by'] ?? ''));
    if ($approvedBy === '') {
        $errors[] = 'Approved By is required.';
    } elseif (strlen($approvedBy) > 150) {
        $errors[] = 'Approved By must be 150 characters or fewer.';
    }

    if (!$errors) {
        $latest = empc_latest_totals($con);
        $total = (int)$latest['total'] + $employeeCount;
        $totalTracking = (int)$latest['total_tracking'] + $liveTrackingCount;
        $userId = empc_current_user_id();
        $today = date('Y-m-d');

        $stmt = empc_stmt($con, 'INSERT INTO jos_emp_license_log (userid, date, employee_count, total, live_tracking_count, total_tracking, approved_by) VALUES (?, ?, ?, ?, ?, ?, ?)');
        $stmt->bind_param('isiiiis', $userId, $today, $employeeCount, $total, $liveTrackingCount, $totalTracking, $approvedBy);
        $stmt->execute();
        $stmt->close();

        $_SESSION['flash_employee_count'] = 'Employee License Activation added successfully.';
        redirect('/' . $pageLink);
    }
    $isForm = true;
}

$logs = empc_fetch_logs($con);
$input = 'mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700 outline-none transition focus:border-brand-500 focus:ring-4 focus:ring-brand-100';

console_header('Employee License Activation', $pageLink);
?>
<section 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">Employee Count</span>
  </div>
  <h1 class="text-2xl font-bold text-slate-900">Employee License Activation</h1>
  <p class="mt-2 text-sm font-medium text-slate-500">Manage employee license count and live tracking activations.</p>
</section>

<?php if ($flash): ?>
  <div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-bold 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-bold text-red-700"><?= h(implode(' ', $errors)) ?></div>
<?php endif; ?>

<?php if ($isForm): ?>
<form method="post" class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
  <div class="flex flex-col gap-4 border-b border-slate-100 px-5 py-5 md:flex-row md:items-center md:justify-between">
    <div class="flex items-center gap-4">
      <span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="fa-solid fa-id-card"></i></span>
      <div>
        <h2 class="text-lg font-bold text-slate-800">New Employee License Activation</h2>
        <p class="mt-1 text-sm font-medium text-slate-400">Fields marked with * are required.</p>
      </div>
    </div>
    <a href="/<?= h($pageLink) ?>" class="inline-flex items-center justify-center rounded-xl border border-slate-200 px-5 py-3 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-5 p-5 md:grid-cols-3">
    <label class="text-sm font-bold text-slate-700">Employee License Count *
      <input type="number" min="0" max="999999" name="employee_count" required value="<?= h((string)($_POST['employee_count'] ?? '')) ?>" class="<?= $input ?>">
    </label>
    <label class="text-sm font-bold text-slate-700">Live Tracking Count *
      <input type="number" min="0" max="999999" name="live_tracking_count" required value="<?= h((string)($_POST['live_tracking_count'] ?? '')) ?>" class="<?= $input ?>">
    </label>
    <label class="text-sm font-bold text-slate-700">Approved By *
      <input type="text" maxlength="150" name="approved_by" required value="<?= h((string)($_POST['approved_by'] ?? '')) ?>" class="<?= $input ?>">
    </label>
  </div>
  <div class="flex justify-center gap-3 px-5 pb-6">
    <button type="submit" class="rounded-xl bg-brand-600 px-8 py-3 text-sm font-bold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50" <?= empty($acl['can_add']) ? 'disabled' : '' ?>><i class="fa-solid fa-floppy-disk mr-2"></i>Submit</button>
    <a href="/<?= h($pageLink) ?>" class="rounded-xl border border-slate-200 px-8 py-3 text-sm font-bold text-slate-600 hover:bg-slate-50">Cancel</a>
  </div>
</form>
<?php else: ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-4 border-b border-slate-100 p-5 md:flex-row md:items-center md:justify-between">
    <div>
      <h2 class="text-lg font-bold text-slate-800">Employee License Activation List</h2>
      <p class="mt-1 text-sm font-medium text-slate-400">License activation records are ordered by latest record.</p>
    </div>
    <?php if (!empty($acl['can_add'])): ?>
      <a href="/<?= h($pageLink) ?>?mode=add" class="inline-flex items-center justify-center rounded-xl bg-brand-600 px-5 py-3 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus mr-2"></i>Add</a>
    <?php endif; ?>
  </div>
  <div class="overflow-x-auto">
    <table class="w-full min-w-[980px] text-left text-sm">
      <thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600">
        <tr>
          <th class="w-20 px-5 py-4">Sr No</th>
          <th class="px-5 py-4">Employee License Count</th>
          <th class="px-5 py-4">Total License Count</th>
          <th class="px-5 py-4">Live Tracking Count</th>
          <th class="px-5 py-4">Total Tracking Count</th>
          <th class="px-5 py-4">Approved By</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
      <?php if (!$logs): ?>
        <tr><td colspan="6" class="px-5 py-16 text-center text-sm font-bold text-slate-400">No employee license activations found.</td></tr>
      <?php else: foreach ($logs as $index => $row): ?>
        <tr class="align-top hover:bg-slate-50/70">
          <td class="px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td>
          <td class="px-5 py-4 font-semibold text-slate-700"><?= empc_int($row, 'employee_count') ?></td>
          <td class="px-5 py-4 font-semibold text-slate-700"><?= empc_int($row, 'total') ?></td>
          <td class="px-5 py-4 font-semibold text-slate-700"><?= empc_int($row, 'live_tracking_count') ?></td>
          <td class="px-5 py-4 font-semibold text-slate-700"><?= empc_int($row, 'total_tracking') ?></td>
          <td class="px-5 py-4 font-semibold text-slate-700"><?= h(empc_text($row, 'approved_by', '-')) ?></td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</section>
<?php endif; ?>
<?php
console_footer();
