<?php

// Define MySQL constants if missing (PHP 7+)
if (!defined('MYSQL_ASSOC')) define('MYSQL_ASSOC', MYSQLI_ASSOC);
if (!defined('MYSQL_NUM')) define('MYSQL_NUM', MYSQLI_NUM);
if (!defined('MYSQL_BOTH')) define('MYSQL_BOTH', MYSQLI_BOTH);
if (!defined('MYSQL_CLIENT_COMPRESS')) define('MYSQL_CLIENT_COMPRESS', 32);
if (!defined('MYSQL_CLIENT_IGNORE_SPACE')) define('MYSQL_CLIENT_IGNORE_SPACE', 256);
if (!defined('MYSQL_CLIENT_INTERACTIVE')) define('MYSQL_CLIENT_INTERACTIVE', 1024);
if (!defined('MYSQL_CLIENT_SSL')) define('MYSQL_CLIENT_SSL', 2048);

if (!function_exists('mb_substr')) {
    function mb_substr($string, $start, $length = null, $encoding = null) {
        return ($length === null) ? substr($string, $start) : substr($string, $start, $length);
    }
}

$GLOBALS['db_connection'] = null;

function _mysql_get_default_link($link_identifier = null) {
    if ($link_identifier instanceof mysqli) {
        return $link_identifier;
    }
    if (isset($GLOBALS['db_connection']) && $GLOBALS['db_connection'] instanceof mysqli) {
        return $GLOBALS['db_connection'];
    }
    return null;
}

if (!function_exists('mysql_connect')) {
    function mysql_connect($host = 'localhost', $user = 'root', $password = '', $new_link = false, $client_flags = 0) {
        $cleanHost = str_replace('p:', '', $host);
        $port = 3306;
        if (strpos($cleanHost, ':') !== false) {
            list($cleanHost, $portStr) = explode(':', $cleanHost, 2);
            $port = (int)$portStr;
        }
        $link = @mysqli_connect($cleanHost, $user, $password, '', $port);
        if ($link) {
            $GLOBALS['db_connection'] = $link;
        }
        return $link;
    }
}

if (!function_exists('mysql_pconnect')) {
    function mysql_pconnect($host = 'localhost', $user = 'root', $password = '', $client_flags = 0) {
        return mysql_connect($host, $user, $password);
    }
}

if (!function_exists('mysql_select_db')) {
    function mysql_select_db($database_name, $link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_select_db($link, $database_name);
        }
        return false;
    }
}

if (!function_exists('mysql_query')) {
    function mysql_query($query, $link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_query($link, $query);
        }
        return false;
    }
}

if (!function_exists('mysql_fetch_array')) {
    function mysql_fetch_array($result, $result_type = MYSQLI_BOTH) {
        if ($result instanceof mysqli_result) {
            return mysqli_fetch_array($result, $result_type);
        }
        return false;
    }
}

if (!function_exists('mysql_fetch_assoc')) {
    function mysql_fetch_assoc($result) {
        if ($result instanceof mysqli_result) {
            return mysqli_fetch_assoc($result);
        }
        return false;
    }
}

if (!function_exists('mysql_fetch_row')) {
    function mysql_fetch_row($result) {
        if ($result instanceof mysqli_result) {
            return mysqli_fetch_row($result);
        }
        return false;
    }
}

if (!function_exists('mysql_fetch_object')) {
    function mysql_fetch_object($result, $class_name = null, $params = null) {
        if ($result instanceof mysqli_result) {
            if ($class_name !== null) {
                return mysqli_fetch_object($result, $class_name, $params ? $params : array());
            }
            return mysqli_fetch_object($result);
        }
        return false;
    }
}

if (!function_exists('mysql_num_rows')) {
    function mysql_num_rows($result) {
        if ($result instanceof mysqli_result) {
            return mysqli_num_rows($result);
        }
        return false;
    }
}

if (!function_exists('mysql_affected_rows')) {
    function mysql_affected_rows($link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_affected_rows($link);
        }
        return false;
    }
}

if (!function_exists('mysql_insert_id')) {
    function mysql_insert_id($link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_insert_id($link);
        }
        return false;
    }
}

if (!function_exists('mysql_real_escape_string')) {
    function mysql_real_escape_string($string, $link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_real_escape_string($link, $string);
        }
        return addslashes($string);
    }
}

