<?php
/**
 * EcoBe Job Search Proxy — Cliente PHP para Python Scraper API
 * 
 * Arquitetura:
 * PHP (este arquivo) -> Python VPS (cloudscraper) -> Sites de emprego
 * 
 * Vantagens:
 * - Bypassa Cloudflare automaticamente
 * - Não precisa de proxies pagos
 * - Funciona com Indeed, Glassdoor, etc
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$action   = $_GET['action']   ?? '';
$query    = $_GET['q']        ?? 'marketing manager';
$location = $_GET['location'] ?? 'Portugal';
$id       = $_GET['id']       ?? '';
$source   = $_GET['source']   ?? 'linkedin';

// ══════════════════════════════════════════════════════════════════════════════
// CONFIGURAÇÃO - Coloque o IP/domínio do seu VPS Python aqui
// ══════════════════════════════════════════════════════════════════════════════

$PYTHON_API_URL = 'http://SEU_VPS_IP:5000';  // Ex: http://45.76.123.45:5000

// ══════════════════════════════════════════════════════════════════════════════

function callPythonAPI($endpoint, $params = []) {
  global $PYTHON_API_URL;
  
  $url = $PYTHON_API_URL . $endpoint;
  if (!empty($params)) {
    $url .= '?' . http_build_query($params);
  }
  
  $ch = curl_init();
  curl_setopt_array($ch, [
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_CONNECTTIMEOUT => 10,
  ]);
  
  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $error    = curl_error($ch);
  curl_close($ch);
  
  if ($httpCode !== 200 || $error) {
    return [
      'error' => 'Failed to connect to scraper API',
      'details' => $error,
      'http_code' => $httpCode
    ];
  }
  
  return json_decode($response, true) ?: ['error' => 'Invalid response'];
}

// ══════════════════════════════════════════════════════════════════════════════
// ENDPOINTS
// ══════════════════════════════════════════════════════════════════════════════

if ($action === 'search') {
  
  $result = callPythonAPI('/search', [
    'q'        => $query,
    'location' => $location,
    'sources'  => 'all', // ou: 'linkedin,indeed,glassdoor'
  ]);
  
  echo json_encode($result, JSON_PRETTY_PRINT);
  
} elseif ($action === 'detail') {
  
  if (empty($id)) {
    echo json_encode(['error' => 'Missing job ID']);
    exit;
  }
  
  $result = callPythonAPI('/detail', [
    'id'     => $id,
    'source' => $source,
  ]);
  
  echo json_encode($result, JSON_PRETTY_PRINT);
  
} elseif ($action === 'health') {
  
  // Testar se Python API está online
  $result = callPythonAPI('/health');
  echo json_encode($result, JSON_PRETTY_PRINT);
  
} else {
  
  echo json_encode([
    'error' => 'Invalid action',
    'usage' => [
      'search' => '?action=search&q=marketing&location=Portugal',
      'detail' => '?action=detail&id=123456&source=linkedin',
      'health' => '?action=health',
    ]
  ], JSON_PRETTY_PRINT);
  
}