<?php
    $rootFolder = basename($_SERVER['DOCUMENT_ROOT']);
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . str_replace('/pages', '', dirname($_SERVER['SCRIPT_NAME']));
?>
<?php
/* ============================================================================
 * File: config.php
 * Purpose: Central config + ALL DB connections (MySQLi only; no PDO)
 * Defaults: $conn points to broriserin_onb (as requested)
 * Collation: utf8mb4_general_ci on every connection
 * URL bases: BASE_URL + sectioned URLs (ONBOARDING, AMS, crmplus) + ASSETS_URL
 * ========================================================================== */

if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_OFF); }
date_default_timezone_set('Asia/Kolkata');

/* Helper: set charset & connection collation */
function _set_charset_and_collation($link){
    if ($link instanceof mysqli) {
        @mysqli_set_charset($link, 'utf8mb4');
        @mysqli_query($link, "SET NAMES utf8mb4");
        @mysqli_query($link, "SET collation_connection = 'utf8mb4_general_ci'");
    }
}


/* ======================= DB CONNECTIONS (edit creds if needed) ======================= */
/* HR Dump (superadmin) */
$conn_sa = mysqli_connect("localhost","broriser_superadmin","br@comXJ3S","broriser_superadmin");	_set_charset_and_collation($conn_sa);

/* HR Dump (HRD) */
//$hrd = mysqli_connect("localhost","broriser_hrd","br@comXJ3S","broriser_hrd");	_set_charset_and_collation($hrd);

/* IC Attendance (IC) */
$conn_ic = mysqli_connect("localhost","broriser_ic_attendance","br@comXJ3S","broriser_ic_attendance");	_set_charset_and_collation($conn_ic);

/* IC Reports */
//$cron = mysqli_connect("localhost","broriser_icreports","br@comXJ3S","broriser_icreports");	_set_charset_and_collation($cron);

/* Project Empanel */
$connpe = mysqli_connect("localhost","broriser_project_empanel","br@comXJ3S","broriser_project_empanel");	_set_charset_and_collation($connpe);

/* Legacy Attendance DB */
$connwo = mysqli_connect("localhost","broriser_attendance","br@comXJ3S","broriser_attendance");	_set_charset_and_collation($connwo);

/* Web API */
$conwebapi = mysqli_connect("localhost","broriser_web_api","br@comXJ3S","broriser_web_api");	_set_charset_and_collation($conwebapi);

/* WhatsApp */
$conwhatsapp = mysqli_connect("localhost","broriser_whatsapp","br@comXJ3S","broriser_whatsapp");	_set_charset_and_collation($conwhatsapp);

/* ONB (DEFAULT) — $conn must point to broriser_onb */
$conn = mysqli_connect("localhost","broriser_onb","br@comXJ3S","broriser_onb");	_set_charset_and_collation($conn);

/* CRMPLUS (NEW) — houses ui_crm, crm_enquiries, etc. */
$conn_crmplus = mysqli_connect("localhost","broriser_brorisercom","br@comXJ3S","broriser_brorisercom");	_set_charset_and_collation($conn_crmplus);

/* Readable aliases */
$conn_hrd               = $hrd;            // HR dump
$conn_attendance_ic     = $conn_ic;        // IC attendance
$conn_icreports         = $cron;           // IC reports
$conn_project_empanel   = $connpe;         // Project empanel
$conn_attendance_legacy = $connwo;         // Legacy attendance
$conn_web_api           = $conwebapi;      // Web API
$conn_whatsapp          = $conwhatsapp;    // WhatsApp
$conn_onb               = $conn;           // ONB (default)
$conn_crm               = $conn_crmplus;   // CRMPLUS (use this in CRM pages)

/* Safe query helper (no exceptions) */
function dbq($dbc, $sql){
    if (!$dbc || !($dbc instanceof mysqli)) return false;
    $res = @mysqli_query($dbc, $sql);
    return $res ?: false;
}

/* ======================= BASE URLS ======================= */
/* Root site URL (keep trailing slash). Update to your real public URL. */
if (!defined('BASE_URL')) {
    define('BASE_URL', 'https://int.broriser.in/'); // <-- you can change this once for all sections
}
/* Sectioned URLs (no trailing slash here) */
if (!defined('BASE_URL_ONBOARDING')) define('BASE_URL_ONBOARDING', rtrim(BASE_URL, '/').'/onboarding');
if (!defined('BASE_URL_AMS'))        define('BASE_URL_AMS',        rtrim(BASE_URL, '/').'/ams');
if (!defined('BASE_URL_crmplus'))      define('BASE_URL_crmplus',      rtrim(BASE_URL, '/').'/crmplus');
// Ensure BASE_URL_mobile is defined (your file already does this)
if (!defined('BASE_URL_mobile')) {
    define('BASE_URL_mobile', rtrim(BASE_URL, '/') . '/mobile'); // no trailing slash in constant
}

