<?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 add services']);
    exit;
}

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

$input = json_decode(file_get_contents('php://input'), true);
$title = trim($input['title'] ?? '');
$description = trim($input['description'] ?? '');
$icon = trim($input['icon'] ?? 'fas fa-cogs');
$price = floatval($input['price'] ?? 0);
$status = trim($input['status'] ?? 'active');

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

try {
    // Ensure expected schema columns exist
    $mysqli->query("CREATE TABLE IF NOT EXISTS services (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        description TEXT,
        icon VARCHAR(100),
        price DECIMAL(10, 2),
        status VARCHAR(50) DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");

    $column_checks = [
        'description' => "ALTER TABLE services ADD COLUMN description TEXT",
        'price' => "ALTER TABLE services ADD COLUMN price DECIMAL(10,2) DEFAULT 0",
        'status' => "ALTER TABLE services ADD COLUMN status VARCHAR(50) DEFAULT 'active'"
    ];

    foreach ($column_checks as $column => $alter_sql) {
        $check = $mysqli->query("SHOW COLUMNS FROM services LIKE '" . $column . "'");
        if ($check && $check->num_rows === 0) {
            $mysqli->query($alter_sql);
        }
    }

    $stmt = $mysqli->prepare("INSERT INTO services (title, description, icon, price, status) VALUES (?, ?, ?, ?, ?)");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }

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

    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Service added successfully',
            'service_id' => $stmt->insert_id
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add service']);
    }

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

$mysqli->close();
?>
