<?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 = 'Plan Requests';

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

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 primary_key_column(PDO $pdo, string $table): string
{
    $stmt = $pdo->prepare(
        "SELECT k.column_name
         FROM information_schema.table_constraints tc
         JOIN information_schema.key_column_usage k
           ON k.constraint_name = tc.constraint_name
          AND k.table_schema = tc.table_schema
          AND k.table_name = tc.table_name
         WHERE tc.table_schema = DATABASE()
           AND tc.table_name = :t
           AND tc.constraint_type = 'PRIMARY KEY'
         ORDER BY k.ordinal_position ASC
         LIMIT 1"
    );
    $stmt->execute(['t' => $table]);
    return (string)($stmt->fetchColumn() ?: '');
}

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']);
    $requestTable = pick_existing_table($pdo, ['subscription_plan_requests', 'plan_requests', 'subscription_requests', 'customer_plan_requests', 'customer_subscriptions']);

    if ($requestTable !== '') {
        $reqCols = table_columns($pdo, $requestTable);

        $pkCol = primary_key_column($pdo, $requestTable);
        $idCol = $pkCol !== '' ? $pkCol : (in_array('request_id', $reqCols, true) ? 'request_id' : (in_array('id', $reqCols, true) ? 'id' : ''));
        if ($idCol === '') {
            throw new RuntimeException('Could not detect request table primary key column.');
        }
        $planIdCol = in_array('plan_id', $reqCols, true) ? 'plan_id' : (in_array('subscription_plan_id', $reqCols, true) ? 'subscription_plan_id' : 'plan_id');
        $custCol = in_array('customer_id', $reqCols, true) ? 'customer_id' : (in_array('user_id', $reqCols, true) ? 'user_id' : 'customer_id');
        $statusCol = in_array('status', $reqCols, true) ? 'status' : '';
        $createdCol = in_array('created_at', $reqCols, true) ? 'created_at' : '';

        $sql = 'SELECT r.' . $idCol . ' AS request_id, r.' . $planIdCol . ' AS plan_id, r.' . $custCol . ' AS customer_id';
        $sql .= $statusCol !== '' ? (', r.' . $statusCol . ' AS status') : ", 'pending' AS status";
        $sql .= $createdCol !== '' ? (', r.' . $createdCol . ' AS created_at') : ', NULL AS created_at';
        $sql .= ', u.full_name AS customer_name, u.email AS customer_email';

        if ($planTable !== '') {
            $planCols = table_columns($pdo, $planTable);
            $pidCol = in_array('plan_id', $planCols, true) ? 'plan_id' : (in_array('id', $planCols, true) ? 'id' : 'plan_id');
            $pnameCol = in_array('plan_name', $planCols, true) ? 'plan_name' : (in_array('name', $planCols, true) ? 'name' : 'plan_name');
            $sql .= ', p.' . $pnameCol . ' AS plan_name';
            $sql .= ' FROM ' . $requestTable . ' r JOIN users u ON u.user_id = r.' . $custCol . ' LEFT JOIN ' . $planTable . ' p ON p.' . $pidCol . ' = r.' . $planIdCol;
        } else {
            $sql .= ", CONCAT('Plan #', r." . $planIdCol . ") AS plan_name";
            $sql .= ' FROM ' . $requestTable . ' r JOIN users u ON u.user_id = r.' . $custCol;
        }

        $sql .= ' ORDER BY r.' . $idCol . ' 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' => false],
    ['label' => 'Plan Requests', 'href' => '/pest/public/admin/plan_requests.php', 'active' => true],
];

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-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">Plan Requests</h1>
            <p class="mt-1 text-sm text-slate-600">Approve or decline customer subscription plan requests.</p>
        </div>
    </div>

    <?php if ($requestTable === ''): ?>
        <div class="mt-6 rounded-xl border bg-slate-50 p-4 text-sm text-slate-700">
            Requests table not found in database.
        </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">Request</th>
                        <th class="py-2 pr-4">Customer</th>
                        <th class="py-2 pr-4">Plan</th>
                        <th class="py-2 pr-4">Status</th>
                        <th class="py-2 pr-4">Created</th>
                        <th class="py-2">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$rows): ?>
                        <tr class="border-b"><td class="py-3 text-slate-500" colspan="6">No requests 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['request_id']) ?></td>
                                <td class="py-3 pr-4">
                                    <div class="font-medium"><?= e((string)$r['customer_name']) ?></div>
                                    <div class="text-xs text-slate-500"><?= e((string)$r['customer_email']) ?></div>
                                </td>
                                <td class="py-3 pr-4"><?= e((string)$r['plan_name']) ?></td>
                                <td class="py-3 pr-4"><?= e((string)$r['status']) ?></td>
                                <td class="py-3 pr-4"><?= e((string)($r['created_at'] ?? '')) ?></td>
                                <td class="py-3">
                                    <div class="flex flex-wrap gap-2">
                                        <form method="post" action="/pest/public/admin/plan_request_update.php" onsubmit="return confirm('Approve this request?');">
                                            <input type="hidden" name="id" value="<?= e((string)$r['request_id']) ?>">
                                            <input type="hidden" name="status" value="approved">
                                            <button class="rounded-lg border border-green-200 bg-green-50 px-3 py-1.5 text-xs text-green-700 hover:bg-green-100" type="submit">Approve</button>
                                        </form>
                                        <form method="post" action="/pest/public/admin/plan_request_update.php" onsubmit="return confirm('Decline this request?');">
                                            <input type="hidden" name="id" value="<?= e((string)$r['request_id']) ?>">
                                            <input type="hidden" name="status" value="declined">
                                            <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">Decline</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';
