<?php

declare(strict_types=1);

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

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

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

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

header('Location: /pest/public/customer/index.php');
exit;

$customerId = (int)($user['user_id'] ?? 0);

$plans = [];
$myRequests = [];
$error = '';

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 '';
}

$planTable = '';
$requestTable = '';

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 ($planTable !== '') {
        $planCols = table_columns($pdo, $planTable);

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

        $sql = 'SELECT ' . $idCol . ' AS plan_id, ' . $nameCol . ' AS plan_name';
        if (in_array($descCol, $planCols, true)) {
            $sql .= ', ' . $descCol . ' AS description';
        } else {
            $sql .= ', NULL AS description';
        }
        if (in_array($priceCol, $planCols, true)) {
            $sql .= ', ' . $priceCol . ' AS price';
        } else {
            $sql .= ', NULL AS price';
        }
        $sql .= ' FROM ' . $planTable;
        if ($activeCol !== '') {
            $sql .= ' WHERE ' . $activeCol . ' = 1';
        }
        $sql .= ' ORDER BY plan_id DESC';

        $plans = $pdo->query($sql)->fetchAll();
    }

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

        $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' : '';
        $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.');
        }

        $sql = 'SELECT ' . $idCol . ' AS request_id, ' . $planIdCol . ' AS plan_id';
        if ($statusCol !== '') {
            $sql .= ', ' . $statusCol . ' AS status';
        } else {
            $sql .= ", 'pending' AS status";
        }
        if ($createdCol !== '') {
            $sql .= ', ' . $createdCol . ' AS created_at';
        } else {
            $sql .= ', NULL AS created_at';
        }
        $sql .= ' FROM ' . $requestTable . ' WHERE ' . $custCol . ' = :cid ORDER BY ' . $idCol . ' DESC';

        $stmt = $pdo->prepare($sql);
        $stmt->execute(['cid' => $customerId]);
        $myRequests = $stmt->fetchAll();
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $planId = (int)($_POST['plan_id'] ?? 0);
    if ($planId <= 0) {
        $error = 'Invalid plan selected.';
    } elseif ($requestTable === '') {
        $error = 'Plan requests table not found in database.';
    } else {
        try {
            $pdo = Database::pdo();
            $reqCols = table_columns($pdo, $requestTable);

            $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' : '';

            $data = [
                $planIdCol => $planId,
                $custCol => $customerId,
            ];
            if ($statusCol !== '') {
                $data[$statusCol] = 'pending';
            }
            if ($createdCol !== '') {
                $data[$createdCol] = date('Y-m-d H:i:s');
            }

            $colNames = array_keys($data);
            $placeholders = [];
            foreach ($colNames as $c) {
                $placeholders[] = ':' . $c;
            }

            $sql = 'INSERT INTO ' . $requestTable . ' (' . implode(',', $colNames) . ') VALUES (' . implode(',', $placeholders) . ')';
            $stmt = $pdo->prepare($sql);
            $stmt->execute($data);

            header('Location: /pest/public/customer/plans.php');
            exit;
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
}

$nav = [
    ['label' => 'My Requests', 'href' => '/pest/public/customer/index.php', 'active' => false],
    ['label' => 'Request Service', 'href' => '/pest/public/customer/request_service.php', 'active' => false],
    ['label' => 'My Services', 'href' => '/pest/public/customer/my_services.php', 'active' => false],
    ['label' => 'Service Reports', 'href' => '/pest/public/customer/reports.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/customer/complaints.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/customer/payments.php', 'active' => false],
    ['label' => 'Subscription Plans', 'href' => '/pest/public/customer/plans.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 items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Subscription Plans</h1>
            <p class="mt-1 text-sm text-slate-600">Choose a plan and send a request. Admin will approve and assign it to you.</p>
        </div>
    </div>

    <?php if ($planTable === ''): ?>
        <div class="mt-6 rounded-xl border bg-slate-50 p-4 text-sm text-slate-700">
            No plans table found in database.
        </div>
    <?php else: ?>
        <div class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2">
            <?php if (!$plans): ?>
                <div class="rounded-xl border bg-slate-50 p-4 text-sm text-slate-700">No active plans available.</div>
            <?php else: ?>
                <?php foreach ($plans as $p): ?>
                    <div class="rounded-xl border bg-white p-5">
                        <div class="text-lg font-semibold"><?= e((string)$p['plan_name']) ?></div>
                        <?php if (!empty($p['description'])): ?>
                            <div class="mt-1 text-sm text-slate-600"><?= e((string)$p['description']) ?></div>
                        <?php endif; ?>
                        <form class="mt-4" method="post" action="" onsubmit="return confirm('Send request for this plan?');">
                            <input type="hidden" name="plan_id" value="<?= e((string)$p['plan_id']) ?>">
                            <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Request Plan</button>
                        </form>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <div class="mt-8 rounded-xl border bg-white p-5">
        <div class="text-sm font-semibold">My Plan Requests</div>
        <?php if ($requestTable === ''): ?>
            <div class="mt-2 text-sm text-slate-600">Requests table not configured.</div>
        <?php else: ?>
            <div class="mt-3 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">Plan ID</th>
                            <th class="py-2 pr-4">Status</th>
                            <th class="py-2">Created</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$myRequests): ?>
                            <tr class="border-b"><td class="py-3 text-slate-500" colspan="4">No plan requests yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($myRequests 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"><?= e((string)$r['plan_id']) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)$r['status']) ?></td>
                                    <td class="py-3"><?= e((string)($r['created_at'] ?? '')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
