<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Product Barcode Generator - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/pos/products/barcode.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/pos/products/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}

// Require authentication
require_auth();

// Define helper functions if they don't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

// Get product ID from URL
$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$product_id) {
    die('Invalid product ID');
}

// Get product data
$product = null;
try {
    $product = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$product_id]);
} catch (Exception $e) {
    error_log("Error fetching product: " . $e->getMessage());
    die('Error loading product data');
}

if (!$product) {
    die('Product not found');
}

// Check if product has barcode
if (empty($product['barcode'])) {
    die('This product does not have a barcode');
}

// Get quantity from URL (default 1)
$quantity = isset($_GET['quantity']) ? min(100, max(1, (int)$_GET['quantity'])) : 1;

// Get paper size (default A4)
$paper_size = isset($_GET['paper']) ? $_GET['paper'] : 'a4';

// Set page title
$page_title = 'Barcode - ' . ($product['product_name'] ?? 'Product');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo escape_html($page_title); ?></title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- JsBarcode -->
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    
    <style>
        body {
            background: #f0f0f0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        
        .barcode-page {
            max-width: 800px;
            margin: 0 auto;
        }
        
        .barcode-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 30px;
            margin-bottom: 20px;
        }
        
        .barcode-label {
            border: 1px dashed #ccc;
            padding: 15px;
            text-align: center;
            background: white;
            page-break-inside: avoid;
            border-radius: 4px;
        }
        
        .barcode-label .product-name {
            font-size: 12px;
            font-weight: bold;
            margin-bottom: 5px;
            word-wrap: break-word;
        }
        
        .barcode-label .price {
            font-size: 14px;
            color: #28a745;
            font-weight: bold;
            margin: 5px 0;
        }
        
        .barcode-label svg {
            max-width: 100%;
            height: auto;
        }
        
        .controls {
            position: sticky;
            top: 20px;
            z-index: 1000;
        }
        
        .form-group {
            margin-bottom: 10px;
        }
        
        @media print {
            body {
                background: white;
                padding: 0;
            }
            .no-print {
                display: none !important;
            }
            .barcode-page {
                max-width: 100%;
            }
            .barcode-card {
                box-shadow: none;
                padding: 0;
                background: none;
            }
            .barcode-label {
                border: none;
                page-break-inside: avoid;
            }
        }
        
        /* Label sizes for different paper */
        .paper-a4 .barcode-label {
            width: 100%;
            margin-bottom: 20px;
        }
        
        .paper-label .barcode-label {
            width: 2in;
            height: 1in;
            float: left;
            margin: 5px;
            border: 1px solid #ccc;
            padding: 10px;
            font-size: 10px;
        }
        
        .paper-label .barcode-label .product-name {
            font-size: 9px;
        }
        
        .paper-label .barcode-label .price {
            font-size: 11px;
        }
        
        .paper-label .barcode-label .code {
            font-size: 8px;
        }
        
        /* Clear floats */
        .paper-label #barcodeContainer::after {
            content: "";
            clear: both;
            display: table;
        }
        
        .me-1 { margin-right: 0.25rem; }
        .me-2 { margin-right: 0.5rem; }
        .ms-2 { margin-left: 0.5rem; }
        .mb-2 { margin-bottom: 0.5rem; }
        .mb-4 { margin-bottom: 1.5rem; }
    </style>
