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

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

$error = '';
$planTable = '';
$row = null;

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 === '') {
        $error = 'Plans table not found in database.';
    } else {
        $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 . ' WHERE ' . $idCol . ' = :id LIMIT 1';

        $stmt = $pdo->prepare($sql);
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();

        if (!$row) {
            http_response_code(404);
            echo 'Plan not found';
            exit;
        }

        $values = [
            'plan_name' => (string)($row['plan_name'] ?? ''),
            'description' => (string)($row['description'] ?? ''),
            'is_active' => ((int)($row['is_active'] ?? 1) === 1) ? '1' : '0',
        ];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $values['plan_name'] = trim((string)($_POST['plan_name'] ?? ''));
            $values['description'] = trim((string)($_POST['description'] ?? ''));
            $values['is_active'] = trim((string)($_POST['is_active'] ?? '1'));

            if ($values['plan_name'] === '') {
                $error = 'Plan name is required.';
            } else {
                $data = [
                    $nameCol => $values['plan_name'],
                    'id' => $id,
                ];
                $set = [];
                $set[] = $nameCol . '=:' . $nameCol;

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

                $sqlU = 'UPDATE ' . $planTable . ' SET ' . implode(', ', $set) . ' WHERE ' . $idCol . ' = :id';
                $stmtU = $pdo->prepare($sqlU);
                $stmtU->execute($data);

                header('Location: /pest/public/admin/plans.php');
                exit;
            }
        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
    $values = [
        'plan_name' => '',
        'description' => '',
        'is_active' => '1',
    ];
}

$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">Edit Plan</h1>
            <p class="mt-1 text-sm text-slate-600">Update subscription plan details.</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 changes</button>
        </div>
    </form>
</div>
<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
