<?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 Service';

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

$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' => true],
    ['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],
];

$error = '';

try {
    $pdo = Database::pdo();
    $stmt = $pdo->prepare('SELECT service_id, service_name, description, price, duration_minutes, category, is_active FROM services WHERE service_id = :id LIMIT 1');
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch();

    if (!$row) {
        http_response_code(404);
        echo 'Service not found';
        exit;
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
    $row = null;
}

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

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

    if ($values['service_name'] === '') {
        $error = 'Service name is required.';
    } else {
        try {
            $pdo = Database::pdo();
            $stmt2 = $pdo->prepare(
                'UPDATE services SET service_name=:service_name, description=:description, duration_minutes=:duration_minutes, category=:category, is_active=:is_active WHERE service_id=:id'
            );
            $stmt2->execute([
                'service_name' => $values['service_name'],
                'description' => ($values['description'] !== '' ? $values['description'] : null),
                'duration_minutes' => ($values['duration_minutes'] !== '' ? (int)$values['duration_minutes'] : null),
                'category' => ($values['category'] !== '' ? $values['category'] : null),
                'is_active' => ((int)$values['is_active'] === 1) ? 1 : 0,
                'id' => $id,
            ]);

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

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 Service</h1>
            <p class="mt-1 text-sm text-slate-600">Update service details.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/services.php">Back</a>
    </div>

    <form class="mt-6 grid grid-cols-1 gap-4" method="post" action="">
        <div>
            <label class="block text-sm font-medium">Service name</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="service_name" value="<?= e($values['service_name']) ?>" required>
        </div>
        <div>
            <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="3"><?= e($values['description']) ?></textarea>
        </div>
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div>
                <label class="block text-sm font-medium">Duration (minutes)</label>
                <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" name="duration_minutes" value="<?= e($values['duration_minutes']) ?>">
            </div>
            <div>
                <label class="block text-sm font-medium">Category</label>
                <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="category" value="<?= e($values['category']) ?>">
            </div>
        </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>
            <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';
