<?php
// ROOT CONFIG.PHP - FINAL CORRECTED VERSION

// Start session safely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// --- 1. DATABASE CREDENTIALS ---
$DB_HOST = "localhost";   
$DB_USER = "bestseba_bdtop";            
$DB_PASS = "bestseba_bdtop"; // IMPORTANT: Add your password!   
$DB_NAME = "bestseba_bdtop";            
$DB_PORT = 3306;

// --- 2. PDO DATABASE CONNECTION ---
try {
    $pdo = new PDO(
        "mysql:host=$DB_HOST;port=$DB_PORT;dbname=$DB_NAME;charset=utf8mb4",
        $DB_USER,
        $DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );
} catch (PDOException $e) {
    die("DB connection failed: " . $e->getMessage());
}

// --- 3. CMS SETTINGS LOADER ---
try {
    $settings_stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
    $settings_from_db = $settings_stmt->fetchAll();
    
    $settings = [];
    foreach ($settings_from_db as $setting) {
        $settings[$setting['setting_key']] = $setting['setting_value'];
    }
} catch (Exception $e) {
    $settings = [];
}

// --- 4. HELPER FUNCTIONS ---
if (!function_exists('h')) {
    function h($str) {
        return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');
    }
}
if (!function_exists('set_flash')) {
    function set_flash($msg, $type = "success") {
        $_SESSION['flash'] = ['msg' => $msg, 'type' => $type];
    }
}
if (!function_exists('show_flash')) {
    function show_flash() {
        if (!empty($_SESSION['flash'])) {
            $f = $_SESSION['flash'];
            $alert_class = ($f['type'] == 'error') ? 'danger' : $f['type'];
            echo '<div class="alert alert-' . h($alert_class) . '">' . h($f['msg']) . '</div>';
            unset($_SESSION['flash']);
        }
    }
}
if (!function_exists('redirect')) {
    function redirect($url) {
        header("Location: $url");
        exit;
    }
}
if (!function_exists('is_post')) {
    function is_post() {
        return $_SERVER['REQUEST_METHOD'] === 'POST';
    }
}

// --- 5. CSRF PROTECTION FUNCTIONS ---
if (!function_exists('csrf_token')) {
    function csrf_token() {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }
}
if (!function_exists('csrf_field')) {
    function csrf_field() {
        echo '<input type="hidden" name="csrf_token" value="' . csrf_token() . '">';
    }
}
if (!function_exists('verify_csrf')) {
    function verify_csrf() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (empty($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
                die("CSRF token mismatch");
            }
        }
    }
}

// --- 6. AUTHENTICATION FUNCTIONS ---
if (!function_exists('require_login')) {
    function require_login() {
        $current = basename($_SERVER['PHP_SELF']);
        $public_pages = ['login.php','signup.php'];

        if (!isset($_SESSION['user_id']) && !in_array($current, $public_pages)) {
            if (strpos($_SERVER['REQUEST_URI'], '/admin/') === false) {
                redirect('login.php');
            }
        }
    }
}
if (!function_exists('is_admin')) {
    function is_admin() {
        return !empty($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1;
    }
}

// --- 7. TELEGRAM NOTIFICATION FUNCTION (using Vercel Relay) ---
if (!function_exists('sendTelegramMessage')) {
    function sendTelegramMessage($message, $settings) {
        $botToken = $settings['telegram_bot_token'] ?? null;
        $chatId = $settings['telegram_chat_id'] ?? null;

        if (!$botToken || !$chatId) {
            return false;
        }
        
        $relayUrl = 'https://telegram-two-fawn.vercel.app/api/telegram';

        $data = json_encode([
            'botToken' => $botToken,
            'chatId' => $chatId,
            'message' => $message
        ]);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $relayUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }
}


