<?php
session_start();

// Check if user is admin
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$action = $_POST['action'] ?? '';
$service_file = __DIR__ . '/../service.html';
$service_php_file = __DIR__ . '/../service.php';

if (!file_exists($service_file)) {
    echo json_encode(['success' => false, 'message' => 'Service file not found']);
    exit;
}

if ($action === 'delete_service') {
    $service_index = intval($_POST['service_index'] ?? -1);
    $service_title = $_POST['service_title'] ?? '';

    if ($service_index < 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid service index']);
        exit;
    }

    $html_content = file_get_contents($service_file);
    
    // Extract all service boxes
    if (!preg_match_all('/<div class="col-md-6 col-xl-4">.*?<div class="service-box.*?<\/div>\s*<\/div>/s', $html_content, $matches)) {
        echo json_encode(['success' => false, 'message' => 'Could not locate services in HTML file']);
        exit;
    }

    // Check if service index is valid
    if ($service_index >= count($matches[0])) {
        echo json_encode(['success' => false, 'message' => 'Service not found']);
        exit;
    }

    // Remove the specific service from HTML content
    $service_to_delete = $matches[0][$service_index];
    $updated_content = str_replace($service_to_delete, '', $html_content);

    // Write back to service.html
    if (!file_put_contents($service_file, $updated_content)) {
        echo json_encode(['success' => false, 'message' => 'Failed to update service.html']);
        exit;
    }

    // Also update service.php if it exists
    if (file_exists($service_php_file)) {
        $php_content = file_get_contents($service_php_file);
        
        if (preg_match_all('/<div class="col-md-6 col-xl-4">.*?<div class="service-box.*?<\/div>\s*<\/div>/s', $php_content, $php_matches)) {
            if ($service_index < count($php_matches[0])) {
                $service_to_delete_php = $php_matches[0][$service_index];
                $updated_php_content = str_replace($service_to_delete_php, '', $php_content);
                
                if (!file_put_contents($service_php_file, $updated_php_content)) {
                    echo json_encode(['success' => true, 'message' => 'Service deleted from HTML but failed to update service.php']);
                    exit;
                }
            }
        }
    }

    echo json_encode(['success' => true, 'message' => 'Service deleted successfully from both files']);
    
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
