<?php
declare(strict_types=1);

const BILLING_ROOT = __DIR__ . '/..';
$privateErrorLog = BILLING_ROOT . '/storage/php-error.log';
ini_set('log_errors', '1');
ini_set('error_log', $privateErrorLog);
$configFile = BILLING_ROOT . '/config/config.php';
if (!is_file($configFile)) {
    http_response_code(503);
    exit('Billing is not configured. Install the private server configuration before opening this application.');
}

$config = require $configFile;
$config['app']['base_url'] = 'https://billing.sodazw.co.zw';
date_default_timezone_set($config['app']['timezone'] ?? 'Africa/Harare');
$trustedProxies = (array)($config['security']['trusted_proxy_ips'] ?? []);
$fromTrustedProxy = in_array((string)($_SERVER['REMOTE_ADDR'] ?? ''), $trustedProxies, true);
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || ($fromTrustedProxy && (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https'));
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-Robots-Tag: noindex, nofollow, noarchive');
header('Referrer-Policy: no-referrer');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
header('Cache-Control: private, no-store, max-age=0');
header('Pragma: no-cache');
if ($isHttps) header('Strict-Transport-Security: max-age=31536000');
session_name($config['app']['session_name'] ?? 'sodazw_billing_session');
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => $isHttps,
    'httponly' => true,
    'samesite' => 'Lax',
]);
ini_set('session.use_strict_mode', '1');
session_start();

$db = $config['db'];
$dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', $db['host'], $db['port'], $db['name'], $db['charset'] ?? 'utf8mb4');
try {
    $pdo = new PDO($dsn, $db['user'], $db['pass'], [
        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(503);
    exit('The billing database is temporarily unavailable. Please check the database configuration.');
}

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/release.php';
require_once __DIR__ . '/finance.php';
require_once __DIR__ . '/whatsapp.php';
require_once __DIR__ . '/paynow.php';
