<?php
/**
 * Admin - Edit Service
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Edit Service';
$service_id = intval($_GET['id'] ?? 0);

$service = null;
$errors = [];

// Get service
if ($service_id) {
    try {
        $stmt = db()->prepare("SELECT * FROM services WHERE id = ?");
        $stmt->execute([$service_id]);
        $service = $stmt->fetch();
    } catch (PDOException $e) {}
}

if (!$service) {
    redirect(BASE_URL . 'admin/services.php', 'error', 'Service not found');
}

// Get categories
$categories = [];
try {
    $stmt = db()->query("SELECT * FROM service_categories WHERE status = 1 ORDER BY name");
    $categories = $stmt->fetchAll();
} catch (PDOException $e) {}

// Parse existing features
$existing_features = [];
if (!empty($service['features'])) {
    $decoded = json_decode($service['features'], true);
    if (is_array($decoded)) {
        $existing_features = $decoded;
    }
}

// Update service
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $short_description = sanitize($_POST['short_description'] ?? '');
        $category_id = intval($_POST['category_id'] ?? 0);
        $icon = sanitize($_POST['icon'] ?? 'briefcase');
        $price = floatval($_POST['price'] ?? 0);
        $button_link = sanitize($_POST['button_link'] ?? '');
        $button_text = sanitize($_POST['button_text'] ?? 'Learn More');
        $status = isset($_POST['status']) ? 1 : 0;
        
        // Process features
        $features = [];
        if (isset($_POST['features']) && is_array($_POST['features'])) {
            foreach ($_POST['features'] as $feature) {
                $feature = trim($feature);
                if (!empty($feature)) {
                    $features[] = $feature;
                }
            }
        }
        $features_json = json_encode($features);
        
        if (empty($name)) $errors[] = 'Service name is required';
        if (empty($description)) $errors[] = 'Description is required';
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("UPDATE services SET 
                    category_id = ?, name = ?, description = ?, short_description = ?, 
                    icon = ?, price_starting_from = ?, button_link = ?, button_text = ?, features = ?, status = ?, updated_at = NOW()
                    WHERE id = ?");
                $stmt->execute([$category_id, $name, $description, $short_description, $icon, $price, $button_link, $button_text, $features_json, $status, $service_id]);
                
                // Refresh service data
                $stmt = db()->prepare("SELECT * FROM services WHERE id = ?");
                $stmt->execute([$service_id]);
                $service = $stmt->fetch();
                
                // Refresh features
                $existing_features = [];
                if (!empty($service['features'])) {
                    $decoded = json_decode($service['features'], true);
                    if (is_array($decoded)) {
                        $existing_features = $decoded;
                    }
                }
                
                $success = 'Service updated successfully';
            } catch (PDOException $e) {
                error_log("Service update error: " . $e->getMessage());
                $errors[] = 'Failed to update service: ' . $e->getMessage();
            }
        }
    }
}

$csrf_token = generate_csrf_token();

include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Edit Service</h2>
    <a href="services.php" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-2"></i>Back
    </a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <?php foreach ($errors as $error): ?>
            <p class="mb-0"><?php echo $error; ?></p>
        <?php endforeach; ?>
    </div>
<?php endif; ?>
<?php if (isset($success)): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Service Name <span class="text-danger">*</span></label>
                    <input type="text" name="name" class="form-control" value="<?php echo $service['name']; ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Category</label>
                    <select name="category_id" class="form-select">
                        <option value="">Select Category</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo $service['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                            <?php echo $cat['name']; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Icon (Bootstrap Icon name)</label>
                    <input type="text" name="icon" class="form-control" value="<?php echo $service['icon']; ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Price (0 for free/contact)</label>
                    <input type="number" name="price" class="form-control" step="0.01" value="<?php echo $service['price_starting_from'] ?? 0; ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Button Text</label>
                    <input type="text" name="button_text" class="form-control" value="<?php echo $service['button_text'] ?? 'Learn More'; ?>" placeholder="e.g., Learn More, Get Started">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Button Link (URL)</label>
                    <input type="text" name="button_link" class="form-control" value="<?php echo $service['button_link'] ?? ''; ?>" placeholder="e.g., contact.php or https://example.com">
                    <small class="text-muted">Leave empty for default service page</small>
                </div>
                <div class="col-12">
                    <label class="form-label">Short Description</label>
                    <input type="text" name="short_description" class="form-control" value="<?php echo $service['short_description']; ?>">
                </div>
                <div class="col-12">
                    <label class="form-label">Full Description <span class="text-danger">*</span></label>
                    <textarea name="description" class="form-control" rows="6" required><?php echo $service['description']; ?></textarea>
                </div>
                
                <!-- Features Section -->
                <div class="col-12">
                    <label class="form-label">Features / Bullet Points</label>
                    <div id="features-container">
                        <?php 
                        $feature_count = count($existing_features);
                        if ($feature_count === 0) $feature_count = 1;
                        for ($i = 0; $i < $feature_count; $i++): 
                            $feature = $existing_features[$i] ?? '';
                        ?>
                        <div class="input-group mb-2 feature-row">
                            <span class="input-group-text"><i class="bi bi-check-circle text-success"></i></span>
                            <input type="text" name="features[]" class="form-control" value="<?php echo $feature; ?>" placeholder="Enter feature or bullet point">
                            <button type="button" class="btn btn-outline-danger remove-feature" onclick="this.closest('.feature-row').remove()">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                        <?php endfor; ?>
                    </div>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="addFeatureRow()">
                        <i class="bi bi-plus-circle me-1"></i>Add Feature
                    </button>
                    <small class="text-muted d-block mt-1">Add bullet points or features that will be displayed on the service card</small>
                </div>
                
                <div class="col-12">
                    <div class="form-check">
                        <input type="checkbox" name="status" class="form-check-input" id="statusCheck" <?php echo $service['status'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="statusCheck">Active</label>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save me-2"></i>Update Service
                </button>
                <a href="services.php" class="btn btn-outline-secondary ms-2">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
function addFeatureRow() {
    const container = document.getElementById('features-container');
    const row = document.createElement('div');
    row.className = 'input-group mb-2 feature-row';
    row.innerHTML = `
        <span class="input-group-text"><i class="bi bi-check-circle text-success"></i></span>
        <input type="text" name="features[]" class="form-control" placeholder="Enter feature or bullet point">
        <button type="button" class="btn btn-outline-danger remove-feature" onclick="this.closest('.feature-row').remove()">
            <i class="bi bi-trash"></i>
        </button>
    `;
    container.appendChild(row);
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
