<?php
require_once '../config.php';

$conn = get_db_connection();
$message = '';
$message_type = '';

// Helper function to create slug from name
if (!function_exists('create_slug')) {
    function create_slug($name)
    {
        $slug = strtolower(trim($name));
        $slug = preg_replace('/[^a-z0-9-]/', '-', $slug);
        $slug = preg_replace('/-+/', '-', $slug);
        return trim($slug, '-');
    }
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add' || $_POST['action'] === 'edit') {
            $name = trim($_POST['name'] ?? '');
            $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
            $description = trim($_POST['description'] ?? '');
            $content = $_POST['content'] ?? '';
            $url = trim($_POST['url'] ?? '');
            $display_order = intval($_POST['display_order'] ?? 0);
            $image_path = $_POST['current_image'] ?? '';

            // Handle image upload
            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['image'];
                $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
                $file_type = mime_content_type($file['tmp_name']);

                if (in_array($file_type, $allowed_types, true)) {
                    if ($file['size'] <= 5 * 1024 * 1024) { // 5MB
                        $upload_dir = dirname(__DIR__) . '/uploads/services/';
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0755, true);
                        }

                        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                        $filename = 'service-' . time() . '-' . uniqid() . '.' . $extension;
                        $filepath = $upload_dir . $filename;

                        if (move_uploaded_file($file['tmp_name'], $filepath)) {
                            $image_path = '/uploads/services/' . $filename;
                        }
                    }
                }
            }

            if (empty($name)) {
                $message = 'Service name is required!';
                $message_type = 'danger';
            } else {
                $slug = create_slug($name);

                if ($_POST['action'] === 'add') {
                    $stmt = $conn->prepare("INSERT INTO services (category_id, name, slug, description, content, image, url, display_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("issssssi", $category_id, $name, $slug, $description, $content, $image_path, $url, $display_order);

                    if ($stmt->execute()) {
                        $message = 'Service added successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error adding service: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                } else {
                    $id = intval($_POST['id']);
                    $stmt = $conn->prepare("UPDATE services SET category_id = ?, name = ?, slug = ?, description = ?, content = ?, image = ?, url = ?, display_order = ? WHERE id = ?");
                    $stmt->bind_param("issssssii", $category_id, $name, $slug, $description, $content, $image_path, $url, $display_order, $id);

                    if ($stmt->execute()) {
                        $message = 'Service updated successfully!';
                        $message_type = 'success';
                    } else {
                        $message = 'Error updating service: ' . $stmt->error;
                        $message_type = 'danger';
                    }
                    $stmt->close();
                }
            }
        } elseif ($_POST['action'] === 'delete') {
            $id = intval($_POST['id']);
            $stmt = $conn->prepare("DELETE FROM services WHERE id = ?");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                $message = 'Service deleted successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error deleting service: ' . $stmt->error;
                $message_type = 'danger';
            }
            $stmt->close();
        } elseif ($_POST['action'] === 'update_order') {
            $orders = $_POST['orders'] ?? [];
            $success = true;
            foreach ($orders as $id => $order) {
                $id = intval($id);
                $order = intval($order);
                $stmt = $conn->prepare("UPDATE services SET display_order = ? WHERE id = ?");
                $stmt->bind_param("ii", $order, $id);
                if (!$stmt->execute()) {
                    $success = false;
                }
                $stmt->close();
            }
            if ($success) {
                $message = 'Display orders updated successfully!';
                $message_type = 'success';
            } else {
                $message = 'Some orders could not be updated.';
                $message_type = 'danger';
            }
        }
    }
}

// Get all categories
$categories_result = $conn->query("SELECT * FROM service_categories ORDER BY display_order ASC, name ASC");
$categories = [];
if ($categories_result) {
    while ($row = $categories_result->fetch_assoc()) {
        $categories[] = $row;
    }
}

// Get all services
$services_result = $conn->query("SELECT s.*, c.name as category_name 
    FROM services s 
    LEFT JOIN service_categories c ON s.category_id = c.id 
    ORDER BY s.display_order ASC, s.id ASC");
$services = [];
if ($services_result) {
    while ($row = $services_result->fetch_assoc()) {
        $services[] = $row;
    }
}

// Get service for editing
$edit_service = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM services WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $row = $result->fetch_assoc()) {
        $edit_service = $row;
    }
    $stmt->close();
}

$page_title = 'Services Management';
$extra_css = '<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">';
$extra_js = '<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
    var quill = new Quill("#content-editor", {
        theme: "snow",
        modules: {
            toolbar: [
                [{ "header": [1, 2, 3, false] }],
                ["bold", "italic", "underline", "strike"],
                [{ "color": [] }, { "background": [] }],
                [{ "list": "ordered"}, { "list": "bullet" }],
                [{ "align": [] }],
                ["link", "image", "blockquote", "code-block"],
                ["clean"]
            ]
        }
    });
    
    var form = document.querySelector("form");
    var contentTextarea = document.getElementById("content");
    
    if (contentTextarea.value) {
        quill.root.innerHTML = contentTextarea.value;
    }
    
    form.addEventListener("submit", function(e) {
        contentTextarea.value = quill.root.innerHTML;
    });
</script>';