</head>
<body class="paper-<?php echo escape_html($paper_size); ?>">
    <div class="barcode-page">
        <!-- Controls -->
        <div class="controls no-print mb-4">
            <div class="barcode-card">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <h4><?php echo escape_html($product['product_name'] ?? ''); ?></h4>
                        <p class="mb-0">
                            <strong>Code:</strong> <?php echo escape_html($product['product_code'] ?? ''); ?><br>
                            <strong>Barcode:</strong> <?php echo escape_html($product['barcode'] ?? ''); ?><br>
                            <strong>Price:</strong> <?php echo format_currency($product['unit_price'] ?? 0); ?>
                        </p>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex justify-content-end flex-wrap">
                            <div class="me-2 mb-2">
                                <label for="quantity" class="form-label d-block">Quantity</label>
                                <input type="number" class="form-control" id="quantity" value="<?php echo $quantity; ?>" min="1" max="100" style="width: 100px;">
                            </div>
                            
                            <div class="me-2 mb-2">
                                <label for="paper_size" class="form-label d-block">Paper</label>
                                <select class="form-select" id="paper_size" style="width: 120px;">
                                    <option value="a4" <?php echo $paper_size == 'a4' ? 'selected' : ''; ?>>A4 Sheet</option>
                                    <option value="label" <?php echo $paper_size == 'label' ? 'selected' : ''; ?>>Label Sheet</option>
                                </select>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label d-block">&nbsp;</label>
                                <div>
                                    <button type="button" class="btn btn-primary me-1" onclick="updatePage()">
                                        <i class="fas fa-sync-alt"></i> Update
                                    </button>
                                    
                                    <button type="button" class="btn btn-success" onclick="window.print()">
                                        <i class="fas fa-print"></i> Print
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Barcode Labels -->
        <div class="barcode-card">
            <div class="row" id="barcodeContainer">
                <?php for ($i = 0; $i < $quantity; $i++): ?>
                <div class="<?php echo $paper_size == 'label' ? 'col-6 col-sm-4' : 'col-12'; ?> mb-3">
                    <div class="barcode-label">
                        <div class="product-name"><?php echo escape_html($product['product_name'] ?? ''); ?></div>
                        <svg class="barcode" data-barcode="<?php echo escape_html($product['barcode'] ?? ''); ?>"></svg>
                        <div class="price"><?php echo format_currency($product['unit_price'] ?? 0); ?></div>
                        <div class="code" style="font-size: 10px; color: #666;"><?php echo escape_html($product['product_code'] ?? ''); ?></div>
                    </div>
                </div>
                <?php endfor; ?>
            </div>
        </div>

        <!-- Additional Info -->
        <div class="barcode-card no-print">
            <h5>Barcode Information</h5>
            <p class="mb-1">
                <strong>Format:</strong> Code 128<br>
                <strong>Barcode Value:</strong> <?php echo escape_html($product['barcode'] ?? ''); ?><br>
                <strong>Generated:</strong> <?php echo date('Y-m-d H:i:s'); ?>
            </p>
            <p class="text-muted small mb-0">
                <i class="fas fa-info-circle me-1"></i>
                These barcodes are optimized for printing. Use the print button or browser print function.
            </p>
        </div>
    </div>

    <!-- Font Awesome -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
    
    <script>
        // Generate barcodes
        function generateBarcodes() {
            try {
                JsBarcode(".barcode").init();
                console.log('Barcodes generated successfully');
            } catch (e) {
                console.error('Error generating barcodes:', e);
            }
        }
        
        // Update page with new quantity/paper size
        function updatePage() {
            const quantity = document.getElementById('quantity').value;
            const paper = document.getElementById('paper_size').value;
            window.location.href = '?id=<?php echo $product_id; ?>&quantity=' + quantity + '&paper=' + paper;
        }
        
        // Generate on load
        window.onload = function() {
            setTimeout(generateBarcodes, 100); // Small delay to ensure DOM is ready
        };
        
        // Regenerate after print dialog closes
        window.onafterprint = function() {
            setTimeout(generateBarcodes, 100);
        };
        
        // Handle quantity input validation
        document.getElementById('quantity').addEventListener('change', function(e) {
            let value = parseInt(this.value);
            if (isNaN(value) || value < 1) this.value = 1;
            if (value > 100) this.value = 100;
        });
        
        // Handle Enter key in quantity field
        document.getElementById('quantity').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                updatePage();
            }
        });
    </script>
</body>
</html>