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

$error = '';
$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 '';
}

$values = [
    'plan_name' => '',
    'description' => '',
    'is_active' => '1',
];

try {
    $pdo = Database::pdo();
    $planTable = pick_existing_table($pdo, ['subscription_plans', 'plans', 'service_plans']);
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($values as $k => $v) {
        $values[$k] = trim((string)($_POST[$k] ?? ''));
    }

    if ($planTable === '') {
        $error = 'Plans table not found in database.';
    } elseif ($values['plan_name'] === '') {
        $error = 'Plan name is required.';
    } else {
        try {
            $pdo = Database::pdo();
            $cols = table_columns($pdo, $planTable);

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

            $data = [];
            $data[$nameCol] = $values['plan_name'];
            if ($descCol !== '') {
                $data[$descCol] = ($values['description'] !== '' ? $values['description'] : null);
            }
            if ($priceCol !== '') {
                $data[$priceCol] = 0;
            }
            if ($activeCol !== '') {
                $data[$activeCol] = ((int)$values['is_active'] === 1) ? 1 : 0;
            }

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

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

            header('Location: /pest/public/admin/plans.php');
            exit;
        } 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 items-center justify-between">
        <div>
            <h1 class="text-xl font-semibold">Add Plan</h1>
            <p class="mt-1 text-sm text-slate-600">Create a subscription plan.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/plans.php">Back</a>
    </div>

    <form class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2" method="post" action="">
        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Plan name</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="plan_name" value="<?= e($values['plan_name']) ?>" required>
        </div>
        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Description</label>
            <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="description" rows="4"><?= e($values['description']) ?></textarea>
        </div>
        <div>
            <label class="block text-sm font-medium">Active</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="is_active">
                <option value="1" <?= ($values['is_active'] === '1') ? 'selected' : '' ?>>Yes</option>
                <option value="0" <?= ($values['is_active'] === '0') ? 'selected' : '' ?>>No</option>
            </select>
        </div>

        <div class="md:col-span-2">
            <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">Save</button>
        </div>
    </form>
</div>
<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