require_once 'includes/admin-header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title"><?php echo $edit_service ? 'Edit Service' : 'Add New Service'; ?></h2>
        <?php if ($edit_service): ?>
            <a href="services" class="btn btn-secondary btn-sm">Cancel</a>
        <?php endif; ?>
    </div>

    <form method="POST" action="" enctype="multipart/form-data">
        <input type="hidden" name="action" value="<?php echo $edit_service ? 'edit' : 'add'; ?>">
        <?php if ($edit_service): ?>
            <input type="hidden" name="id" value="<?php echo $edit_service['id']; ?>">
        <?php endif; ?>

        <div class="dashboard-grid">
            <div class="left-col">
                <div class="form-group">
                    <label for="name">Service Name *</label>
                    <input type="text" id="name" name="name" class="form-control" required
                        value="<?php echo htmlspecialchars($edit_service['name'] ?? ''); ?>"
                        placeholder="e.g. Chimney Sweeping">
                </div>

                <div class="form-group">
                    <label for="description">Short Description</label>
                    <textarea id="description" name="description" class="form-control" style="min-height: 80px;"
                        placeholder="Brief summary for listings..."><?php echo htmlspecialchars($edit_service['description'] ?? ''); ?></textarea>
                </div>

                <div class="form-group">
                    <label for="content">Full Content *</label>
                    <div id="content-editor"
                        style="height: 400px; background: white; border-radius: 0 0 var(--radius-md) var(--radius-md);">
                        <?php echo $edit_service['content'] ?? ''; ?>
                    </div>
                    <textarea id="content" name="content"
                        style="display: none;"><?php echo htmlspecialchars($edit_service['content'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                </div>
            </div>

            <div class="right-col">
                <div class="form-group">
                    <label for="category_id">Category</label>
                    <select id="category_id" name="category_id" class="form-control">
                        <option value="">-- No Category --</option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?php echo $category['id']; ?>" <?php echo (isset($edit_service['category_id']) && $edit_service['category_id'] == $category['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label for="image">Main Image</label>
                    <?php if (!empty($edit_service['image'])): ?>
                        <div style="margin-bottom: 12px;">
                            <img src="<?php echo htmlspecialchars($edit_service['image']); ?>" alt="Current image"
                                style="width: 100%; border-radius: var(--radius-md); border: 1px solid var(--border);">
                        </div>
                    <?php endif; ?>
                    <input type="file" id="image" name="image" class="form-control" accept="image/*">
                    <input type="hidden" name="current_image"
                        value="<?php echo htmlspecialchars($edit_service['image'] ?? ''); ?>">
                </div>

                <div class="form-group">
                    <label for="url">Custom URL (Optional)</label>
                    <input type="text" id="url" name="url" class="form-control"
                        value="<?php echo htmlspecialchars($edit_service['url'] ?? ''); ?>"
                        placeholder="e.g. /services/chimney-sweep">
                </div>

                <div class="form-group">
                    <label for="display_order">Display Order</label>
                    <input type="number" id="display_order" name="display_order" class="form-control"
                        value="<?php echo $edit_service['display_order'] ?? count($services) + 1; ?>" min="0">
                </div>

                <button type="submit" class="btn btn-primary" style="width: 100%; justify-content: center;">
                    <i class="fas fa-save"></i> <?php echo $edit_service ? 'Update Service' : 'Add Service'; ?>
                </button>
            </div>
        </div>
    </form>
</div>

<div class="card">
    <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
        <h2 class="card-title">All Services (<?php echo count($services); ?>)</h2>
        <button type="submit" form="order-form" class="btn btn-secondary btn-sm">
            <i class="fas fa-sort-numeric-down"></i> Save Display Order
        </button>
    </div>

    <div class="table-responsive">
        <form id="order-form" method="POST" action="">
            <input type="hidden" name="action" value="update_order">
            <table class="table">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Service Name</th>
                        <th>Category</th>
                        <th style="width: 100px;">Order</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($services)): ?>
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 40px; color: var(--text-muted);">No services
                                found. Add your first service above.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($services as $service): ?>
                            <tr>
                                <td style="width: 80px;">
                                    <?php if (!empty($service['image'])): ?>
                                        <img src="<?php echo htmlspecialchars($service['image']); ?>" alt=""
                                            style="width: 60px; height: 60px; object-fit: cover; border-radius: var(--radius-sm);">
                                    <?php else: ?>
                                        <div
                                            style="width: 60px; height: 60px; background: var(--light); border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; color: var(--text-light);">
                                            <i class="fas fa-image"></i>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="font-weight: 700;"><?php echo htmlspecialchars($service['name']); ?></div>
                                    <div style="font-size: 12px; color: var(--text-muted);">
                                        <?php echo htmlspecialchars($service['slug']); ?>
                                    </div>
                                </td>
                                <td>
                                    <?php if (!empty($service['category_name'])): ?>
                                        <span
                                            class="badge badge-info"><?php echo htmlspecialchars($service['category_name']); ?></span>
                                    <?php else: ?>
                                        <span class="text-muted" style="font-size: 12px;">Uncategorized</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <input type="number" name="orders[<?php echo $service['id']; ?>]"
                                        value="<?php echo $service['display_order']; ?>" class="form-control form-control-sm"
                                        style="width: 70px;">
                                </td>
                                <td>
                                    <div style="display: flex; gap: 8px;">
                                        <a href="?edit=<?php echo $service['id']; ?>" class="btn btn-secondary btn-sm">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="if(confirm('Are you sure you want to delete this service?')) { 
                                                const f = document.createElement('form');
                                                f.method='POST';
                                                f.innerHTML = '<input type=\'hidden\' name=\'action\' value=\'delete\'><input type=\'hidden\' name=\'id\' value=\'<?php echo $service['id']; ?>\'>';
                                                document.body.appendChild(f);
                                                f.submit();
                                            }">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </form>
    </div>
</div>

<?php require_once 'includes/admin-footer.php'; ?>