<?php
/**
 * Booking — services CRUD.
 * Single page: list + inline create/edit form (toggled by ?edit=ID
 * or ?new=1).
 */
require_once dirname(__DIR__, 3) . '/config.php';
require_once dirname(__DIR__) . '/BookingAPI.php';

Auth::require();
Auth::requirePerm('booking.manage_services');
BookingAPI::ensureSchema();

$pageTitle  = 'Services';
$currentNav = 'booking-services';

$tid = current_tenant_id();

$flash = null;
$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$isNew  = !empty($_GET['new']);

$editing = null;
if ($editId > 0) {
    $editing = Database::row(
        "SELECT * FROM booking_services WHERE id = ? AND tenant_id = ?",
        [$editId, $tid]
    );
    if (!$editing) { http_response_code(404); $editing = null; $editId = 0; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $action = $_POST['_action'] ?? '';
        if ($action === 'save') {
            $id    = (int)($_POST['id'] ?? 0);
            $name  = trim((string)($_POST['name'] ?? ''));
            if ($name === '') {
                $flash = ['type' => 'error', 'msg' => 'Name is required.'];
            } else {
                $row = [
                    'tenant_id'    => $tid,
                    'name'         => mb_substr($name, 0, 160),
                    'slug'         => BookingAPI::slugify($name, $id > 0 ? $id : null),
                    'description'  => trim((string)($_POST['description'] ?? '')) ?: null,
                    'duration_min' => max(5, (int)($_POST['duration_min'] ?? 30)),
                    'buffer_min'   => max(0, (int)($_POST['buffer_min'] ?? 0)),
                    'price_cents'  => max(0, (int)round(((float)($_POST['price'] ?? 0)) * 100)),
                    'currency'     => mb_substr(strtoupper(trim((string)($_POST['currency'] ?? 'USD'))), 0, 8),
                    'color'        => mb_substr(trim((string)($_POST['color'] ?? '#2563EB')), 0, 16),
                    'is_active'    => !empty($_POST['is_active']) ? 1 : 0,
                ];
                if ($id > 0) {
                    Database::update('booking_services', $row, 'id = ? AND tenant_id = ?', [$id, $tid]);
                    AuditLog::record('booking.service_updated', (string)$id);
                    $flash = ['type' => 'success', 'msg' => 'Service saved.'];
                } else {
                    $id = Database::insert('booking_services', $row);
                    AuditLog::record('booking.service_created', (string)$id);
                    $flash = ['type' => 'success', 'msg' => 'Service created.'];
                }
                header('Location: ' . plugin_url('booking', 'admin/services.php'));
                exit;
            }
        } elseif ($action === 'delete') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id > 0) {
                Database::delete('booking_provider_services', 'service_id = ?', [$id]);
                Database::delete('booking_services', 'id = ? AND tenant_id = ?', [$id, $tid]);
                AuditLog::record('booking.service_deleted', (string)$id);
                $flash = ['type' => 'success', 'msg' => 'Service deleted.'];
                header('Location: ' . plugin_url('booking', 'admin/services.php'));
                exit;
            }
        }
    }
}

$services = Database::rows(
    "SELECT s.*,
            (SELECT COUNT(*) FROM booking_provider_services ps WHERE ps.service_id = s.id) AS provider_count
       FROM booking_services s
      WHERE s.tenant_id = ?
   ORDER BY s.name",
    [$tid]
);

require SLATE_ROOT . '/admin/partials/header.php';
?>

<?php slate_breadcrumbs([
    ['label' => __('dashboard', 'Dashboard'), 'href' => SLATE_URL . '/admin/'],
    ['label' => __('booking', 'Booking'), 'href' => plugin_url('booking', 'admin/index.php')],
    ['label' => 'Services'],
]); ?>

<div class="page-header">
    <div><h1>Services</h1></div>
    <?php if (!$isNew && !$editing): ?>
        <a href="?new=1" class="btn btn-primary">New service</a>
    <?php endif; ?>
</div>

<?php if ($flash): ?><div class="alert alert-<?= e($flash['type']) ?>"><?= e($flash['msg']) ?></div><?php endif; ?>

<?php if ($isNew || $editing):
    $s = $editing ?: ['id'=>0,'name'=>'','description'=>'','duration_min'=>30,'buffer_min'=>0,
                      'price_cents'=>0,'currency'=>'USD','color'=>'#2563EB','is_active'=>1];
