<?php

declare(strict_types=1);

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo 'Method Not Allowed';
    exit;
}

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    echo 'Invalid ID';
    exit;
}

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 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 === '') {
        throw new RuntimeException('Plans table not found.');
    }

    $colsStmt = $pdo->prepare(
        'SELECT column_name
         FROM information_schema.columns
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $colsStmt->execute(['t' => $planTable]);
    $cols = $colsStmt->fetchAll(PDO::FETCH_COLUMN);

    $idCol = in_array('plan_id', $cols, true) ? 'plan_id' : (in_array('id', $cols, true) ? 'id' : 'plan_id');

    $stmt = $pdo->prepare('DELETE FROM ' . $planTable . ' WHERE ' . $idCol . ' = :id');
    $stmt->execute(['id' => $id]);
} catch (Throwable $e) {
    http_response_code(500);
    echo $e->getMessage();
    exit;
}

header('Location: /pest/public/admin/plans.php');
exit;
