<?php
// admin/packages.php
session_start();
include '../config.php';
include 'auth_check.php';

// Handle Actions
$message = '';
$error = '';

if (isset($_GET['msg'])) {
    $message = htmlspecialchars($_GET['msg']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add') {
            $name = $_POST['name'];
            $price = $_POST['price'];
            $tokens = $_POST['token_amount'];
            $desc = $_POST['description'];
            $featured = isset($_POST['is_featured']) ? 1 : 0;
            $duration = $_POST['duration_days'] ?? 365;

            $stmt = $conn->prepare("INSERT INTO subscription_packages (name, price, token_amount, description, is_featured, duration_days) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sdiisi", $name, $price, $tokens, $desc, $featured, $duration);
            if ($stmt->execute()) {
                $message = "Package '$name' added successfully.";
            } else {
                $error = "Error adding package: " . $conn->error;
            }
        } elseif ($_POST['action'] === 'delete') {
            $id = intval($_POST['package_id']);
            $conn->query("UPDATE subscription_packages SET is_active = 0 WHERE id = $id");
            $message = "Package deactivated.";
        } elseif ($_POST['action'] === 'activate') {
            $id = intval($_POST['package_id']);
            $conn->query("UPDATE subscription_packages SET is_active = 1 WHERE id = $id");
            $message = "Package reactivated.";
        } elseif ($_POST['action'] === 'toggle_featured') {
            $id = intval($_POST['package_id']);
            $conn->query("UPDATE subscription_packages SET is_featured = NOT is_featured WHERE id = $id");
            $message = "Featured status toggled.";
        } elseif ($_POST['action'] === 'edit') {
            $id = intval($_POST['package_id']);
            $name = $_POST['name'];
            $price = $_POST['price'];
            $tokens = $_POST['token_amount'];
            $desc = $_POST['description'];
            $featured = isset($_POST['is_featured']) ? 1 : 0;
            $duration = $_POST['duration_days'] ?? 365;

            $stmt = $conn->prepare("UPDATE subscription_packages SET name=?, price=?, token_amount=?, description=?, is_featured=?, duration_days=? WHERE id=?");
            $stmt->bind_param("sdiisii", $name, $price, $tokens, $desc, $featured, $duration, $id);
            if ($stmt->execute()) {
                $message = "Package '$name' updated successfully.";
            } else {
                $error = "Error updating package: " . $conn->error;
            }
        } elseif ($_POST['action'] === 'update_settings') {
            if (isset($_POST['settings']) && is_array($_POST['settings'])) {
                foreach ($_POST['settings'] as $key => $val) {
                    $key = $conn->real_escape_string($key);
                    $val = $conn->real_escape_string($val);
                    $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('$key', '$val') ON DUPLICATE KEY UPDATE setting_value = '$val'");
                }
                header("Location: packages.php?msg=" . urlencode("Token pricing rules updated successfully."));
                exit;
            }
        }
    }
}

// Get Statistics
$stats = [
    'total_packages' => 0,
    'active_packages' => 0,
    'active_subscribers' => 0,
    'revenue_earned' => 0
];

