<?php
// Load credentials from separate file (not in git)
if (!file_exists(__DIR__ . '/config.local.php')) {
    die('Configuration file missing. Please create config.local.php');
}

$config = require __DIR__ . '/config.local.php';

// Telegram notifications for error reports (values live in config.local.php)
if (!empty($config['telegram_bot_token'])) {
    define('TELEGRAM_BOT_TOKEN', $config['telegram_bot_token']);
    define('TELEGRAM_CHAT_ID', $config['telegram_chat_id'] ?? '');
}

$host = $config['db_host'];
$user = $config['db_user'];
$password = $config['db_password'];
$dbname = $config['db_name'];

define('SHOPIFY_LOCATION_ID', 'gid://shopify/Location/90679607572');

/**
 * Auto-detect the application's base URL for building absolute URLs
 * Works whether installed in root or subdirectory
 * Examples:
 * - https://kapichorori.com/invoice-system/4
 * - https://yourdomain.com
 * - http://localhost/myapp
 */
function getBaseUrl() {
    static $baseUrl = null;
    
    if ($baseUrl !== null) {
        return $baseUrl;
    }
    
    // Determine protocol
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    
    // Get host
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    
    // IMPORTANT: Use __FILE__ (config.php location) not SCRIPT_FILENAME
    // This ensures we get /invoice-system/4 NOT /invoice-system/4/api
    // __FILE__ points to config.php which is in the app root
    $configPath = dirname(__FILE__);
    $docRoot = $_SERVER['DOCUMENT_ROOT'] ?? '';
    
    // Remove document root from config path to get relative path
    if ($docRoot !== '' && strpos($configPath, $docRoot) === 0) {
        $relativePath = substr($configPath, strlen($docRoot));
        // Normalize slashes
        $relativePath = str_replace('\\', '/', $relativePath);
        $relativePath = rtrim($relativePath, '/');
    } else {
        // Fallback: try to detect from REQUEST_URI
        $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
        // Remove /api/script.php to get just /invoice-system/4
        $relativePath = dirname(dirname($scriptName));
        if ($relativePath === '/' || $relativePath === '.') {
            $relativePath = '';
        }
    }
    
    // Build full base URL
    $baseUrl = $protocol . $host . $relativePath;
    
    return $baseUrl;
}

// Define the base URL constant for easy access throughout the app
define('BASE_URL', getBaseUrl());

// Create MySQLi connection
$conn = new mysqli($host, $user, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    // Return JSON error for API calls or AJAX
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strpos($_SERVER['REQUEST_URI'], 'api/') !== false) {
        header('Content-Type: application/json');
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Database connection error.'
        ]);
        exit;
    } else {
        // Friendly HTML message for normal pages
        http_response_code(500);
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>InvOps - Database Error</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background: #f4f4f4;
                    margin: 0;
                    padding: 0;
                }
                .error-box {
                    max-width: 600px;
                    margin: 60px auto;
                    background: #fff;
                    border-radius: 6px;
                    box-shadow: 0 2px 6px rgba(0,0,0,0.15);
                    padding: 20px 24px;
                    border-left: 5px solid #e74c3c;
                }
                h1 {
                    margin-top: 0;
                    font-size: 1.4rem;
                    color: #c0392b;
                }
                p {
                    font-size: 0.95rem;
                    color: #555;
                }
                code {
                    background: #f7f7f7;
                    padding: 2px 4px;
                    border-radius: 3px;
                    font-size: 0.9rem;
                }
            </style>
        </head>
        <body>
        <div class="error-box">
            <h1>Database connection error</h1>
            <p>The system could not connect to the database. Please try again later.</p>
        </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// Set charset
$conn->set_charset("utf8mb4");

// Optional: set default timezone (adjust if you prefer another)
if (function_exists('date_default_timezone_set')) {
    date_default_timezone_set('America/New_York');
}

/**
 * Helper to check if a table exists in the current database.
 */
