<?php
// ── Database configuration ────────────────────────────────────────────────────
// BUG #4 FIX: Use a dedicated DB user (not root) with a strong password.
// Set these values via environment variables or a .env file — never hardcode
// credentials in source code that gets committed to version control.
//
// To create the DB user in MySQL/MariaDB:
//   CREATE USER 'voucher_user'@'localhost' IDENTIFIED BY 'your_strong_password';
//   GRANT SELECT, INSERT, UPDATE, DELETE ON voucher_system.* TO 'voucher_user'@'localhost';
//   FLUSH PRIVILEGES;

$db_host = getenv('DB_HOST') ?: 'localhost';
$db_user = getenv('DB_USER') ?: 'kuchin99_pernaevents';
$db_pass = getenv('DB_PASS') ?: 'Kilang28###';
$db_name = getenv('DB_NAME') ?: 'kuchin99_voucher_system';

// Safety check: warn if running with root fallback (env vars not configured)
if (!getenv('DB_USER')) {
    error_log('WARNING: DB_USER env var not set — falling back to root. Set DB_HOST, DB_USER, DB_PASS, DB_NAME on your server before going live.');
}

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

if ($conn->connect_error) {
    // BUG #4 FIX: never expose raw connection errors to the browser
    error_log("DB connection failed: " . $conn->connect_error);
    http_response_code(500);
    die(json_encode(['error' => 'Service temporarily unavailable.']));
}

// BUG #5 FIX: force utf8mb4 for all queries — supports Malay/Unicode/emoji names
$conn->set_charset('utf8mb4');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
