<?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 (!file_exists($service_php_file)) {
    echo json_encode(['success' => false, 'message' => 'Service PHP file not found']);
    exit;
}

if ($action === 'add_service') {
    $title = $_POST['title'] ?? '';
    $image = $_POST['image'] ?? '';
    $link = $_POST['link'] ?? '#';
    $description = $_POST['description'] ?? '';

    if (!$title || !$image || !$description) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit;
    }

    $html_content = file_get_contents($service_file);

    // Count existing services to get the right delay
    $service_count = substr_count($html_content, 'class="col-md-6 col-xl-4"');
    $delay = ($service_count % 9) + 1;
    
    // Create new service HTML with proper formatting
    $new_service = '                <div class="col-md-6 col-xl-4">
                    <div class="service-box wow fadeInUp" data-wow-delay=".' . $delay . 's">
                        <div class="box-img global-img"><img src="' . htmlspecialchars($image) . '" alt="' . htmlspecialchars($title) . '"></div>
                        <div class="box-content">
                            <h3 class="box-title"><a href="' . htmlspecialchars($link) . '">' . htmlspecialchars($title) . '</a></h3>
                            <p class="box-text">
                                ' . htmlspecialchars($description) . '
                            </p>
                            <a href="' . htmlspecialchars($link) . '" class="line-btn">More Information</a>
                        </div>
                    </div>
                </div>';
    
    // Find the closing row div before the container closing
    if (preg_match('/(\s*<\/div>\s*<\/div>\s*<\/section>)/m', $html_content, $matches)) {
        $replacement = "\n" . $new_service . $matches[1];
        $updated_content = preg_replace('/(\s*<\/div>\s*<\/div>\s*<\/section>)/m', $replacement, $html_content, 1);
        
        if (file_put_contents($service_file, $updated_content)) {
            // Also update service.php
            $php_content = file_get_contents($service_php_file);
            if (preg_match('/(\s*<\/div>\s*<\/div>\s*<\/section>)/m', $php_content, $matches)) {
                $replacement = "\n" . $new_service . $matches[1];
                $updated_php_content = preg_replace('/(\s*<\/div>\s*<\/div>\s*<\/section>)/m', $replacement, $php_content, 1);
                
                if (file_put_contents($service_php_file, $updated_php_content)) {
                    echo json_encode(['success' => true, 'message' => 'Service added successfully']);
                } else {
                    echo json_encode(['success' => true, 'message' => 'Service added but service.php update failed']);
                }
            } else {
                echo json_encode(['success' => true, 'message' => 'Service added but could not locate service section in service.php']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to write to service file']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Could not locate service section']);
    }
    
} else if ($action === 'update_service') {
    $service_index = intval($_POST['service_index'] ?? 0);
    $title = $_POST['title'] ?? '';
    $image = $_POST['image'] ?? '';
    $description = $_POST['description'] ?? '';

    if ($service_index < 0 || !$title || !$image || !$description) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit;
    }

    $html_content = file_get_contents($service_file);
    
    // Find all service col-md-6 containers (not just the box content)
    if (preg_match_all('/(<div class="col-md-6 col-xl-4">\s*<div class="service-box[^>]*>\s*<div class="box-img[^>]*><img src="[^"]*" alt="[^"]*"><\/div>\s*<div class="box-content">\s*<h3 class="box-title"><a href="[^"]*">[^<]*<\/a><\/h3>\s*<p class="box-text">[^<]*(?:<[^>]*>[^<]*)*?<\/p>\s*<a href="[^"]*" class="line-btn">[^<]*<\/a>\s*<\/div>\s*<\/div>\s*<\/div>)/s', $html_content, $matches)) {
        
        if ($service_index < count($matches[0])) {
            // Build the replacement HTML with proper formatting
            $replacement = '                <div class="col-md-6 col-xl-4">
                    <div class="service-box wow fadeInUp" data-wow-delay=".' . ($service_index + 1) . 's">
                        <div class="box-img global-img"><img src="' . htmlspecialchars($image) . '" alt="' . htmlspecialchars($title) . '"></div>
                        <div class="box-content">
                            <h3 class="box-title"><a href="#">' . htmlspecialchars($title) . '</a></h3>
                            <p class="box-text">
                                ' . htmlspecialchars($description) . '
                            </p>
                            <a href="#" class="line-btn">More Information</a>
                        </div>
                    </div>
                </div>';
            
            $updated_content = str_replace($matches[0][$service_index], $replacement, $html_content);
            
            if (file_put_contents($service_file, $updated_content)) {
                // Also update service.php
                $php_content = file_get_contents($service_php_file);
                if (preg_match_all('/(<div class="col-md-6 col-xl-4">\s*<div class="service-box[^>]*>\s*<div class="box-img[^>]*><img src="[^"]*" alt="[^"]*"><\/div>\s*<div class="box-content">\s*<h3 class="box-title"><a href="[^"]*">[^<]*<\/a><\/h3>\s*<p class="box-text">[^<]*(?:<[^>]*>[^<]*)*?<\/p>\s*<a href="[^"]*" class="line-btn">[^<]*<\/a>\s*<\/div>\s*<\/div>\s*<\/div>)/s', $php_content, $php_matches)) {
                    if ($service_index < count($php_matches[0])) {
                        $updated_php_content = str_replace($php_matches[0][$service_index], $replacement, $php_content);
                        if (file_put_contents($service_php_file, $updated_php_content)) {
                            echo json_encode(['success' => true, 'message' => 'Service updated successfully']);
                        } else {
                            echo json_encode(['success' => true, 'message' => 'Service updated but service.php update failed']);
                        }
                    } else {
                        echo json_encode(['success' => true, 'message' => 'Service updated but service.php service index out of range']);
                    }
                } else {
                    echo json_encode(['success' => true, 'message' => 'Service updated but could not parse service.php services']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update service file']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Service index out of range']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Could not parse services']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}

