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

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

$profile_id = $_GET['id'] ?? null;

if (!$profile_id) {
    echo json_encode(['error' => 'Profile ID is missing.']);
    exit;
}

try {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM gtm_profiles WHERE id = ?");
    $stmt->execute([$profile_id]);
    $profile = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$profile) {
        echo json_encode(['error' => 'Profile not found.']);
        exit;
    }

    // Simulate AI-powered recommendations based on profile data
    $recommendations = '<ul>';

    if (strpos(strtolower($profile['sales_motions']), 'outbound') !== false || strpos(strtolower($profile['roles']), 'sdr') !== false) {
        $recommendations .= '<li><strong>CRM:</strong> HubSpot (Integrates with SDR workflows)</li>';
    }

    if (strpos(strtolower($profile['sells_what']), 'product') !== false) {
        $recommendations .= '<li><strong>Analytics:</strong> Mixpanel (Tracks Product-led growth)</li>';
    }

    if (strpos(strtolower($profile['market_size']), 'large') !== false || strpos(strtolower($profile['market_size']), 'enterprise') !== false) {
        $recommendations .= '<li><strong>Automation:</strong> Zapier (Connects CRM to email marketing tools)</li>';
    }

    if ($recommendations === '<ul>') {
        $recommendations = '<p>No specific tool recommendations for this profile.</p>';
    } else {
        $recommendations .= '</ul>';
    }

    $update_stmt = $pdo->prepare("UPDATE gtm_profiles SET tools_text = ? WHERE id = ?");
    $update_stmt->execute([$recommendations, $profile_id]);

    echo json_encode(['recommendations' => $recommendations]);

} catch (PDOException $e) {
    error_log($e->getMessage());
    echo json_encode(['error' => 'Database error occurred.']);
}
