<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['admin']);

$user = auth_user();
$title = 'Subscription Plans';

$error = '';
$rows = [];
$planTable = '';

function table_exists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.tables
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return (int)$stmt->fetchColumn() > 0;
}

function table_columns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        'SELECT column_name
         FROM information_schema.columns
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

function pick_existing_table(PDO $pdo, array $candidates): string
{
    foreach ($candidates as $t) {
        if (table_exists($pdo, $t)) {
            return $t;
        }
    }
    return '';
}

try {
    $pdo = Database::pdo();
    $planTable = pick_existing_table($pdo, ['subscription_plans', 'plans', 'service_plans']);

    if ($planTable !== '') {
        $cols = table_columns($pdo, $planTable);

        $idCol = in_array('plan_id', $cols, true) ? 'plan_id' : (in_array('id', $cols, true) ? 'id' : 'plan_id');
        $nameCol = in_array('plan_name', $cols, true) ? 'plan_name' : (in_array('name', $cols, true) ? 'name' : 'plan_name');
        $descCol = in_array('description', $cols, true) ? 'description' : (in_array('details', $cols, true) ? 'details' : '');
        $priceCol = in_array('price', $cols, true) ? 'price' : (in_array('amount', $cols, true) ? 'amount' : '');
        $activeCol = in_array('is_active', $cols, true) ? 'is_active' : (in_array('active', $cols, true) ? 'active' : '');

        $sql = 'SELECT ' . $idCol . ' AS plan_id, ' . $nameCol . ' AS plan_name';
        $sql .= $descCol !== '' ? (', ' . $descCol . ' AS description') : ', NULL AS description';
        $sql .= $priceCol !== '' ? (', ' . $priceCol . ' AS price') : ', NULL AS price';
        $sql .= $activeCol !== '' ? (', ' . $activeCol . ' AS is_active') : ', 1 AS is_active';
        $sql .= ' FROM ' . $planTable . ' ORDER BY plan_id DESC';

        $rows = $pdo->query($sql)->fetchAll();
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => '/pest/public/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => '/pest/public/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => '/pest/public/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => '/pest/public/admin/task_assignment.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => '/pest/public/admin/reports.php', 'active' => false],
    ['label' => 'Subscription Plans', 'href' => '/pest/public/admin/plans.php', 'active' => true],
    ['label' => 'Plan Requests', 'href' => '/pest/public/admin/plan_requests.php', 'active' => false],
];

ob_start();
?>
<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">Subscription Plans</h1>
            <p class="mt-1 text-sm text-slate-600">Publish plans for customers to request.</p>
        </div>
        <a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" href="/pest/public/admin/plan_add.php">Add Plan</a>
    </div>

    <?php if ($planTable === ''): ?>
        <div class="mt-6 rounded-xl border bg-slate-50 p-4 text-sm text-slate-700">
            Plans table not found in database. Expected one of: <span class="font-medium">subscription_plans</span>, <span class="font-medium">plans</span>, <span class="font-medium">service_plans</span>.
        </div>
    <?php else: ?>
        <div class="mt-5 overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="text-left text-slate-600">
                    <tr class="border-b">
                        <th class="py-2 pr-4">ID</th>
                        <th class="py-2 pr-4">Plan</th>
                        <th class="py-2 pr-4">Active</th>
                        <th class="py-2">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$rows): ?>
                        <tr class="border-b"><td class="py-3 text-slate-500" colspan="4">No plans found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                            <tr class="border-b last:border-0">
                                <td class="py-3 pr-4 font-medium">#<?= e((string)$r['plan_id']) ?></td>
                                <td class="py-3 pr-4">
                                    <div class="font-medium"><?= e((string)$r['plan_name']) ?></div>
                                    <div class="text-xs text-slate-500"><?= e((string)($r['description'] ?? '')) ?></div>
                                </td>
                                <td class="py-3 pr-4"><?= ((int)($r['is_active'] ?? 1) === 1) ? 'Yes' : 'No' ?></td>
                                <td class="py-3">
                                    <div class="flex flex-wrap gap-2">
                                        <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/plan_edit.php?id=<?= e((string)$r['plan_id']) ?>">Edit</a>
                                        <form method="post" action="/pest/public/admin/plan_delete.php" onsubmit="return confirm('Delete this plan?');">
                                            <input type="hidden" name="id" value="<?= e((string)$r['plan_id']) ?>">
                                            <button class="rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs text-red-700 hover:bg-red-100" type="submit">Delete</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
