<?php
// backend/config/db.php

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

require_once __DIR__ . '/../vendor/autoload.php';

use Dotenv\Dotenv;

// Try to load .env from multiple possible locations
$envLoaded = false;
$searchPaths = [
    __DIR__ . '/../..',                          // jordan_bot/
    __DIR__ . '/../../..',                        // lawer.tripz-egypt.com/
    __DIR__ . '/../../../..',                     // htdocs/
    __DIR__ . '/../../../../..',                  // home directory
    posix_getpwuid(posix_getuid())['dir'] ?? '',  // PHP-detected home dir
    $_SERVER['DOCUMENT_ROOT'] ?? ''
];

$envData = [];

foreach ($searchPaths as $path) {
    if (!empty($path) && file_exists($path . '/.env')) {
        try {
            // Manual parsing to handle comments and raw strings gracefully
            $lines = file($path . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $parsed = true;
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line) || strpos($line, '#') === 0 || strpos($line, ';') === 0) continue;
                
                if (strpos($line, '=') !== false) {
                    list($key, $value) = explode('=', $line, 2);
                    $key = trim($key);
                    $value = trim($value, " \t\n\r\0\x0B\"'"); // remove quotes
                    $_ENV[$key] = $value;
                    $_SERVER[$key] = $value;
                    putenv("$key=$value");
                }
            }
            $envLoaded = true;
            break;
        } catch (Exception $e) {
            // Fallback to Dotenv library if manual parsing somehow fails
            if (class_exists('Dotenv\Dotenv')) {
                try {
                    $dotenv = Dotenv\Dotenv::createImmutable($path);
                    $dotenv->load();
                    $envLoaded = true;
                    break;
                } catch (Exception $inner) {}
            }
        }
    }
}

if (!$envLoaded) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => '.env file not found or could not be parsed. Searched paths: ' . implode(', ', array_filter($searchPaths))
    ]);
    exit;
}

// Security: API Key Validation
$expectedApiKey = $_SERVER['API_KEY'] ?? (getenv('API_KEY') ?: ($_ENV['API_KEY'] ?? 'JORDAN_BOT_SECRET_2026'));

// Safe header extraction for NGINX/PHP-FPM
$headers = function_exists('getallheaders') ? getallheaders() : [];
$providedKey = $headers['X-API-Key'] ?? ($headers['x-api-key'] ?? $_SERVER['HTTP_X_API_KEY'] ?? null);

// Enhanced Debug Logging
error_log("JordanBot API Check: Provided: [$providedKey], Expected: [$expectedApiKey], EnvLoaded: [" . ($envLoaded ? "YES" : "NO") . "]");

if ($providedKey !== $expectedApiKey) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized: Invalid or missing API Key']);
    exit;
}

// Extra Security: App Signature Fingerprint Validation (Temporarily Disabled for Debugging)
/*
$expectedSignatures = $_ENV['APP_SIGNATURE_SHA256'] ?? null;
if (!empty($expectedSignatures)) {
    $providedSignature = $headers['X-App-Signature'] ?? ($headers['x-app-signature'] ?? null);
    $validSignatures = explode(',', $expectedSignatures);
    $isValid = false;
    foreach ($validSignatures as $sig) {
        if (strcasecmp(trim($sig), trim($providedSignature)) === 0) {
            $isValid = true;
            break;
        }
    }
    if (!$isValid) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Forbidden: Invalid App Signature (Anti-Tamper)']);
        exit;
    }
}
*/

$host = $_ENV['DB_HOST'] ?? 'localhost';
$dbname = $_ENV['DB_NAME'] ?? 'jordan_bot_db';
$username = $_ENV['DB_USER'] ?? 'root';
$password = $_ENV['DB_PASS'] ?? '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed: ' . $e->getMessage()]);
    exit;
}
?>
