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

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

$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
$page = max(1, $page);
$per_page = max(1, $per_page);
$offset = ($page - 1) * $per_page;

try {
    // Ensure services table exists
    $create_table = "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
    )";

    if (!$mysqli->query($create_table)) {
        throw new Exception("Failed to create services table: " . $mysqli->error);
    }

    // Migrate legacy schema variants to ensure expected columns exist.
    $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) {
            throw new Exception("Column check failed for " . $column . ": " . $mysqli->error);
        }

        if ($check->num_rows === 0) {
            if (!$mysqli->query($alter_sql)) {
                throw new Exception("Failed to add column " . $column . ": " . $mysqli->error);
            }
        }
    }

    // Backfill description from legacy short_description when available.
    $legacy_short_desc = $mysqli->query("SHOW COLUMNS FROM services LIKE 'short_description'");
    if ($legacy_short_desc && $legacy_short_desc->num_rows > 0) {
        $mysqli->query("UPDATE services SET description = short_description WHERE (description IS NULL OR description = '') AND short_description IS NOT NULL");
    }

    // Get total count
    $count_query = "SELECT COUNT(*) as total FROM services";
    $count_result = $mysqli->query($count_query);

    if (!$count_result) {
        throw new Exception("Count query failed: " . $mysqli->error);
    }

    $total = intval($count_result->fetch_assoc()['total']);

    // Get services
    $query = "SELECT id, title, description, icon, price, status, created_at FROM services ORDER BY created_at DESC LIMIT ? OFFSET ?";
    $stmt = $mysqli->prepare($query);

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

    $stmt->bind_param('ii', $per_page, $offset);

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

    $result = $stmt->get_result();
    $services = [];

    while ($row = $result->fetch_assoc()) {
        $services[] = $row;
    }

    echo json_encode([
        'success' => true,
        'services' => $services,
        'total' => $total,
        'page' => $page,
        'per_page' => $per_page,
        'total_pages' => max(1, ceil($total / $per_page))
    ]);

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

$mysqli->close();
?>
