<?php
/**
 * License & Add-ons — Admin only.
 * Shows the current license (from license.json / remote server) and the
 * active/inactive status of every purchasable add-on module.
 * Admin can force-refresh the license cache from here.
 */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }
if (($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../dashboard.php?error=access_denied');
    exit;
}

require_once '../config.php';
require_once '../module_definitions.php';

$license        = checkLicense();
$active_modules = $license['modules'] ?? [];
$plan           = $license['plan']    ?? 'unknown';
$valid_until    = $license['valid_until'] ?? null;
$cached_at      = $license['cached_at']  ?? null;
$source         = $license['source']     ?? 'unknown';

// Collect purchasable add-on definitions
$addons = [];
foreach (EDUTRACK_MODULES as $key => $def) {
    if (empty($def['addon_key'])) continue;
    $addons[] = array_merge($def, [
        'module_key'  => $key,
        'is_active'   => in_array($key, $active_modules, true),
    ]);
}

$wa_number   = '233537793106';
$school_name = getSettingValue('school_name') ?: (defined('SITE_NAME') ? SITE_NAME : 'EduTrack School');

$plan_colors = [
    'starter' => '#6c757d',
    'growth'  => '#0d6efd',
    'premium' => '#6f42c1',
];
$plan_color = $plan_colors[$plan] ?? '#6c757d';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>License &amp; Add-ons — EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .addon-card {
            border: 1px solid #e5e7eb;
            border-radius: 14px;
            transition: box-shadow .18s;
        }
        .addon-card:hover { box-shadow: 0 4px 16px rgba(0,0,0,.09); }
        .addon-card.is-active  { border-color: #86efac; background: #f0fdf4; }
        .addon-card.is-locked  { background: #fafafa; }
        .addon-icon {
            width: 48px; height: 48px;
            border-radius: 11px;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.3rem;
            flex-shrink: 0;
        }
        .plan-badge {
            display: inline-flex; align-items: center; gap: .4rem;
            padding: .35rem .9rem; border-radius: 20px;
            font-weight: 700; font-size: .85rem; color: #fff;
        }
        .source-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
        .action-btn { min-width: 120px; }
    </style>
</head>
<body>
<div class="wrapper">
    <?= buildSidebar('admin/addons.php') ?>
    <div class="main-content">
        <?php if (function_exists('buildTopbar')) echo buildTopbar('License &amp; Add-ons'); ?>

        <div class="container-fluid py-4">

            <!-- Page header -->
            <div class="d-flex align-items-center gap-3 mb-4">
                <div style="background:linear-gradient(135deg,#6366f1,#8b5cf6);border-radius:12px;width:44px;height:44px;display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-certificate text-white"></i>
                </div>
                <div>
                    <h4 class="mb-0 fw-bold">License &amp; Add-ons</h4>
                    <p class="text-muted small mb-0">View your active modules and manage add-on licenses</p>
                </div>
            </div>

            <!-- License summary card -->
            <div class="card border-0 mb-4" style="border-radius:14px;background:linear-gradient(135deg,#1e1b4b,#312e81);">
                <div class="card-body p-4 text-white">
                    <div class="row align-items-center g-3">
                        <div class="col-auto">
                            <i class="fas fa-shield-alt fa-2x opacity-75"></i>
                        </div>
                        <div class="col">
                            <div class="d-flex align-items-center gap-2 mb-1">
                                <span class="plan-badge" style="background:<?= $plan_color ?>">
                                    <?= ucfirst($plan) ?> Plan
                                </span>
                                <?php if ($valid_until && $valid_until !== '2099-12-31'): ?>
                                    <span class="badge bg-white text-dark">
                                        Valid until <?= date('d M Y', strtotime($valid_until)) ?>
                                    </span>
                                <?php endif ?>
                            </div>
                            <div class="small opacity-75 d-flex align-items-center gap-2 flex-wrap">
                                <span>
                                    <span class="source-dot" style="background:<?= $source === 'server' ? '#4ade80' : '#fbbf24' ?>"></span>
                                    <?= $source === 'server' ? 'Live from license server' : ($source === 'default' ? 'Default (no server response)' : 'Cached data') ?>
                                </span>
                                <?php if ($cached_at): ?>
                                    &middot; Last updated <?= date('d M Y H:i', strtotime($cached_at)) ?>
                                <?php endif ?>
                                &middot; <?= count($active_modules) ?> modules active
                            </div>
                        </div>
                        <div class="col-auto">
                            <button class="btn btn-light btn-sm px-3" id="btnRefreshLicense">
                                <i class="fas fa-sync-alt me-1" id="refreshIcon"></i>Refresh License
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Add-ons grid -->
            <h6 class="fw-semibold text-muted mb-3 text-uppercase" style="letter-spacing:.05em;font-size:.75rem;">
                Purchasable Add-ons
            </h6>

            <div class="row g-3 mb-4">
            <?php
            $icon_bg = [
                'canteen_module'   => 'linear-gradient(135deg,#f97316,#ea580c)',
                'terminal_reports' => 'linear-gradient(135deg,#0ea5e9,#0284c7)',
                'exams'            => 'linear-gradient(135deg,#8b5cf6,#6d28d9)',
                'timetable'        => 'linear-gradient(135deg,#10b981,#059669)',
                'parent_portal'    => 'linear-gradient(135deg,#f59e0b,#d97706)',
                'online_payments'  => 'linear-gradient(135deg,#06b6d4,#0891b2)',
                'finance_suite'    => 'linear-gradient(135deg,#16a34a,#15803d)',
                'multi_calendar'   => 'linear-gradient(135deg,#0ea5e9,#0369a1)',
                'whatsapp_comms'   => 'linear-gradient(135deg,#25D366,#128C7E)',
                'student_activities' => 'linear-gradient(135deg,#7c3aed,#5b21b6)',
                'health_records'   => 'linear-gradient(135deg,#e11d48,#9f1239)',
                'payroll'          => 'linear-gradient(135deg,#0f766e,#115e59)',
                'biometric_attendance' => 'linear-gradient(135deg,#4338ca,#3730a3)',
                'ai_agent'         => 'linear-gradient(135deg,#ec4899,#be185d)',
                'ai_analytics'     => 'linear-gradient(135deg,#6366f1,#4f46e5)',
            ];
            foreach ($addons as $addon):
                $active   = $addon['is_active'];
                $ak       = htmlspecialchars($addon['addon_key']);
                $bg       = $icon_bg[$addon['addon_key']] ?? 'linear-gradient(135deg,#6b7280,#4b5563)';
                $wa_text  = "Hello! I'm using EduTrack ({$school_name}) and would like to activate the \"{$addon['label']}\" add-on. Please advise.";
                $wa_link  = "https://wa.me/{$wa_number}?text=" . rawurlencode($wa_text);
            ?>
            <div class="col-md-6 col-xl-4">
                <div class="addon-card p-4 h-100 d-flex flex-column gap-3 <?= $active ? 'is-active' : 'is-locked' ?>">
                    <div class="d-flex align-items-center gap-3">
                        <div class="addon-icon" style="background:<?= $bg ?>">
                            <i class="fas <?= htmlspecialchars($addon['icon']) ?> text-white"></i>
                        </div>
                        <div class="flex-grow-1">
                            <div class="d-flex align-items-center gap-2 flex-wrap">
                                <span class="fw-semibold"><?= htmlspecialchars($addon['label']) ?></span>
                                <?php if ($active): ?>
                                    <span class="badge bg-success">
                                        <i class="fas fa-check me-1"></i>Active
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">
                                        <i class="fas fa-lock me-1"></i>Not licensed
                                    </span>
                                <?php endif ?>
                            </div>
                            <div class="small text-muted mt-1">
                                GHS <?= number_format((float)$addon['addon_price'], 0) ?>/month
                                &middot; Plans: <?= implode(', ', array_map('ucfirst', $addon['plans'])) ?>
                            </div>
                        </div>
                    </div>

                    <div class="mt-auto d-flex gap-2 flex-wrap">
                    <?php if ($active): ?>
                        <a href="<?= rtrim(BASE_URL, '/') . '/' . htmlspecialchars($addon['path']) ?>"
                           class="btn btn-success btn-sm action-btn">
                            <i class="fas fa-arrow-right me-1"></i>Open Module
                        </a>
                        <a href="<?= $wa_link ?>" target="_blank"
                           class="btn btn-outline-secondary btn-sm action-btn">
                            <i class="fab fa-whatsapp me-1"></i>Manage
                        </a>
                    <?php else: ?>
                        <a href="<?= $wa_link ?>" target="_blank"
                           class="btn btn-primary btn-sm action-btn">
                            <i class="fab fa-whatsapp me-1"></i>Activate via ORIC
                        </a>
                        <a href="<?= rtrim(BASE_URL, '/') . '/upgrade.php?module=' . htmlspecialchars($addon['module_key']) ?>"
                           class="btn btn-outline-secondary btn-sm action-btn">
                            <i class="fas fa-info-circle me-1"></i>Learn More
                        </a>
                    <?php endif ?>
                    </div>
                </div>
            </div>
            <?php endforeach ?>
            </div>

            <!-- Contact footer -->
            <div class="card border-0" style="background:linear-gradient(135deg,#f0fdf4,#dcfce7);border-radius:14px;">
                <div class="card-body d-flex flex-wrap align-items-center gap-3 py-3">
                    <div class="flex-grow-1">
                        <strong>License changes take effect after a refresh.</strong>
                        <span class="text-muted ms-1 small">
                            ORIC Network activates and manages licenses remotely.
                            After ORIC confirms your payment, click <em>Refresh License</em> above to pull the updated license.
                        </span>
                    </div>
                    <a href="https://wa.me/<?= $wa_number ?>?text=<?= rawurlencode("Hello! I need help with my EduTrack license for {$school_name}.") ?>"
                       target="_blank" class="btn btn-success btn-sm px-3">
                        <i class="fab fa-whatsapp me-1"></i>WhatsApp ORIC
                    </a>
                    <a href="mailto:info@oricnetwork.com" class="btn btn-outline-secondary btn-sm px-3">
                        <i class="fas fa-envelope me-1"></i>Email ORIC
                    </a>
                </div>
            </div>

        </div><!-- /container -->
    </div><!-- /main-content -->
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('btnRefreshLicense').addEventListener('click', function () {
    const btn  = this;
    const icon = document.getElementById('refreshIcon');
    btn.disabled = true;
    icon.classList.add('fa-spin');

    fetch('../ajax/refresh_license.php', { method: 'POST' })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                // Reload to show fresh data
                window.location.reload();
            } else {
                alert('Could not refresh license: ' + (data.error || 'Unknown error'));
                btn.disabled = false;
                icon.classList.remove('fa-spin');
            }
        })
        .catch(() => {
            alert('Request failed. Check your internet connection and try again.');
            btn.disabled = false;
            icon.classList.remove('fa-spin');
        });
});
</script>
</body>
</html>