function tableExists(mysqli $conn, string $tableName): bool
{
    static $cache = [];

    if (isset($cache[$tableName])) {
        return $cache[$tableName];
    }

    $sql = "SELECT 1 FROM information_schema.TABLES
            WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
            LIMIT 1";
    if ($stmt = $conn->prepare($sql)) {
        $dbName = $conn->real_escape_string($conn->query("SELECT DATABASE()")->fetch_row()[0] ?? '');
        $stmt->bind_param('ss', $dbName, $tableName);
        if ($stmt->execute()) {
            $stmt->store_result();
            $exists = $stmt->num_rows > 0;
            $stmt->close();
            $cache[$tableName] = $exists;
            return $exists;
        }
        $stmt->close();
    }

    $cache[$tableName] = false;
    return false;
}

/**
 * Centralized Audit Log helper.
 * Records field-level changes into audit_log table if it exists.
 *
 * @param mysqli $conn
 * @param string $entityType   e.g. 'customer', 'order', 'invoice'
 * @param int    $entityId
 * @param string $fieldName
 * @param mixed  $oldValue
 * @param mixed  $newValue
 */
function logAuditChange(mysqli $conn, $entityType, $entityId, $fieldName, $oldValue, $newValue): void
{
    // If nothing changed, skip
    if ($oldValue === $newValue) {
        return;
    }

    // Only log if the table exists
    if (!tableExists($conn, 'audit_log')) {
        return;
    }

    // Resolve who changed it
    $changedBy = 'system';
    if (session_status() === PHP_SESSION_ACTIVE) {
        if (!empty($_SESSION['username'])) {
            $changedBy = $_SESSION['username'];
        } elseif (!empty($_SESSION['email'])) {
            $changedBy = $_SESSION['email'];
        }
    }

    // Normalize complex values
    if (is_array($oldValue) || is_object($oldValue)) {
        $oldValue = json_encode($oldValue);
    }
    if (is_array($newValue) || is_object($newValue)) {
        $newValue = json_encode($newValue);
    }

    $sql = "INSERT INTO audit_log (entity_type, entity_id, field_name, old_value, new_value, changed_by)
            VALUES (?, ?, ?, ?, ?, ?)";

    if ($stmt = $conn->prepare($sql)) {
        $entityType  = (string)$entityType;
        $fieldName   = (string)$fieldName;
        $oldValueStr = (string)$oldValue;
        $newValueStr = (string)$newValue;
        $changedBy   = (string)$changedBy;

        $stmt->bind_param(
            'sissss',
            $entityType,
            $entityId,
            $fieldName,
            $oldValueStr,
            $newValueStr,
            $changedBy
        );
        $stmt->execute();
        $stmt->close();
    }
}

/**
 * Centralized error logger.
 * Creates a short error_code and stores technical details in error_reports.
 * Returns the generated error_code so you can show it to the user.
 *
 * Usage example in any page:
 *
 *   $code = logErrorAndGetCode($conn, "Prepare failed: " . $conn->error);
 *   echo "<script>window.LAST_ERROR_CODE = '".htmlspecialchars($code, ENT_QUOTES)."';</script>";
 */
function logErrorAndGetCode(mysqli $conn, string $errorMessage, ?string $pageUrl = null, ?int $userId = null): string
{
    // Generate a human-readable error code, e.g. ER-20251211-ABC123
    $random = substr(bin2hex(random_bytes(4)), 0, 6);
    $code   = 'ER-' . date('Ymd') . '-' . strtoupper($random);

    if ($pageUrl === null && isset($_SERVER['REQUEST_URI'])) {
        $pageUrl = $_SERVER['REQUEST_URI'];
    }

    $browserInfo = $_SERVER['HTTP_USER_AGENT'] ?? '';

    // Only log if table exists, to avoid 500s on fresh installs
    if (!tableExists($conn, 'error_reports')) {
        return $code;
    }

    $sql = "INSERT INTO error_reports (user_id, error_code, page_url, error_message, browser_info)
            VALUES (?, ?, ?, ?, ?)";

    if ($stmt = $conn->prepare($sql)) {
        // Try to pick user_id from session if not passed
        if (($userId === null || $userId === '') && isset($_SESSION['user_id'])) {
            $userId = $_SESSION['user_id'];
        }

        $stmt->bind_param(
            'issss',
            $userId,
            $code,
            $pageUrl,
            $errorMessage,
            $browserInfo
        );
        $stmt->execute();
        $stmt->close();
    }

    return $code;
}
?>
