<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

try {
    // Optional Auth check, maybe public?
    // $user_id = Auth::check(); // Let's keep it open for now or check token if provided

    $category = $_GET['category'] ?? 'all';
    
    // Check table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS mk_services (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        title VARCHAR(255) NOT NULL,
        price INT NOT NULL,
        category VARCHAR(50) DEFAULT 'General',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        rating FLOAT DEFAULT 0,
        FOREIGN KEY (user_id) REFERENCES users(id)
    )");

    $sql = "SELECT s.*, u.username as user FROM mk_services s JOIN users u ON s.user_id = u.id";
    if ($category !== 'all') {
        $sql .= " WHERE s.category = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$category]);
    } else {
        $stmt = $pdo->query($sql);
    }
    
    $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['status' => 'success', 'services' => $services]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