?>
    <div class="card">
        <div class="card-header"><h2><?= $editing ? 'Edit ' . e($editing['name']) : 'New service' ?></h2></div>
        <form method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="_action" value="save">
            <input type="hidden" name="id" value="<?= (int)$s['id'] ?>">

            <div class="field-row field-row-2">
                <div class="field">
                    <label class="field-label" for="name">Name <span class="field-required">*</span></label>
                    <input type="text" id="name" name="name" required maxlength="160" value="<?= e($s['name']) ?>">
                </div>
                <div class="field">
                    <label class="field-label" for="color">Colour</label>
                    <input type="color" id="color" name="color" value="<?= e($s['color']) ?>">
                </div>
            </div>

            <div class="field">
                <label class="field-label" for="description">Description</label>
                <textarea id="description" name="description" maxlength="2000"><?= e($s['description'] ?? '') ?></textarea>
            </div>

            <div class="field-row field-row-3">
                <div class="field">
                    <label class="field-label" for="duration_min">Duration (min) <span class="field-required">*</span></label>
                    <input type="number" id="duration_min" name="duration_min" min="5" step="5" required value="<?= (int)$s['duration_min'] ?>">
                </div>
                <div class="field">
                    <label class="field-label" for="buffer_min">Buffer after (min)</label>
                    <input type="number" id="buffer_min" name="buffer_min" min="0" step="5" value="<?= (int)$s['buffer_min'] ?>">
                </div>
                <div class="field">
                    <label class="field-label" for="price">Price</label>
                    <input type="number" id="price" name="price" min="0" step="0.01" value="<?= e(number_format(((int)$s['price_cents'])/100, 2, '.', '')) ?>">
                </div>
            </div>

            <div class="field-row field-row-2">
                <div class="field">
                    <label class="field-label" for="currency">Currency</label>
                    <input type="text" id="currency" name="currency" maxlength="8" value="<?= e($s['currency']) ?>">
                </div>
                <div class="field" style="display:flex;align-items:flex-end;">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                        <input type="checkbox" name="is_active" value="1" <?= !empty($s['is_active']) ? 'checked' : '' ?>>
                        <span>Active (bookable)</span>
                    </label>
                </div>
            </div>

            <div class="flex gap-2 mt-3">
                <button type="submit" class="btn btn-primary"><?= $editing ? 'Save changes' : 'Create service' ?></button>
                <a href="<?= e(plugin_url('booking', 'admin/services.php')) ?>" class="btn btn-ghost">Cancel</a>
            </div>
        </form>
    </div>
<?php endif; ?>

<?php if (!$services): ?>
    <div class="card"><div class="empty"><div class="empty-title">No services yet</div><p class="text-sm">Create one to get started.</p></div></div>
<?php else: ?>
    <div class="data-list" data-single-open>
        <?php foreach ($services as $s):
            $detail = [
                'Duration'   => $s['duration_min'] . ' min' . ($s['buffer_min'] ? ' (+ ' . $s['buffer_min'] . ' min buffer)' : ''),
                'Price'      => $s['price_cents'] > 0 ? $s['currency'] . ' ' . number_format($s['price_cents']/100, 2) : 'Free',
                'Providers'  => $s['provider_count'] . ' linked',
                'Slug'       => ['label' => 'Slug', 'html' => '<code>' . e($s['slug']) . '</code>'],
            ];
            if (!empty($s['description'])) $detail['Description'] = ['label'=>'Description','value'=>$s['description'],'muted'=>true];

            $actions = '<a href="?edit=' . (int)$s['id'] . '" class="btn btn-sm">Edit</a> '
                     . '<form method="post" style="display:inline;margin:0;" onsubmit="return confirm(\'Delete this service?\')">'
                     . csrf_field()
                     . '<input type="hidden" name="_action" value="delete">'
                     . '<input type="hidden" name="id" value="' . (int)$s['id'] . '">'
                     . '<button class="btn btn-sm btn-danger">Delete</button>'
                     . '</form>';

            slate_data_row([
                'avatar'       => mb_substr($s['name'], 0, 1),
                'avatar_color' => $s['is_active'] ? 'info' : 'muted',
                'title'        => $s['name'],
                'meta'         => $s['duration_min'] . ' min' . ($s['price_cents'] > 0 ? ' · ' . $s['currency'] . ' ' . number_format($s['price_cents']/100, 2) : ''),
                'badge'        => $s['is_active'] ? ['Active', 'active'] : ['Inactive', 'inactive'],
                'detail'       => $detail,
                'actions'      => $actions,
            ]);
        endforeach; ?>
    </div>
    <?php slate_data_list_script(); ?>
<?php endif; ?>

<?php require SLATE_ROOT . '/admin/partials/footer.php'; ?>
