<?php
/**
 * Database Configuration
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

define('DB_CHARSET', 'utf8mb4');

// Use local DB when running on Laragon/localhost; use Byethost when on live server
$isLocal = in_array($_SERVER['HTTP_HOST'] ?? '', ['localhost', '127.0.0.1'], true)
    || (isset($_SERVER['SERVER_NAME']) && in_array($_SERVER['SERVER_NAME'], ['localhost', '127.0.0.1'], true));

if ($isLocal) {
    define('DB_HOST', '127.0.0.1');
    define('DB_NAME', 'php_registration');
    define('DB_USER', 'root');
    define('DB_PASS', '');
} else {
    define('DB_HOST', 'sql103.byethost11.com');
    define('DB_NAME', 'b11_41100569_2');
    define('DB_USER', 'b11_41100569');
    define('DB_PASS', '123456');
}

function getDbConnection(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];
        try {
            $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            // On local: if database doesn't exist, create it and the table
            if ($e->getCode() === 1049 && defined('DB_HOST') && in_array(DB_HOST, ['127.0.0.1', 'localhost'], true)) {
                $pdo = new PDO('mysql:host=' . DB_HOST . ';charset=' . DB_CHARSET, DB_USER, DB_PASS, $options);
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
                $pdo->exec("USE `" . DB_NAME . "`");
                $pdo->exec("CREATE TABLE IF NOT EXISTS users (
                    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    name VARCHAR(100) NOT NULL,
                    email VARCHAR(255) NOT NULL UNIQUE,
                    password VARCHAR(255) NOT NULL,
                    email_verified TINYINT(1) DEFAULT 0,
                    verification_token VARCHAR(64) NULL,
                    token_expires_at DATETIME NULL,
                    password_reset_token VARCHAR(64) NULL,
                    password_reset_expires_at DATETIME NULL,
                    last_login_at DATETIME NULL,
                    last_login_ip VARCHAR(45) NULL,
                    is_admin TINYINT(1) DEFAULT 0,
                    suspended TINYINT(1) DEFAULT 0,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_email (email),
                    INDEX idx_verification_token (verification_token),
                    INDEX idx_password_reset_token (password_reset_token)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $pdo->exec("CREATE TABLE IF NOT EXISTS contact_messages (
                    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    name VARCHAR(100) NOT NULL,
                    email VARCHAR(255) NOT NULL,
                    subject VARCHAR(255) NOT NULL,
                    message TEXT NOT NULL,
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_created (created_at)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $pdo = null; // reconnect with dbname for future requests
                return getDbConnection();
            }
            throw $e;
        }
    }
    return $pdo;
}
