<?php
/**
 * WaterCure - Site Configuration
 * Independent auth system for separate domain deployment
 */

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Database Configuration (shared across all cure sites)
define('DB_HOST', 'localhost');
define('DB_NAME', 'multicure_db');
define('DB_USER', 'multicure_user');
define('DB_PASS', 'CHANGE_THIS_PASSWORD');

// Site Configuration
define('SITE_NAME', 'WaterCure');
define('SITE_TAGLINE', 'Pure Water Solutions');
define('SITE_COLOR', '#0ea5e9');
define('SITE_KEY', 'watercure');

// Check if user is logged in as reseller
function isReseller() {
    return isset($_SESSION['reseller_logged_in']) && $_SESSION['reseller_logged_in'] === true;
}

// Get reseller info
function getResellerInfo() {
    if (isReseller()) {
        return [
            'id' => $_SESSION['reseller_id'] ?? null,
            'name' => $_SESSION['reseller_name'] ?? 'Reseller',
            'company' => $_SESSION['reseller_company'] ?? '',
            'discount' => $_SESSION['reseller_discount'] ?? 15
        ];
    }
    return null;
}

// Calculate reseller price
function getResellerPrice($regularPrice, $customDiscount = null) {
    if (!isReseller()) {
        return $regularPrice;
    }
    $discount = $customDiscount ?? ($_SESSION['reseller_discount'] ?? 15);
    return round($regularPrice * (1 - $discount / 100), 2);
}

// Format price for display
function formatPrice($price, $showReseller = true) {
    if (isReseller() && $showReseller) {
        return '<span class="reseller-price">R' . number_format($price, 2) . '</span>';
    }
    return 'R' . number_format($price, 2);
}

// Database connection function
function getDBConnection() {
    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
            ]
        );
        return $pdo;
    } catch (PDOException $e) {
        error_log("Database connection failed: " . $e->getMessage());
        return null;
    }
}

// CSRF Token functions
function generateCSRFToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
?>
