<?php
session_start();

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$servername = "localhost";
$username   = "engrgolk";
$password   = "Venu@#10522";
$database   = "engrgolk_agrosys";

date_default_timezone_set('Asia/Colombo');

if (!function_exists('is_ajax_request')) {
    function is_ajax_request() {
        return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
            || (isset($_GET['ajax']) && (string)$_GET['ajax'] === '1')
            || (isset($_SERVER['CONTENT_TYPE']) && stripos($_SERVER['CONTENT_TYPE'], 'application/json') !== false);
    }
}

if (!function_exists('app_log_error')) {
    function app_log_error($message) {
        error_log('[KSP] ' . $message);
    }
}

if (!function_exists('respond_ajax_error')) {
    function respond_ajax_error($message = 'Connection issue. Please try again.') {
        if (is_ajax_request()) {
            http_response_code(503);
            header('Content-Type: application/json; charset=UTF-8');
            echo json_encode([
                'status' => 'error',
                'message' => $message
            ]);
            exit();
        }
    }
}

try {
    $conn = mysqli_init();
    if (!$conn) {
        throw new Exception('Unable to initialize MySQL connection.');
    }

    mysqli_options($conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5);

    if (!@$conn->real_connect($servername, $username, $password, $database)) {
        throw new Exception('Database connection failed.');
    }

    $conn->set_charset('utf8mb4');
    $conn->query("SET SESSION wait_timeout=60");
    $conn->query("SET SESSION interactive_timeout=60");
} catch (Throwable $e) {
    app_log_error('Database connection error: ' . $e->getMessage());
    respond_ajax_error('Network or database issue detected. Please try again.');

    http_response_code(503);
    exit('Service temporarily unavailable. Please try again.');
}

/* Application constants */
define('APP_NAME', 'Krushi Sewa Piyasa');
define('APP_ADDRESS_LINE', 'Nelundeniya, Kegalle');
define('APP_PHONE_LINE', '071-777-2378');
define('APP_REPORT_LOGO', __DIR__ . '/logo/logo_circle_1.png');
define('APP_REPORT_DIR', __DIR__ . '/generated_reports');

/* Mail settings */
define('REPORT_FROM_EMAIL', 'krushisewapiyasa@engrgo.lk');
define('REPORT_FROM_NAME', 'Krushi Sewa Piyasa');

/*
|--------------------------------------------------------------------------
| SMTP settings
|--------------------------------------------------------------------------
| If your server can send mail directly with PHP mail(), you can leave
| SMTP_PASSWORD empty and the code will try the local mail() fallback.
| If you want SMTP sending, fill these values properly.
*/
define('SMTP_HOST', 'localhost');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', 'krushisewapiyasa@engrgo.lk');
define('SMTP_PASSWORD', '');
define('SMTP_SECURE', 'tls');
?>