<?php
// =============================================
// config.php - Main Configuration File
// =============================================

define('DB_HOST', 'localhost');
define('DB_USER', 'enoticet_pry');
define('DB_PASS', 'Boc(o;;GHXypyb+(');
define('DB_NAME', 'enoticet_pry');

define('SITE_URL', 'https://p1.enotice.top/telecom');
define('CURRENCY', '৳');
define('SESSION_TIMEOUT', 86400 * 30); // 30 days

// Database Connection
function getDB() {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $pdo = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
        } catch (PDOException $e) {
            die(json_encode(['success' => false, 'message' => 'Database connection failed']));
        }
    }
    return $pdo;
}

// Session with long lifetime
ini_set('session.gc_maxlifetime', 86400 * 30);
ini_set('session.cookie_lifetime', 86400 * 30);
session_set_cookie_params([
    'lifetime' => 86400 * 30,
    'path'     => '/',
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);
session_start();

// Auto-login from remember me cookie
if (!isset($_SESSION['user_id']) && isset($_COOKIE['remember_token'])) {
    try {
        $db = getDB();
        $token = $_COOKIE['remember_token'];
        $stmt = $db->prepare("SELECT * FROM users WHERE remember_token=? AND status='active' LIMIT 1");
        $stmt->execute([$token]);
        $u = $stmt->fetch();
        if ($u) {
            $_SESSION['user_id']           = $u['id'];
            $_SESSION['role']              = $u['role'];
            $_SESSION['name']              = $u['name'];
            $_SESSION['last_activity']     = time();
            $_SESSION['device_last_check'] = 0; // Force immediate check
            // Refresh cookie
            setcookie('remember_token', $token, time() + 86400*30, '/', '', true, true);
        }
    } catch(Exception $e) {}
}

// Auth functions
function isLoggedIn() {
    return isset($_SESSION['user_id']) && isset($_SESSION['last_activity']) &&
           (time() - $_SESSION['last_activity']) < SESSION_TIMEOUT;
}

function isAdmin() {
    return isLoggedIn() && $_SESSION['role'] === 'admin';
}

function isReseller() {
    return isLoggedIn() && in_array($_SESSION['role'], ['reseller', 'admin']);
}

function requireLogin() {
    if (!isLoggedIn()) {
        $current = $_SERVER['REQUEST_URI'] ?? '';
        $isAdmin = strpos($current, '/admin/') !== false;
        if ($isAdmin) {
            header('Location: ' . SITE_URL . '/admin/login.php');
        } else {
            header('Location: ' . SITE_URL . '/login.php');
        }
        exit;
    }

    if (isset($_SESSION['user_id'])) {
        $now = time();
        $lastCheck = $_SESSION['device_last_check'] ?? 0;

        if ($now - $lastCheck > 10) {
            require_once __DIR__ . '/device_security.php';
            $token = getDeviceToken();
            $_SESSION['device_token']      = $token;
            $_SESSION['device_last_check'] = $now;
            $db = getDB();
            try {
                // Check if device exists
                $s = $db->prepare("SELECT id, is_blocked, is_active FROM user_devices WHERE user_id=? AND device_token=?");
                $s->execute([$_SESSION['user_id'], $token]);
                $d = $s->fetch();

                if ($d) {
                    // Device exists — update last_seen
                    $db->prepare("UPDATE user_devices SET last_seen=NOW(), login_count=login_count+1 WHERE id=?")->execute([$d['id']]);
                    if ($d['is_blocked'] || !$d['is_active']) {
                        $_SESSION['device_blocked'] = true;
                    } else {
                        $_SESSION['device_blocked'] = false;
                    }
                } else {
                    // New device — register it
                    $result = checkDeviceLogin($_SESSION['user_id']);
                    if (!$result['ok'] && $result['blocked']) {
                        $_SESSION['device_blocked'] = true;
                    } else {
                        $_SESSION['device_blocked'] = false;
                    }
                }
            } catch(Exception $e) {
                $_SESSION['device_blocked'] = false;
            }
        }

        if (!empty($_SESSION['device_blocked'])) {
            session_destroy();
            header('Location: ' . SITE_URL . '/device-blocked.php');
            exit;
        }
    }
    $_SESSION['last_activity'] = time();
}

function requireAdmin() {
    if (!isLoggedIn()) {
        header('Location: ' . SITE_URL . '/admin/login.php');
        exit;
    }
    if (!isAdmin()) {
        header('Location: ' . SITE_URL . '/admin/login.php?error=unauthorized');
        exit;
    }
    $_SESSION['last_activity'] = time();
}

function getCurrentUser() {
    if (!isLoggedIn()) return null;
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    return $stmt->fetch();
}

function getSetting($key) {
    $db = getDB();
    $stmt = $db->prepare("SELECT value FROM settings WHERE `key` = ?");
    $stmt->execute([$key]);
    $row = $stmt->fetch();
    return $row ? $row['value'] : null;
}

// Dynamic SITE_NAME from DB, fallback to default
if (!defined('SITE_NAME')) {
    $__siteName = getSetting('site_name');
    define('SITE_NAME', $__siteName ?: 'Priyo Telecom');
}

function formatMoney($amount) {
    return CURRENCY . ' ' . number_format($amount, 2);
}

function generateRef() {
    return 'PT' . strtoupper(substr(md5(uniqid()), 0, 10));
}

function detectOperator($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($phone) == 11) {
        $prefix = substr($phone, 0, 3);
    } elseif (strlen($phone) == 13) {
        $prefix = substr($phone, 2, 3);
    } else {
        return null;
    }
    
    $db = getDB();
    $operators = $db->query("SELECT * FROM operators WHERE status='active'")->fetchAll();
    foreach ($operators as $op) {
        $prefixes = json_decode($op['prefix'], true);
        if (in_array($prefix, $prefixes)) return $op;
    }
    return null;
}

function sanitize($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

function jsonResponse($success, $message, $data = []) {
    header('Content-Type: application/json');
    echo json_encode(array_merge(['success' => $success, 'message' => $message], $data));
    exit;
}

// ✅ USD to BDT rate — DB থেকে নেয়, fallback 110
function getUsdRate() {
    static $rate = null;
    if ($rate !== null) return $rate;
    try {
        $db = getDB();
        $r = $db->query("SELECT value FROM settings WHERE `key`='intl_usd_rate'")->fetchColumn();
        $rate = $r ? floatval($r) : 110;
    } catch(Exception $e) {
        $rate = 110;
    }
    return $rate;
}

// ✅ USD amount → BDT
function usdToBdt($usd) {
    return round(floatval($usd) * getUsdRate(), 2);
}