if (!function_exists('mysql_escape_string')) {
    function mysql_escape_string($string) {
        $link = _mysql_get_default_link();
        if ($link) {
            return mysqli_real_escape_string($link, $string);
        }
        return addslashes($string);
    }
}

if (!function_exists('mysql_error')) {
    function mysql_error($link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_error($link);
        }
        return mysqli_connect_error();
    }
}

if (!function_exists('mysql_errno')) {
    function mysql_errno($link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_errno($link);
        }
        return mysqli_connect_errno();
    }
}

if (!function_exists('mysql_free_result')) {
    function mysql_free_result($result) {
        if ($result instanceof mysqli_result) {
            mysqli_free_result($result);
            return true;
        }
        return false;
    }
}

if (!function_exists('mysql_close')) {
    function mysql_close($link_identifier = null) {
        $link = _mysql_get_default_link($link_identifier);
        if ($link) {
            return mysqli_close($link);
        }
        return false;
    }
}

if (!function_exists('mysql_data_seek')) {
    function mysql_data_seek($result, $row_number) {
        if ($result instanceof mysqli_result) {
            return mysqli_data_seek($result, $row_number);
        }
        return false;
    }
}

if (!function_exists('mysql_num_fields')) {
    function mysql_num_fields($result) {
        if ($result instanceof mysqli_result) {
            return mysqli_num_fields($result);
        }
        return false;
    }
}

if (!function_exists('mysql_field_name')) {
    function mysql_field_name($result, $field_offset) {
        if ($result instanceof mysqli_result) {
            $field_info = mysqli_fetch_field_direct($result, $field_offset);
            return $field_info ? $field_info->name : false;
        }
        return false;
    }
}

/**
 * Connects to database server and selects a database
 */
$db_url = getenv("JAWSDB_URL") ?: getenv("CLEARDB_DATABASE_URL") ?: getenv("DATABASE_URL");
if ($db_url && strpos($db_url, 'mysql://') === 0) {
    $db_parts = parse_url($db_url);
    $host     = $db_parts['host'] ?? 'localhost';
    $port     = $db_parts['port'] ?? 3306;
    $username = $db_parts['user'] ?? 'root';
    $password = $db_parts['pass'] ?? '';
    $dbname   = ltrim($db_parts['path'] ?? '', '/');
    if ($port && $port != 3306) {
        $host = $host . ":" . $port;
    }
} else {
    $host     = getenv('DB_HOST') ?: 'localhost';
    $username = getenv('DB_USER') ?: 'loveweddingcam_test';
    $password = getenv('DB_PASS') ?: ',V#jmj3qH+apqu$)';
    $dbname   = getenv('DB_NAME') ?: 'loveweddingcam_test';
}

$connection = mysql_pconnect($host, $username, $password) or die("connection to the server fail: " . mysql_error());
mysql_select_db($dbname, $connection) or die("could not open db: $dbname");

function db_connect()
{
    global $connection, $dbname, $username, $password, $host;
    if (!$connection) {
        $connection = mysql_pconnect($host, $username, $password);
    }
    if (!$connection) {
        return false;
    }
    if (!mysql_select_db($dbname, $connection)) {
        return false;
    }
    return $connection;
}

function escape_string($str) {
    try {
        return mysql_real_escape_string($str);
    } catch (Exception $e) {
        throw new Exception("escape_string: " . $e->getMessage());
    }
}

function login($user, $pass)
{
    db_connect();
    $result = mysql_query("SELECT * FROM tbladmin WHERE name = '" . escape_string($user) . "' AND password = '" . escape_string($pass) . "'");
    if (!$result) return false;
    $num_rows = mysql_num_rows($result);
    if ($num_rows < 1) return false;
    mysql_free_result($result);
    return true;
}

function getBaseUrl() {
    $currentPath = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '';
    $pathInfo = pathinfo($currentPath);
    $hostName = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    $protocol = (isset($_SERVER['SERVER_PROTOCOL']) && strtolower(substr($_SERVER["SERVER_PROTOCOL"], 0, 5)) == 'https://') ? 'https://' : 'http://';
    $dirname = isset($pathInfo['dirname']) && $pathInfo['dirname'] !== '/' && $pathInfo['dirname'] !== '\\' ? $pathInfo['dirname'] : '';
    return $protocol . $hostName . $dirname . "/";
}

mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection ='utf8_general_ci'");

?>
