<?php
require_once __DIR__ . '/../config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized. Only admins can update services']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['service_id']) || empty($data['service_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Service ID is required']);
    exit;
}

if (!isset($data['title']) || trim($data['title']) === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Service title is required']);
    exit;
}

$service_id = intval($data['service_id']);
$title = trim($data['title']);
$description = trim($data['description'] ?? '');
$icon = trim($data['icon'] ?? 'fas fa-cogs');
$price = floatval($data['price'] ?? 0);
$status = trim($data['status'] ?? 'active');

try {
    $stmt = $mysqli->prepare(
        "UPDATE services SET title = ?, description = ?, icon = ?, price = ?, status = ? WHERE id = ?"
    );

    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }

    $stmt->bind_param('sssdsi', $title, $description, $icon, $price, $status, $service_id);

    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    echo json_encode([
        'success' => true,
        'message' => ($stmt->affected_rows > 0) ? 'Service updated successfully' : 'No changes made'
    ]);

    $stmt->close();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error updating service: ' . $e->getMessage()
    ]);
}

$mysqli->close();
?>
