<?php
// Set timezone to Philippines (UTC+8) so date() returns the correct local date
date_default_timezone_set('Asia/Manila');

// Database settings (cPanel production - pointscard.nroi.net)
$host = 'localhost';
$db = 'nroinet_db';
$user = 'nroinet_db';
$pass = '_I(}%l=%iaAJtMq8';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    if (php_sapi_name() !== 'cli' && !headers_sent()) {
        header('Access-Control-Allow-Origin: *');
        header('Content-Type: application/json');
        // Show actual error on localhost so you can fix it (e.g. wrong DB name, MySQL not running)
        $msg = (isset($_SERVER['HTTP_HOST']) && ($_SERVER['HTTP_HOST'] === 'localhost' || strpos($_SERVER['HTTP_HOST'], '127.0.0.1') !== false))
            ? 'Database connection failed: ' . $e->getMessage()
            : 'Database connection failed. Please try again later.';
        echo json_encode([
            'success' => false,
            'message' => $msg,
            'code' => 'db_error'
        ]);
    } else {
        die("Connection failed: " . $e->getMessage());
    }
    exit;
}

/**
 * Capitalizes the first letter of each word and lowers the rest.
 */
function capitalizeWords($str)
{
    if (empty($str))
        return $str;
    // Handle names like "DE LA CRUZ" -> "De La Cruz"
    return ucwords(strtolower(trim((string) $str)));
}