<?php
require_once '../includes/config.php';
requireAuth();
require_once '../includes/functions.php';

$service = ['title' => '', 'description' => '', 'icon' => '', 'image_url' => ''];
$isEdit = false;

if (isset($_GET['id'])) {
    $service = getService($_GET['id']);
    $isEdit = true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'title' => $_POST['title'],
        'description' => $_POST['description'],
        'icon' => $_POST['icon'],
        'image_url' => $_POST['image_url'] ?? '',
        'features' => $_POST['features'] ?? [] // Add this line to collect features
    ];
    
    // Filter out empty feature strings
    $data['features'] = array_filter($data['features'], function($feature) {
        return !empty(trim($feature));
    });
    
    // Handle image upload
    if (!empty($_FILES['image']['name'])) {
        $upload = uploadImage($_FILES['image']);
        if ($upload['success']) {
            $data['image_url'] = $upload['file'];
        } else {
            $error = $upload['message'];
        }
    }
    
    // Handle image removal
    if (!empty($_POST['remove_image'])) {
        $data['image_url'] = '';
    }
    
    if (empty($error)) {
        if ($isEdit) {
            $success = saveService($data, $_GET['id']);
        } else {
            $success = saveService($data);
        }
        
        if ($success) {
            header("Location: services.php?success=Service+" . ($isEdit ? "updated" : "created"));
            exit;
        } else {
            $error = "Error saving service";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $isEdit ? 'Edit' : 'Add' ?> Service - <?= SITE_NAME ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #1a5276;
            --secondary: #2980b9;
            --accent: #e67e22;
            --light: #ecf0f1;
            --dark: #2c3e50;
            --success: #27ae60;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: 250px;
            background-color: var(--primary);
            color: white;
            padding: 20px 0;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }
        
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        
        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .sidebar-menu {
            padding: 20px 0;
        }
        
        .sidebar-menu a {
            display: block;
            padding: 10px 20px;
            color: white;
            text-decoration: none;
            transition: background-color 0.3s;
        }
        
        .sidebar-menu a:hover, 
        .sidebar-menu a.active {
            background-color: rgba(255, 255, 255, 0.1);
        }
        
        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .form-control, .form-select {
            border-radius: 5px;
            padding: 10px;
            border: 1px solid #ced4da;
        }
        
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.25rem rgba(26, 82, 118, 0.25);
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 5px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background-color: var(--primary);
            border-color: var(--primary);
        }
        
        .btn-primary:hover {
            background-color: var(--secondary);
            border-color: var(--secondary);
        }
        
        .btn-secondary {
            background-color: #6c757d;
            border-color: #6c757d;
        }
        
        .preview-image {
            max-height: 200px;
            margin-top: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
            padding: 5px;
            background: white;
        }
        
        .alert {
            border-radius: 5px;
        }
        
        .breadcrumb {
            background-color: transparent;
            padding: 0;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                height: auto;
            }
            
            .main-content {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header">
            <h4><?= SITE_NAME ?></h4>
            <p class="mb-0">Admin Dashboard</p>
        </div>
        <div class="sidebar-menu">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="services.php" class="active"><i class="fas fa-tools"></i> Services</a>
            <a href="projects.php"><i class="fas fa-project-diagram"></i> Projects</a>
            <a href="gallery.php"><i class="fas fa-images"></i> Gallery</a>
            <a href="users.php"><i class="fas fa-users"></i> Users</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="services.php">Services</a></li>
                <li class="breadcrumb-item active" aria-current="page"><?= $isEdit ? 'Edit' : 'Add' ?> Service</li>
            </ol>
        </nav>
        
        <h1 class="mb-4"><?= $isEdit ? 'Edit' : 'Add' ?> Service</h1>
        
        <?php if (isset($error)): ?>
        <div class="alert alert-danger mb-4"><?= $error ?></div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Service Details</h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="title" class="form-label">Title *</label>
                        <input type="text" class="form-control" id="title" name="title" 
                               value="<?= htmlspecialchars($service['title']) ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">Description *</label>
                        <textarea class="form-control" id="description" name="description" 
                                  rows="5" required><?= htmlspecialchars($service['description']) ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="icon" class="form-label">Icon (Font Awesome class)</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="icon" name="icon" 
                                   value="<?= htmlspecialchars($service['icon']) ?>" 
                                   placeholder="fas fa-hammer">
                            <button class="btn btn-outline-secondary" type="button" data-bs-toggle="modal" data-bs-target="#iconModal">
                                <i class="fas fa-icons"></i> Select Icon
                            </button>
                        </div>
                        <small class="text-muted">Use Font Awesome icon classes (e.g., fas fa-hammer)</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="image" class="form-label">Image</label>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*">
                        <?php if (!empty($service['image_url'])): ?>
                        <div class="mt-3">
                            <p class="mb-1">Current Image:</p>
                            <img src="../<?= $service['image_url'] ?>" class="preview-image" id="imagePreview">
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" id="removeImage" name="remove_image">
                                <label class="form-check-label" for="removeImage">
                                    Remove current image
                                </label>
                            </div>
                            <input type="hidden" name="image_url" value="<?= $service['image_url'] ?>">
                        </div>
                        <?php else: ?>
                        <div class="mt-3">
                            <img src="" class="preview-image d-none" id="imagePreview">
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="mb-4">
    <h5>Service Features</h5>
    <div id="features-container">
        <?php 
        $serviceFeatures = [];
        if ($isEdit) {
            $stmt = $pdo->prepare("SELECT * FROM service_features WHERE service_id = ? ORDER BY sort_order");
            $stmt->execute([$_GET['id']]);
            $serviceFeatures = $stmt->fetchAll();
        }
        
        if (empty($serviceFeatures)) {
            // Add 3 empty feature fields by default
            $serviceFeatures = array_fill(0, 3, ['feature_text' => '']);
        }
        
        foreach ($serviceFeatures as $index => $feature): ?>
        <div class="feature-field mb-2 input-group">
            <input type="text" class="form-control" name="features[]" 
                   value="<?= htmlspecialchars($feature['feature_text']) ?>" 
                   placeholder="Feature description">
            <button type="button" class="btn btn-outline-danger remove-feature" <?= $index < 3 ? 'disabled' : '' ?>>
                <i class="fas fa-times"></i>
            </button>
        </div>
        <?php endforeach; ?>
    </div>
    <button type="button" id="add-feature" class="btn btn-sm btn-secondary mt-2">
        <i class="fas fa-plus"></i> Add Feature
    </button>
</div>
                    <div class="d-flex justify-content-end mt-4">
                        <a href="services.php" class="btn btn-secondary me-2">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-1"></i> Save Service
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Icon Selection Modal -->
    <div class="modal fade" id="iconModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Select Icon</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <?php 
                        $icons = [
                            'fas fa-hammer', 'fas fa-tools', 'fas fa-hard-hat', 'fas fa-building',
                            'fas fa-truck', 'fas fa-helmet-safety', 'fas fa-ruler-combined',
                            'fas fa-paint-roller', 'fas fa-screwdriver', 'fas fa-wrench'
                        ];
                        
                        foreach ($icons as $icon): ?>
                        <div class="col-3 col-md-2 mb-3 text-center">
                            <button type="button" class="btn btn-outline-primary w-100 icon-select" data-icon="<?= $icon ?>">
                                <i class="<?= $icon ?> fa-2x mb-2"></i><br>
                                <small><?= substr($icon, 7) ?></small>
                            </button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Icon selection
        document.querySelectorAll('.icon-select').forEach(button => {
            button.addEventListener('click', function() {
                document.getElementById('icon').value = this.dataset.icon;
                var modal = bootstrap.Modal.getInstance(document.getElementById('iconModal'));
                modal.hide();
            });
        });
        
        // Image preview
        document.getElementById('image').addEventListener('change', function() {
            const preview = document.getElementById('imagePreview');
            const file = this.files[0];
            const reader = new FileReader();
            
            preview.classList.remove('d-none');
            
            reader.onloadend = function() {
                preview.src = reader.result;
            }
            
            if (file) {
                reader.readAsDataURL(file);
            } else {
                preview.src = "";
                preview.classList.add('d-none');
            }
        });
        // Feature management
// Feature management
document.addEventListener('DOMContentLoaded', function() {
    // Add feature
    document.getElementById('add-feature').addEventListener('click', function() {
        const container = document.getElementById('features-container');
        const div = document.createElement('div');
        div.className = 'feature-field mb-2 input-group';
        div.innerHTML = `
            <input type="text" class="form-control" name="features[]" placeholder="Feature description">
            <button type="button" class="btn btn-outline-danger remove-feature">
                <i class="fas fa-times"></i>
            </button>
        `;
        container.appendChild(div);
    });

    // Remove feature
    document.getElementById('features-container').addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-feature') || 
            e.target.closest('.remove-feature')) {
            const featureField = e.target.closest('.feature-field');
            if (featureField) {
                // Don't allow removing the first 3 features
                const allFeatures = document.querySelectorAll('.feature-field');
                if (allFeatures.length > 3) {
                    featureField.remove();
                }
            }
        }
    });
});

document.addEventListener('click', function(e) {
    if (e.target.classList.contains('remove-feature')) {
        e.target.closest('.feature-field').remove();
    }
});
    </script>
</body>
</html>