<?php
// যেকোনো ফোল্ডার থেকে সেশন এবং কনফিগ ফাইল লোড করা
if (session_status() === PHP_SESSION_NONE) { session_start(); }
$doc_root = $_SERVER['DOCUMENT_ROOT'];

$config_loaded = false;
if (file_exists($doc_root . '/config.php')) { require_once $doc_root . '/config.php'; $config_loaded = true; } 
elseif (file_exists('../config.php')) { require_once '../config.php'; $config_loaded = true; }
elseif (file_exists('../../config.php')) { require_once '../../config.php'; $config_loaded = true; }

if (!$config_loaded) { die("System Configuration Error."); }

// ----------------------------------------------------------------------
// Global Auto-Login Check (Highly Secure & Cookie Synced)
// ----------------------------------------------------------------------
if (!isset($_SESSION['user_logged_in']) && isset($_COOKIE['auth_remember']) && isset($conn)) {
    $cookie_token = $_COOKIE['auth_remember'];
    $hashed_token = hash('sha256', $cookie_token); 
    
    // ডাটাবেসে চেক করা হচ্ছে টোকেনটি আছে কিনা (লগআউট করলে ডাটাবেসে টোকেন NULL হয়ে যাবে)
    $stmt = $conn->prepare("SELECT id, fullname, is_verified FROM users WHERE remember_token=? AND is_verified=1 LIMIT 1");
    $stmt->bind_param("s", $hashed_token);
    $stmt->execute();
    $res = $stmt->get_result();
    
    if ($res->num_rows > 0) {
        $user = $res->fetch_assoc();
        session_regenerate_id(true); // Session Fixation Protection
        $_SESSION['user_logged_in'] = true;
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['fullname'];
    } else {
        // যদি ডাটাবেসে টোকেন না থাকে (যেমন ইউজার লগআউট করে ফেলেছে), তাহলে ফেক/পুরনো কুকিটি মুছে ফেলা হবে
        setcookie('auth_remember', '', time() - 3600, '/');
    }
    $stmt->close();
}

$is_logged_in = isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true;

// 100% SEO Dynamic Setup (Global Scope)
$seo_title = isset($page_title) ? $page_title : "Free Invoice Generator | Create Professional Invoices Online";
$seo_desc = isset($page_description) ? $page_description : "Use our Free Invoice Generator to create professional invoices online. Instantly download PDF invoices. No sign-up required, 100% free invoice maker.";
$seo_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$seo_image = "https://" . $_SERVER['HTTP_HOST'] . "/assets/images/og-image.jpg"; 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- Website Favicon -->
    <link rel="icon" type="image/x-icon" href="/assets/favicon.ico">
    <link rel="apple-touch-icon" href="/assets/favicon.ico">
    
    <!-- SEO Meta Tags -->
    <title><?php echo htmlspecialchars($seo_title, ENT_QUOTES, 'UTF-8'); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($seo_desc, ENT_QUOTES, 'UTF-8'); ?>">
    <link rel="canonical" href="<?php echo htmlspecialchars($seo_url, ENT_QUOTES, 'UTF-8'); ?>">
    <meta name="robots" content="index, follow">

    <!-- Open Graph (Facebook, WhatsApp, LinkedIn Preview) -->
    <meta property="og:site_name" content="Free Invoice Generator">
    <meta property="og:title" content="<?php echo htmlspecialchars($seo_title, ENT_QUOTES, 'UTF-8'); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($seo_desc, ENT_QUOTES, 'UTF-8'); ?>">
    <meta property="og:image" content="<?php echo $seo_image; ?>">
    <meta property="og:url" content="<?php echo htmlspecialchars($seo_url, ENT_QUOTES, 'UTF-8'); ?>">
    <meta property="og:type" content="website">

    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo htmlspecialchars($seo_title, ENT_QUOTES, 'UTF-8'); ?>">
    <meta name="twitter:description" content="<?php echo htmlspecialchars($seo_desc, ENT_QUOTES, 'UTF-8'); ?>">
    <meta name="twitter:image" content="<?php echo $seo_image; ?>">

    <!-- Google Site Name Schema -->
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "WebSite",
      "name": "Free Invoice Generator",
      "alternateName": "Invoice Generator Free",
      "url": "https://invoice-generatorfree.com/"
    }
    </script>
    
    <!-- Fonts and CSS (Absolute Path) -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/header.css">
</head>
<body>

<header>
    <!-- Logo Section -->
    <a href="/" class="logo-wrapper" aria-label="Free Invoice Generator Home">
        <img src="/assets/favicon.ico" alt="Invoice Generator Logo" class="header-logo">
        <div class="logo-text">invoice-<span>generatorfree</span>.com</div>
    </a>
    
    <!-- Desktop Navigation -->
    <div class="desktop-nav">
        <a href="/templates"><i class="fas fa-layer-group"></i> Templates</a>
        <a href="/pricing"><i class="fas fa-tags"></i> Pricing</a>
        <a href="/faq"><i class="fas fa-question-circle"></i> FAQ</a>
        <a href="/contact"><i class="fas fa-headset"></i> Contact Us</a>
        
        <div class="desktop-auth">
            <?php if($is_logged_in): ?>
                <a href="/dashboard/create" class="btn-signup"><i class="fas fa-plus-circle"></i> New Invoice</a>
                <a href="/dashboard" class="user-dropdown">
                    <div class="user-avatar-small"><?php echo strtoupper(substr($_SESSION['user_name'], 0, 1)); ?></div>
                    Dashboard
                </a>
                <a href="/api/auth/logout_api.php" style="color: #ef4444; font-size: 20px; margin-left: 10px;" title="Logout"><i class="fas fa-sign-out-alt"></i></a>
            <?php else: ?>
                <a href="/login" class="btn-login">Log In</a>
                <a href="/signup" class="btn-signup">Create Free Account</a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Mobile Menu Toggle -->
    <div class="menu-btn" onclick="toggleMenu()">
        <i class="fas fa-bars"></i>
    </div>
</header>

<!-- Mobile Sidebar -->
<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <h3>Navigation</h3>
        <button class="close-btn" onclick="toggleMenu()"><i class="fas fa-times"></i></button>
    </div>
    
    <div class="sidebar-links">
        <?php if($is_logged_in): ?>
            <a href="/dashboard"><i class="fas fa-chart-pie"></i> Dashboard</a>
            <a href="/dashboard/create"><i class="fas fa-file-invoice"></i> My Invoices</a>
            <a href="/dashboard/settings"><i class="fas fa-user-cog"></i> Settings</a>
            <hr>
        <?php endif; ?>

        <a href="/templates"><i class="fas fa-layer-group"></i> Templates</a>
        <a href="/pricing"><i class="fas fa-tags"></i> Pricing</a>
        <a href="/faq"><i class="fas fa-question-circle"></i> FAQ</a>
        <a href="/contact"><i class="fas fa-headset"></i> Contact Us</a>
        <hr>
        
        <?php if($is_logged_in): ?>
            <a href="/api/auth/logout_api.php" style="color: #ef4444;"><i class="fas fa-sign-out-alt" style="color: #ef4444;"></i> Logout Account</a>
        <?php else: ?>
            <a href="/login"><i class="fas fa-sign-in-alt"></i> Log In</a>
            <a href="/signup" style="background: var(--primary-green); color: white; justify-content: center; font-weight: 600;"><i class="fas fa-user-plus" style="color: white;"></i> Create Free Account</a>
        <?php endif; ?>
    </div>
</div>

<div class="menu-overlay" id="menuOverlay" onclick="toggleMenu()"></div>

<script src="/assets/js/header.js"></script>