<?php
/**
 * Services Management
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $id = intval($_POST['id'] ?? 0);
    
    $title = sanitizeInput($_POST['title'] ?? '');
    $shortDescription = sanitizeInput($_POST['short_description'] ?? '');
    $fullDescription = sanitizeInput($_POST['full_description'] ?? '');
    $iconClass = sanitizeInput($_POST['icon_class'] ?? '');
    $iconType = sanitizeInput($_POST['icon_type'] ?? 'fontawesome');
    $color = sanitizeInput($_POST['color'] ?? '#FF6B35');
    $category = sanitizeInput($_POST['category'] ?? '');
    $features = sanitizeInput($_POST['features'] ?? '[]');
    $displayOrder = intval($_POST['display_order'] ?? 0);
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    // Handle image upload
    $imageUrl = null;
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (in_array($_FILES['image']['type'], $allowedTypes)) {
            $uploadDir = __DIR__ . '/../uploads/services/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '_' . time() . '.' . $extension;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $filename)) {
                $imageUrl = $filename;
            }
        }
    }
    
    if (empty($title)) {
        $message = 'Title is required.';
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO services (title, short_description, full_description, icon_class, icon_type, 
                color, category, features, image_url, display_order, status) 
                VALUES (:title, :short_desc, :full_desc, :icon, :icon_type, :color, :category, 
                :features, :image, :order, :status)
            ");
            $stmt->execute([
                ':title' => $title,
                ':short_desc' => $shortDescription,
                ':full_desc' => $fullDescription,
                ':icon' => $iconClass,
                ':icon_type' => $iconType,
                ':color' => $color,
                ':category' => $category,
                ':features' => $features,
                ':image' => $imageUrl,
                ':order' => $displayOrder,
                ':status' => $status
            ]);
            $message = 'Service created successfully!';
        } else {
            if ($imageUrl) {
                // Delete old image
                $oldStmt = $pdo->prepare("SELECT image_url FROM services WHERE id = :id");
                $oldStmt->execute([':id' => $id]);
                $oldImage = $oldStmt->fetchColumn();
                if ($oldImage && file_exists(__DIR__ . '/../uploads/services/' . $oldImage)) {
                    unlink(__DIR__ . '/../uploads/services/' . $oldImage);
                }
                $stmt = $pdo->prepare("
                    UPDATE services SET title = :title, short_description = :short_desc, 
                    full_description = :full_desc, icon_class = :icon, icon_type = :icon_type,
                    color = :color, category = :category, features = :features, 
                    image_url = :image, display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':title' => $title, ':short_desc' => $shortDescription,
                    ':full_desc' => $fullDescription, ':icon' => $iconClass,
                    ':icon_type' => $iconType, ':color' => $color,
                    ':category' => $category, ':features' => $features,
                    ':image' => $imageUrl, ':order' => $displayOrder,
                    ':status' => $status, ':id' => $id
                ]);
            } else {
                $stmt = $pdo->prepare("
                    UPDATE services SET title = :title, short_description = :short_desc, 
                    full_description = :full_desc, icon_class = :icon, icon_type = :icon_type,
                    color = :color, category = :category, features = :features, 
                    display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':title' => $title, ':short_desc' => $shortDescription,
                    ':full_desc' => $fullDescription, ':icon' => $iconClass,
                    ':icon_type' => $iconType, ':color' => $color,
                    ':category' => $category, ':features' => $features,
                    ':order' => $displayOrder, ':status' => $status, ':id' => $id
                ]);
            }
            $message = 'Service updated successfully!';
        }
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT image_url FROM services WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $image = $stmt->fetchColumn();
    if ($image && file_exists(__DIR__ . '/../uploads/services/' . $image)) {
        unlink(__DIR__ . '/../uploads/services/' . $image);
    }
    $pdo->prepare("DELETE FROM services WHERE id = :id")->execute([':id' => $id]);
    $message = 'Service deleted successfully!';
}

// Get edit item
$editItem = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM services WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $editItem = $stmt->fetch();
}

// Get all services
$services = $pdo->query("
    SELECT * FROM services ORDER BY display_order ASC, created_at DESC
")->fetchAll();

$pageTitle = 'Services';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <?php 
    $GLOBALS['pdo'] = $pdo;
    include 'includes/sidebar.php'; 
    ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <!-- Add/Edit Form -->
            <div class="card slide-up">
                <div class="card-header">
                    <h3 class="card-title"><?php echo $editItem ? 'Edit Service' : 'Add New Service'; ?></h3>
                </div>
                <form method="POST" enctype="multipart/form-data" style="padding: 1.5rem;">
                    <input type="hidden" name="action" value="<?php echo $editItem ? 'update' : 'create'; ?>">
                    <?php if ($editItem): ?>
                        <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
                    <?php endif; ?>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Service Title *</label>
                            <input type="text" name="title" class="form-control" required
                                   value="<?php echo htmlspecialchars($editItem['title'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Category</label>
                            <input type="text" name="category" class="form-control"
                                   value="<?php echo htmlspecialchars($editItem['category'] ?? ''); ?>"
                                   placeholder="e.g., Survey, Drilling, Solar">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Short Description</label>
                        <textarea name="short_description" class="form-control" rows="2"><?php echo htmlspecialchars($editItem['short_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Full Description</label>
                        <textarea name="full_description" class="form-control" rows="4"><?php echo htmlspecialchars($editItem['full_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Icon Class (Font Awesome)</label>
                            <input type="text" name="icon_class" class="form-control"
                                   value="<?php echo htmlspecialchars($editItem['icon_class'] ?? ''); ?>"
                                   placeholder="e.g., fa-search-location">
                            <small style="color: var(--text-secondary);">Use Font Awesome class names</small>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Icon Type</label>
                            <select name="icon_type" class="form-control">
                                <option value="fontawesome" <?php echo ($editItem['icon_type'] ?? 'fontawesome') === 'fontawesome' ? 'selected' : ''; ?>>Font Awesome</option>
                                <option value="material" <?php echo ($editItem['icon_type'] ?? '') === 'material' ? 'selected' : ''; ?>>Material Icons</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Color</label>
                            <input type="color" name="color" class="form-control"
                                   value="<?php echo htmlspecialchars($editItem['color'] ?? '#FF6B35'); ?>"
                                   style="height: 40px;">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Features (JSON Array)</label>
                        <textarea name="features" class="form-control" rows="3"><?php echo htmlspecialchars($editItem['features'] ?? '[]'); ?></textarea>
                        <small style="color: var(--text-secondary);">Format: ["Feature 1", "Feature 2", "Feature 3"]</small>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Service Image</label>
                            <input type="file" name="image" accept="image/jpeg,image/png,image/webp" class="form-control">
                            <?php if ($editItem && $editItem['image_url']): ?>
                                <div style="margin-top: 0.5rem;">
                                    <img src="../uploads/services/<?php echo htmlspecialchars($editItem['image_url']); ?>" 
                                         alt="Current image" style="max-width: 200px; border-radius: var(--radius-md);">
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                            <div class="form-group">
                                <label class="form-label">Display Order</label>
                                <input type="number" name="display_order" class="form-control"
                                       value="<?php echo $editItem['display_order'] ?? 0; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-control">
                                    <option value="active" <?php echo ($editItem['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo ($editItem['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-top: 1.5rem;">
                        <button type="submit" class="btn btn-primary">
                            <?php echo $editItem ? 'Update Service' : 'Create Service'; ?>
                        </button>
                        <?php if ($editItem): ?>
                            <a href="services.php" class="btn btn-secondary">Cancel</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
            
            <!-- Services List -->
            <div class="card slide-up" style="animation-delay: 0.1s; margin-top: 1.5rem;">
                <div class="card-header">
                    <h3 class="card-title">All Services (<?php echo count($services); ?>)</h3>
                </div>
                <div style="overflow-x: auto;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Icon</th>
                                <th>Title</th>
                                <th>Category</th>
                                <th>Order</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($services as $service): ?>
                            <tr>
                                <td>
                                    <?php if ($service['icon_class']): ?>
                                        <i class="<?php echo htmlspecialchars($service['icon_class']); ?>" 
                                           style="font-size: 1.5rem; color: <?php echo htmlspecialchars($service['color']); ?>;"></i>
                                    <?php else: ?>
                                        <span style="font-size: 1.5rem;">—</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($service['title']); ?></td>
                                <td><?php echo htmlspecialchars($service['category'] ?? '—'); ?></td>
                                <td><?php echo $service['display_order']; ?></td>
                                <td>
                                    <span class="badge badge-<?php echo $service['status'] === 'active' ? 'success' : 'danger'; ?>">
                                        <?php echo ucfirst($service['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 0.5rem;">
                                        <a href="?edit=<?php echo $service['id']; ?>" class="btn btn-primary" style="padding: 0.375rem 0.75rem; font-size: 0.875rem;">Edit</a>
                                        <a href="?delete=<?php echo $service['id']; ?>" 
                                           class="btn" 
                                           style="padding: 0.375rem 0.75rem; font-size: 0.875rem; background: var(--danger-color, #EF4444); color: white;"
                                           onclick="return confirm('Are you sure you want to delete this service?')">Delete</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

