<?php
// Database configuration for Tajdid API

// Environment detection
$isProduction = !in_array($_SERVER['HTTP_HOST'] ?? '', ['localhost', '127.0.0.1', 'website-project.test']) && 
                strpos($_SERVER['HTTP_HOST'] ?? '', '192.168.') !== 0;

// Database credentials - CHANGE THESE for production
$DB_HOST = $isProduction ? 'your-production-db-host' : '127.0.0.1';
$DB_NAME = $isProduction ? 'your_production_db' : 'tajdid_db';
$DB_USER = $isProduction ? 'your_db_user' : 'root';
$DB_PASS = $isProduction ? 'your_db_password' : '';
$DB_CHARSET = 'utf8mb4';

// Optional: Custom upload URL for CDN or different domain
// define('UPLOAD_BASE_URL', 'https://cdn.your-domain.com/tajdid-api');

// Admin API key and write rate-limit settings.
// In production, set TAJDID_ADMIN_KEY from the server environment.
if (!defined('ADMIN_API_KEY')) {
    $adminKeyFromEnv = getenv('TAJDID_ADMIN_KEY');
    if ($adminKeyFromEnv === false || trim($adminKeyFromEnv) === '') {
        $adminKeyFromEnv = $isProduction ? '' : 'tajdid-local-admin-key';
    }
    define('ADMIN_API_KEY', (string) $adminKeyFromEnv);
}

if (!defined('ADMIN_RATE_LIMIT_MAX_REQUESTS')) {
    define('ADMIN_RATE_LIMIT_MAX_REQUESTS', 10);
}

if (!defined('ADMIN_RATE_LIMIT_WINDOW_SECONDS')) {
    define('ADMIN_RATE_LIMIT_WINDOW_SECONDS', 60);
}

if (!defined('ADMIN_RATE_LIMIT_STORAGE_FILE')) {
    define('ADMIN_RATE_LIMIT_STORAGE_FILE', __DIR__ . '/logs/admin_rate_limit.json');
}

$dsn = "mysql:host={$DB_HOST};dbname={$DB_NAME};charset={$DB_CHARSET}";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $DB_USER, $DB_PASS, $options);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'DB connection failed: ' . $e->getMessage()]);
    exit;
}