$stats_result = $conn->query("SELECT 
    COUNT(*) as total_packages,
    SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_packages
FROM subscription_packages");
if ($row = $stats_result->fetch_assoc()) {
    $stats['total_packages'] = $row['total_packages'];
    $stats['active_packages'] = $row['active_packages'];
}

// Active subscribers count
$sub_result = $conn->query("SELECT COUNT(DISTINCT user_id) as active_subscribers FROM user_subscriptions WHERE status = 'active'");
if ($sub_row = $sub_result->fetch_assoc()) {
    $stats['active_subscribers'] = $sub_row['active_subscribers'] ?? 0;
}

// Actual revenue from approved orders
$rev_result = $conn->query("SELECT COALESCE(SUM(amount_paid), 0) as revenue_earned FROM token_orders WHERE status = 'approved'");
if ($rev_row = $rev_result->fetch_assoc()) {
    $stats['revenue_earned'] = $rev_row['revenue_earned'];
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Manage Packages - SaniBook Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        body {
            font-family: 'Inter', system-ui, sans-serif;
        }
    </style>
</head>

<body class="bg-gradient-to-br from-slate-50 to-blue-50/30 min-h-screen">
    <?php include 'navbar.php'; ?>

    <div class="max-w-7xl mx-auto p-6">
        <!-- Header -->
        <div class="flex justify-between items-center mb-8">
            <div>
                <h2 class="text-2xl font-bold text-slate-900 flex items-center gap-3">
                    <i class="fa-solid fa-box-open text-blue-600"></i> Subscription Packages
                </h2>
                <p class="text-slate-600 mt-1">Manage pricing tiers and offerings</p>
            </div>
            <button onclick="document.getElementById('addPackageModal').classList.remove('hidden')"
                class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-bold transition-all shadow-lg hover:shadow-xl flex items-center gap-2">
                <i class="fa-solid fa-plus"></i> New Package
            </button>
        </div>

        <?php if ($message): ?>
            <div
                class="bg-green-50 border-l-4 border-green-500 text-green-800 p-4 rounded-lg mb-6 flex items-center gap-3 shadow-sm">
                <i class="fa-solid fa-check-circle text-2xl"></i>
                <span class="font-medium"><?= htmlspecialchars($message) ?></span>
            </div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div
                class="bg-red-50 border-l-4 border-red-500 text-red-800 p-4 rounded-lg mb-6 flex items-center gap-3 shadow-sm">
                <i class="fa-solid fa-exclamation-triangle text-2xl"></i>
                <span class="font-medium"><?= htmlspecialchars($error) ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistics Panel -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-blue-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-sm font-semibold uppercase tracking-wide">Total Packages</p>
                        <p class="text-2xl font-bold text-slate-900 mt-2"><?= $stats['total_packages'] ?></p>
                    </div>
                    <i class="fa-solid fa-boxes-stacked text-4xl text-blue-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-sm font-semibold uppercase tracking-wide">Active</p>
                        <p class="text-2xl font-bold text-slate-900 mt-2"><?= $stats['active_packages'] ?></p>
                    </div>
                    <i class="fa-solid fa-circle-check text-4xl text-green-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-yellow-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-sm font-semibold uppercase tracking-wide">Active Subscribers</p>
                        <p class="text-2xl font-bold text-slate-900 mt-2">
                            <?= number_format(floatval($stats['active_subscribers'] ?? 0)) ?>
                        </p>
                    </div>
                    <i class="fa-solid fa-users text-4xl text-yellow-500 opacity-20"></i>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-cyan-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-sm font-semibold uppercase tracking-wide">Revenue Earned</p>
                        <p class="text-2xl font-bold text-slate-900 mt-2">KES
                            <?= number_format(floatval($stats['revenue_earned'] ?? 0)) ?>
                        </p>
                    </div>
                    <i class="fa-solid fa-coins text-4xl text-cyan-500 opacity-20"></i>
                </div>
            </div>
        </div>

        <!-- Token Pricing Configurations -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-8 border border-slate-200">
            <h3 class="text-xl font-bold text-slate-800 border-b border-slate-100 pb-4 mb-6">Token Pricing Rules</h3>
            <form method="POST" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <input type="hidden" name="action" value="update_settings">

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Base Token Value (KES)</label>
                    <input type="number" step="0.01" name="settings[token_cost_base_value]"
                        value="<?= COST_BASE_VALUE ?>" class="w-full border-2 border-slate-300 rounded-lg p-3">
                    <p class="text-xs text-slate-500 mt-1">Value of 1 token for "Need More Tokens" calc.</p>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Cost Per Character</label>
                    <input type="number" step="0.01" name="settings[token_cost_per_char]" value="<?= COST_PER_CHAR ?>"
                        class="w-full border-2 border-slate-300 rounded-lg p-3">
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Cost Per Image</label>
                    <input type="number" name="settings[token_cost_per_image]" value="<?= COST_PER_IMAGE ?>"
                        class="w-full border-2 border-slate-300 rounded-lg p-3">
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Cost Per Sec (Video)</label>
                    <input type="number" name="settings[token_cost_per_video_sec]" value="<?= COST_PER_VIDEO_SEC ?>"
                        class="w-full border-2 border-slate-300 rounded-lg p-3">
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Cost Per Sec (Audio)</label>
                    <input type="number" name="settings[token_cost_per_audio_sec]" value="<?= COST_PER_AUDIO_SEC ?>"
                        class="w-full border-2 border-slate-300 rounded-lg p-3">
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Extra Category Cost</label>
                    <input type="number" name="settings[token_cost_per_extra_category]"
                        value="<?= COST_PER_EXTRA_CATEGORY ?>" class="w-full border-2 border-slate-300 rounded-lg p-3">
                    <p class="text-xs text-slate-500 mt-1">Applied per extra selected category/chain/pillar.</p>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Edit Submission Cost</label>
                    <input type="number" name="settings[token_cost_editing]" value="<?= COST_EDITING ?>"
                        class="w-full border-2 border-slate-300 rounded-lg p-3">
                    <p class="text-xs text-slate-500 mt-1">Fixed additional token cost when users edit a submission
                        (Drafts not charged).</p>
                </div>

                <div class="lg:col-span-2 flex items-end">
                    <button type="submit"
                        class="px-6 py-3 bg-slate-800 text-white rounded-lg font-bold hover:bg-slate-900 transition-colors h-[50px] flex items-center">
                        <i class="fa-solid fa-save mr-2"></i> Save Pricing Rules
                    </button>
                </div>
            </form>
        </div>

        <!-- Packages Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php
            $result = $conn->query("SELECT * FROM subscription_packages ORDER BY is_active DESC, price ASC");
            while ($pkg = $result->fetch_assoc()):
                $isActive = $pkg['is_active'];
                $isFeatured = $pkg['is_featured'];
                $borderClass = $isFeatured ? 'border-yellow-400' : ($isActive ? 'border-slate-200' : 'border-red-200');
                ?>
                <div
                    class="bg-white rounded-xl shadow-lg border-2 <?= $borderClass ?> p-6 relative overflow-hidden transition-all hover:shadow-2xl <?= !$isActive ? 'opacity-60' : '' ?>">

                    <!-- Status Badges -->
                    <div class="absolute top-3 right-3 flex gap-2">
                        <?php if ($isFeatured): ?>
                            <span
                                class="bg-gradient-to-r from-yellow-400 to-yellow-600 text-white text-xs font-black px-3 py-1 rounded-full shadow-md uppercase">
                                <i class="fa-solid fa-star"></i> Featured
                            </span>
                        <?php endif; ?>
                        <?php if (!$isActive): ?>
                            <span class="bg-red-500 text-white text-xs font-bold px-3 py-1 rounded-full">Inactive</span>
                        <?php endif; ?>
                    </div>

                    <!-- Package Content -->
                    <div class="mt-8">
                        <h3 class="font-bold text-2xl text-slate-900 mb-2 uppercase tracking-wide">
                            <?= htmlspecialchars($pkg['name']) ?>
                        </h3>

                        <div class="flex items-baseline gap-2 mb-4">
                            <span class="text-4xl font-extrabold text-blue-600">
                                <?= $pkg['price'] == 0 ? 'FREE' : 'KES ' . number_format($pkg['price']) ?>
                            </span>
                        </div>

                        <!-- Token Badge -->
                        <div class="inline-flex items-center gap-2 bg-blue-50 px-4 py-2 rounded-lg mb-4">
                            <i class="fa-solid fa-coins text-blue-600"></i>
                            <span class="text-sm font-bold text-blue-900">
                                <?= number_format($pkg['token_amount']) ?> Tokens
                            </span>
                        </div>

                        <!-- Metadata -->
                        <div class="grid grid-cols-2 gap-3 mb-4 text-xs text-slate-600">
                            <div class="flex items-center gap-2">
                                <i class="fa-solid fa-calendar text-slate-400"></i>
                                <span><?= $pkg['duration_days'] ?? 365 ?> days</span>
                            </div>
                            <div class="flex items-center gap-2">
                                <i class="fa-solid fa-calculator text-slate-400"></i>
                                <span><?= $pkg['token_amount'] > 0 ? number_format($pkg['price'] / $pkg['token_amount'], 2) : '0' ?>
                                    KES/token</span>
                            </div>
                        </div>

                        <!-- Description -->
                        <p class="text-slate-600 text-sm leading-relaxed mb-6 min-h-[60px] border-t border-slate-100 pt-4">
                            <?= nl2br(htmlspecialchars($pkg['description'])) ?>
                        </p>

                        <!-- Actions -->
                        <div class="flex gap-2 flex-wrap">
                            <form method="POST" class="flex-1">
                                <input type="hidden" name="package_id" value="<?= $pkg['id'] ?>">
                                <?php if ($isActive): ?>
                                    <input type="hidden" name="action" value="delete">
                                    <button
                                        class="w-full px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 text-sm font-semibold transition-colors">
                                        <i class="fa-solid fa-ban mr-1"></i> Deactivate
                                    </button>
                                <?php else: ?>
                                    <input type="hidden" name="action" value="activate">
                                    <button
                                        class="w-full px-4 py-2 bg-green-50 text-green-600 rounded-lg hover:bg-green-100 text-sm font-semibold transition-colors">
                                        <i class="fa-solid fa-circle-check mr-1"></i> Activate
                                    </button>
                                <?php endif; ?>
                            </form>

                            <form method="POST" class="flex-1">
                                <input type="hidden" name="package_id" value="<?= $pkg['id'] ?>">
                                <button
                                    class="w-full px-4 py-2 <?= $isFeatured ? 'bg-yellow-100 text-yellow-700' : 'bg-slate-100 text-slate-600' ?> rounded-lg hover:bg-yellow-50 text-sm font-semibold transition-colors">
                                    <i class="fa-solid fa-star mr-1"></i> <?= $isFeatured ? 'Unfeature' : 'Feature' ?>
                                </button>
                            </form>
                        </div>
                        <button type="button" onclick="openEditModal(<?= htmlspecialchars(json_encode($pkg)) ?>)"
                            class="w-full px-4 py-2 mt-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 text-sm font-semibold transition-colors shadow-sm">
                            <i class="fa-solid fa-pen mr-1"></i> Edit Package
                        </button>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    </div>

    <!-- Add Package Modal -->
    <div id="addPackageModal" class="fixed inset-0 bg-black/50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-2xl font-bold text-slate-900">Add New Package</h3>
                <button onclick="document.getElementById('addPackageModal').classList.add('hidden')"
                    class="text-slate-400 hover:text-slate-600 text-2xl">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>

            <form method="POST" class="space-y-5">
                <input type="hidden" name="action" value="add">

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Package Name</label>
                        <input type="text" name="name" required
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Duration (Days)</label>
                        <input type="number" name="duration_days" value="365" required
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Price (KES)</label>
                        <input type="number" name="price" required step="0.01"
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Token Amount</label>
                        <input type="number" name="token_amount" required
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Description</label>
                    <textarea name="description" rows="4"
                        class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors"></textarea>
                </div>

                <div class="flex items-center gap-2">
                    <input type="checkbox" name="is_featured" id="is_featured" class="w-5 h-5 text-blue-600">
                    <label for="is_featured" class="text-sm font-semibold text-slate-700">Mark as Featured
                        Package</label>
                </div>

                <div class="flex justify-end gap-3 mt-8 pt-6 border-t border-slate-200">
                    <button type="button" onclick="document.getElementById('addPackageModal').classList.add('hidden')"
                        class="px-6 py-3 text-slate-600 hover:bg-slate-100 rounded-lg font-semibold transition-colors">
                        Cancel
                    </button>
                    <button type="submit"
                        class="px-6 py-3 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 shadow-lg transition-all">
                        <i class="fa-solid fa-plus mr-2"></i> Create Package
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Package Modal -->
    <div id="editPackageModal" class="fixed inset-0 bg-black/50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-2xl font-bold text-slate-900">Edit Package</h3>
                <button type="button" onclick="document.getElementById('editPackageModal').classList.add('hidden')"
                    class="text-slate-400 hover:text-slate-600 text-2xl">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>

            <form method="POST" class="space-y-5">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="package_id" id="edit_package_id">

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Package Name</label>
                        <input type="text" name="name" id="edit_name" required
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Duration (Days)</label>
                        <input type="number" name="duration_days" id="edit_duration_days" required
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Price (KES)</label>
                        <input type="number" name="price" id="edit_price" required step="0.01"
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-slate-700 mb-2">Token Amount</label>
                        <input type="number" name="token_amount" id="edit_token_amount" required
                            class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors">
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Description</label>
                    <textarea name="description" id="edit_description" rows="4"
                        class="w-full border-2 border-slate-300 rounded-lg p-3 focus:border-blue-500 focus:outline-none transition-colors"></textarea>
                </div>

                <div class="flex items-center gap-2">
                    <input type="checkbox" name="is_featured" id="edit_is_featured" class="w-5 h-5 text-blue-600">
                    <label for="edit_is_featured" class="text-sm font-semibold text-slate-700">Mark as Featured
                        Package</label>
                </div>

                <div class="flex justify-end gap-3 mt-8 pt-6 border-t border-slate-200">
                    <button type="button" onclick="document.getElementById('editPackageModal').classList.add('hidden')"
                        class="px-6 py-3 text-slate-600 hover:bg-slate-100 rounded-lg font-semibold transition-colors">
                        Cancel
                    </button>
                    <button type="submit"
                        class="px-6 py-3 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 shadow-lg transition-all">
                        <i class="fa-solid fa-save mr-2"></i> Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openEditModal(pkg) {
            document.getElementById('edit_package_id').value = pkg.id;
            document.getElementById('edit_name').value = pkg.name;
            document.getElementById('edit_duration_days').value = pkg.duration_days;
            document.getElementById('edit_price').value = pkg.price;
            document.getElementById('edit_token_amount').value = pkg.token_amount;
            document.getElementById('edit_description').value = pkg.description;
            document.getElementById('edit_is_featured').checked = pkg.is_featured == 1;

            document.getElementById('editPackageModal').classList.remove('hidden');
        }
    </script>
</body>

</html>
