<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);

header('Content-Type: application/json; charset=utf-8');

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowed_origins = ['http://localhost:5000', 'http://0.0.0.0:5000', 'http://127.0.0.1:5000'];
if (in_array($origin, $allowed_origins) || strpos($origin, '.replit.dev') !== false || strpos($origin, '.repl.co') !== false) {
    header("Access-Control-Allow-Origin: $origin");
    header('Access-Control-Allow-Credentials: true');
} else {
    header('Access-Control-Allow-Origin: *');
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

// Database configuration - PostgreSQL (Replit) or MySQL (cPanel)
$database_url = getenv('DATABASE_URL');

if ($database_url) {
    $parsed = parse_url($database_url);
    $scheme = $parsed['scheme'] ?? 'mysql';
    $host = $parsed['host'] ?? 'localhost';
    $port = $parsed['port'] ?? ($scheme === 'postgres' || $scheme === 'postgresql' ? 5432 : 3306);
    $dbname = ltrim($parsed['path'] ?? '', '/');
    $user = $parsed['user'] ?? 'root';
    $password = $parsed['pass'] ?? '';
    
    // Determine driver based on scheme
    if ($scheme === 'postgres' || $scheme === 'postgresql') {
        $dsn = "pgsql:host=$host;port=$port;dbname=$dbname";
    } else {
        $dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4";
    }
} else {
    // Fallback for cPanel hosting (MySQL)
   $host = 'localhost';
    $port = 3306;
    $dbname = 'burguerdogordoco_bd'; 
    $user = 'burguerdogordoco_admin';
    $password = 'alexjorge123';
    $dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4";
}

try {
    $pdo = new PDO($dsn, $user, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]));
}

function jsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit();
}

function getJsonInput() {
    $input = file_get_contents('php://input');
    return json_decode($input, true) ?? [];
}

function formatMoney($value) {
    return 'R$ ' . number_format((float)$value, 2, ',', '.');
}

function generateId() {
    return bin2hex(random_bytes(18));
}

function requireAuth() {
    session_start();
    if (!isset($_SESSION['admin_id'])) {
        jsonResponse(['error' => 'Não autorizado. Faça login.'], 401);
    }
    return $_SESSION['admin_id'];
}

function optionalAuth() {
    session_start();
    return $_SESSION['admin_id'] ?? null;
}
