<?php
$db = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $slug = $_POST['slug'] ?? '';
    $short_description = $_POST['short_description'] ?? '';
    $description = $_POST['description'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $price = $_POST['price'] ?? '';
    $icon = $_POST['icon'] ?? 'fas fa-flask';
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        if (!$slug) {
            $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $title));
        }

        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE services SET title=?, slug=?, short_description=?, description=?, image_url=?, price=?, icon=?, sort_order=? WHERE id=?");
                $stmt->execute([$title, $slug, $short_description, $description, $image_url, $price, $icon, $sort_order, $id]);
                $message = 'Service updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO services (title, slug, short_description, description, image_url, price, icon, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$title, $slug, $short_description, $description, $image_url, $price, $icon, $sort_order]);
                $message = 'Service added successfully.';
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'duplicate') !== false || strpos($e->getMessage(), '23505') !== false) {
                $message = 'Error: A service with that slug already exists. Please use a different slug.';
            } else {
                $message = 'Database error: ' . htmlspecialchars($e->getMessage());
            }
        }
    }
}

$services = $db->query("SELECT * FROM services ORDER BY sort_order ASC")->fetchAll();
$editService = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM services WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editService = $stmt->fetch();
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Manage Services</h2>
</div>

<?php if ($message): ?>
<div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="admin-card">
    <h3><?= $editService ? 'Edit Service' : 'Add New Service' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editService): ?>
        <input type="hidden" name="id" value="<?= $editService['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Title</label>
            <input type="text" name="title" value="<?= htmlspecialchars($editService['title'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Slug (URL-friendly name, auto-generated if blank)</label>
            <input type="text" name="slug" value="<?= htmlspecialchars($editService['slug'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Short Description</label>
            <input type="text" name="short_description" value="<?= htmlspecialchars($editService['short_description'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Description</label>
            <textarea name="description" rows="5"><?= htmlspecialchars($editService['description'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Image URL</label>
            <input type="url" name="image_url" value="<?= htmlspecialchars($editService['image_url'] ?? '') ?>">
            <div style="margin-top:8px; display:flex; gap:8px; align-items:center;">
                <input type="file" id="file_upload_service_image" accept="image/*,.pdf" style="font-size:13px;">
                <button type="button" onclick="uploadFile('file_upload_service_image', 'image_url')" class="btn-sm btn-sm-success"><i class="fas fa-upload"></i> Upload</button>
                <span id="upload_status_file_upload_service_image" style="font-size:12px;color:#666;"></span>
            </div>
        </div>
        <div class="form-group">
            <label>Price</label>
            <input type="text" name="price" value="<?= htmlspecialchars($editService['price'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Icon (e.g. fas fa-flask)</label>
            <input type="text" name="icon" value="<?= htmlspecialchars($editService['icon'] ?? 'fas fa-flask') ?>">
        </div>
        <div class="form-group">
            <label>Sort Order</label>
            <input type="number" name="sort_order" value="<?= htmlspecialchars($editService['sort_order'] ?? '0') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editService ? 'Update' : 'Add' ?> Service</button>
        <?php if ($editService): ?>
        <a href="/admin/services" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Services</h3>
    <table>
        <thead>
            <tr><th>Image</th><th>Title</th><th>Price</th><th>Order</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($services as $s): ?>
            <tr>
                <td><img src="<?= htmlspecialchars($s['image_url']) ?>" class="admin-img-preview"></td>
                <td><?= htmlspecialchars($s['title']) ?></td>
                <td><?= htmlspecialchars($s['price']) ?></td>
                <td><?= $s['sort_order'] ?></td>
                <td class="actions">
                    <a href="/admin/services?edit=<?= $s['id'] ?>" class="btn-sm btn-sm-primary">Edit</a>
                    <form method="post" action="/admin/delete" style="display:inline" onsubmit="return confirm('Are you sure?')"><input type="hidden" name="type" value="services"><input type="hidden" name="delete_id" value="<?= $s['id'] ?>"><?= csrfField() ?><button type="submit" class="btn-sm btn-sm-danger">Delete</button></form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
