<?php
require_once '../config.php';
require_once '../lib.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get all active wellness services
        $stmt = $pdo->prepare("
            SELECT id, name, slug, description, short_description, icon, color, position_angle
            FROM wellness_services 
            WHERE is_active = TRUE 
            ORDER BY position_angle ASC
        ");
        $stmt->execute();
        $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Submit service inquiry
        $input = json_decode(file_get_contents('php://input'), true);
        
        $required = ['service_id', 'name', 'email', 'message'];
        foreach ($required as $field) {
            if (empty($input[$field])) {
                throw new Exception("$field is required");
            }
        }

        // Get user ID if logged in
        $user_id = null;
        $token = $_COOKIE['auth_token'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? null;
        if ($token) {
            $user_id = getUserIdFromToken($token);
        }

        $stmt = $pdo->prepare("
            INSERT INTO service_inquiries (service_id, user_id, name, email, phone, message, preferred_contact)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $input['service_id'],
            $user_id,
            $input['name'],
            $input['email'],
            $input['phone'] ?? null,
            $input['message'],
            $input['preferred_contact'] ?? 'email'
        ]);

        echo json_encode([
            'success' => true,
            'message' => 'Inquiry submitted successfully'
        ]);
    }

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