// Provide a convenient $ASSET variable used by theme files (always has trailing slash)
if (!isset($ASSET)) {
    // Prefer mobile-specific base if defined, otherwise fall back to root BASE_URL
    $base_for_assets = defined('BASE_URL_mobile') ? BASE_URL_mobile : BASE_URL;
    $ASSET = rtrim($base_for_assets, '/') . '/';  // e.g. https://broriser.in/mobile/
}


/* Shared assets URL (point this where your theme assets live). 
   Here I assume your app assets are inside /crmplus/assets */
if (!defined('ASSETS_URL'))          define('ASSETS_URL',          BASE_URL_crmplus.'/assets');

/* ======================= MYSQL-BACKED SESSIONS (7 days) ======================= */
class MySQLSessionHandler implements SessionHandlerInterface {
    private mysqli $db;
    private int $ttl;
    public function __construct(mysqli $db, int $ttl = 604800) { // 7 days
        $this->db  = $db;
        $this->ttl = $ttl;
        $this->ensureTable();
    }
    private function ensureTable(): void {
        $sql = "CREATE TABLE IF NOT EXISTS `auth_sessions` (
            `id`         VARCHAR(128)  NOT NULL,
            `user_id`    INT UNSIGNED  NULL,
            `data`       MEDIUMBLOB    NOT NULL,
            `ip_address` VARBINARY(16) NULL,
            `user_agent` VARCHAR(255)  NULL,
            `created_at` DATETIME      NOT NULL,
            `updated_at` DATETIME      NOT NULL,
            `expires_at` DATETIME      NOT NULL,
            PRIMARY KEY (`id`),
            KEY `expires_at` (`expires_at`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";
        @mysqli_query($this->db, $sql);
    }
    public function open($savePath, $sessionName): bool { return true; }
    public function close(): bool { return true; }
    public function read($id): string {
        $now = date('Y-m-d H:i:s');
        $sql = "SELECT `data` FROM `auth_sessions` WHERE `id`=? AND `expires_at` > ? LIMIT 1";
        if ($stmt = $this->db->prepare($sql)) {
            $stmt->bind_param('ss', $id, $now);
            $stmt->execute();
            $stmt->bind_result($data);
            if ($stmt->fetch()) { $stmt->close(); return (string)$data; }
            $stmt->close();
        }
        return '';
    }
    public function write($id, $data): bool {
        $ua  = substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
        $ip  = @inet_pton($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
        $now = date('Y-m-d H:i:s');
        $exp = date('Y-m-d H:i:s', time() + $this->ttl);

        $uid = 0;
        if (isset($_SESSION) && is_array($_SESSION)) {
            if (!empty($_SESSION['auth']['user_id']))        $uid = (int)$_SESSION['auth']['user_id'];
            elseif (!empty($_SESSION['user_id']))            $uid = (int)$_SESSION['user_id'];
            elseif (!empty($_SESSION['user_id1']) && ctype_digit((string)$_SESSION['user_id1'])) $uid = (int)$_SESSION['user_id1'];
        }
        $ip_str = $ip !== false ? $ip : '';

        $sql = "INSERT INTO `auth_sessions`
                (`id`,`user_id`,`data`,`ip_address`,`user_agent`,`created_at`,`updated_at`,`expires_at`)
                VALUES (?,?,?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE
                  `user_id`=VALUES(`user_id`),
                  `data`=VALUES(`data`),
                  `ip_address`=VALUES(`ip_address`),
                  `user_agent`=VALUES(`user_agent`),
                  `updated_at`=VALUES(`updated_at`),
                  `expires_at`=VALUES(`expires_at`)";
        if ($stmt = $this->db->prepare($sql)) {
            $stmt->bind_param('sissssss', $id, $uid, $data, $ip_str, $ua, $now, $now, $exp);
            $ok = $stmt->execute();
            $stmt->close();
            return $ok;
        }
        return false;
    }
    public function destroy($id): bool {
        $sql = "DELETE FROM `auth_sessions` WHERE `id`=? LIMIT 1";
        if ($stmt = $this->db->prepare($sql)) {
            $stmt->bind_param('s', $id);
            $stmt->execute();
            $stmt->close();
        }
        return true;
    }
    public function gc($max_lifetime): int|false {
        $now = date('Y-m-d H:i:s');
        @mysqli_query($this->db, "DELETE FROM `auth_sessions` WHERE `expires_at` <= '{$now}'");
        return @mysqli_affected_rows($this->db);
    }
}

/* ---------- Session cookie + handler wiring (ICSESSID, 7 days, sliding) ---------- */
if (session_status() !== PHP_SESSION_ACTIVE) {
    $isHttps     = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || ((int)($_SERVER['SERVER_PORT'] ?? 80) === 443);
    $SESSION_TTL = 60*60*24*7;

    ini_set('session.use_only_cookies', '1');
    ini_set('session.cookie_httponly',  '1');
    ini_set('session.cookie_samesite',  'Lax');
    ini_set('session.gc_maxlifetime',   (string)$SESSION_TTL);
    ini_set('session.use_strict_mode',  '1');

    session_name('ICSESSID');
    session_set_cookie_params([
        'lifetime' => $SESSION_TTL,
        'path'     => '/',
        'domain'   => '',
        'secure'   => $isHttps,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    $SESSION_DB = null;
    if ($conn_crmplus instanceof mysqli) { $SESSION_DB = $conn_crmplus; }
    elseif ($conn instanceof mysqli)     { $SESSION_DB = $conn; }
    elseif ($conn_sa instanceof mysqli)  { $SESSION_DB = $conn_sa; }

    if ($SESSION_DB instanceof mysqli) {
        $handler = new MySQLSessionHandler($SESSION_DB, $SESSION_TTL);
        session_set_save_handler($handler, true);
        session_start();
        if (!headers_sent()) {
            setcookie(session_name(), session_id(), [
                'expires'  => time() + $SESSION_TTL,
                'path'     => '/',
                'domain'   => '',
                'secure'   => $isHttps,
                'httponly' => true,
                'samesite' => 'Lax',
            ]);
        }
    } else {
        error_log('config.php: No DB available for MySQLSessionHandler — using default file sessions.');
        session_start();
    }
}

/* ------------------------ Common helpers ------------------------ */
if (!function_exists('abs_url')) {
    function abs_url(string $path): string {
        $https  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || ((int)($_SERVER['SERVER_PORT'] ?? 80) === 443);
        $scheme = $https ? 'https' : 'http';
        $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $path   = ltrim($path, '/');
        return $scheme.'://'.$host.'/'.$path;
    }
}
if (!function_exists('is_logged_in')) {
    function is_logged_in(): bool {
        if (!empty($_SESSION['user_id1'])) return true;
        if (!empty($_SESSION['user_id']))  return true;
        if (!empty($_SESSION['auth']['user_id'] ?? null)) return true;
        return false;
    }
}


/* Optional light error logs (non-fatal) */
if (!$hrd)         { error_log('config.php: HRD connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$conn_ic)     { error_log('config.php: IC attendance connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$cron)        { error_log('config.php: IC reports connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$connpe)      { error_log('config.php: Project empanel connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$connwo)      { error_log('config.php: Legacy attendance connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$conwebapi)   { error_log('config.php: Web API connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$conwhatsapp) { error_log('config.php: WhatsApp connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$conn)        { error_log('config.php: ONB (DEFAULT $conn) connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }
if (!$conn_crmplus){ error_log('config.php: CRMPLUS ($conn_crmplus) connection failed: '.(@mysqli_connect_error() ?: 'unknown')); }


// (7) Google Map key
$GOOGLE_MAPS_API_KEY = 'AIzaSyB-FZbEtDvYXFk3M7ALNt11S4kfMO1XVPo';

// (8) Don’t redeclare constants if config is included again
if (!defined('BASE_URL'))           define('BASE_URL', '/onboarding/');   // <-- change to your actual base URL
if (!defined('SENDGRID_API_KEY'))   define('SENDGRID_API_KEY', 'SG.xY0yT2WTTtGBS4P5b717QQ.troBssYTjXtJy2JtSEaGh0t1TdhxAO6nSJ0PEsKqqbE');
if (!defined('SENDGRID_FROM_EMAIL'))define('SENDGRID_FROM_EMAIL', 'info@broriser.in');
if (!defined('SENDGRID_FROM_NAME')) define('SENDGRID_FROM_NAME', 'BroRiser');
?>