<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'db.php';
require_once '../vendor/autoload.php';
require_once 'report_functions.php';

if (!isset($_SESSION['user_id'])) {
    die("Unauthorized");
}

$sale_id = $_GET['id'] ?? null;
if (!$sale_id) {
    die("Sale ID required");
}

// Fetch Sale Data
$stmt = $pdo->prepare("SELECT s.*, u.username, c.name as customer_name, c.email as customer_email, c.tin as customer_tin, c.vrn as customer_vrn, c.address as customer_address 
                       FROM sales s 
                       JOIN users u ON s.user_id = u.id 
                       LEFT JOIN customers c ON s.customer_id = c.id 
                       WHERE s.id = ?");
$stmt->execute([$sale_id]);
$sale = $stmt->fetch();

if (!$sale) {
    die("Sale not found");
}

$itemsStmt = $pdo->prepare("SELECT si.*, p.name FROM sale_items si JOIN products p ON si.product_id = p.id WHERE si.sale_id = ?");
$itemsStmt->execute([$sale_id]);
$items = $itemsStmt->fetchAll();

$settings = get_report_settings($pdo);
$currency = $settings['company_currency_code'] ?? 'USD';

$paper = $_GET['paper'] ?? ($settings['receipt_paper_size'] ?? 'A4');
$format = isset($_GET['download']) ? 'excel' : 'pdf';

$meta = [
    'Receipt ID' => '#' . $sale['id'],
    'Date / Time' => $sale['sale_date'],
    'Payment Method' => $sale['payment_method'],
    'Cashier' => $sale['username'],
    'Customer' => $sale['customer_name'] ?: 'Walk-in Customer'
];

if (!empty($sale['customer_tin'])) {
    $meta['Customer TIN'] = $sale['customer_tin'];
}

$customer_html = '';
if ($sale['customer_id']) {
    $show_tin = ($settings['receipt_show_tin'] ?? 'yes') === 'yes';
    $customer_html = '<div style="margin: 15px 0; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc;">';
    $customer_html .= '<div style="font-size: 14px; font-weight: bold; color: #1e293b; margin-bottom: 2px;">' . strtoupper($sale['customer_name']) . '</div>';
    if ($show_tin && !empty($sale['customer_tin'])) {
        $customer_html .= '<div style="font-size: 11px; color: #64748b;"><strong>TAX ID / TIN:</strong> ' . $sale['customer_tin'] . '</div>';
    }
    if (!empty($sale['customer_address'])) {
        $customer_html .= '<div style="font-size: 10px; color: #64748b; margin-top: 4px;">' . $sale['customer_address'] . '</div>';
    }
    $customer_html .= '</div>';
}

$customer_pos = $settings['receipt_customer_pos'] ?? 'top';

ob_start();

if ($paper === '58mm' || $paper === '80mm') {
    // Thermal Optimized Layout
    ?>
    <div class="header">
        <?php if (($settings['receipt_show_logo'] ?? 'yes') === 'yes' && !empty($settings['company_logo'])): ?>
            <?php 
                $logo_path = realpath(__DIR__ . '/../' . $settings['company_logo']);
                if ($logo_path && file_exists($logo_path)):
                    $mime_type = mime_content_type($logo_path);
                    $base64_img = base64_encode(file_get_contents($logo_path));
            ?>
                <img src="data:<?php echo $mime_type; ?>;base64,<?php echo $base64_img; ?>" class="logo">
            <?php endif; ?>
        <?php endif; ?>
        <div class="brand-name"><?php echo strtoupper($settings['company_name'] ?? 'JUSTSALE'); ?></div>
        <div style="font-size: 10px;">
            <?php echo ($settings['company_address'] ?? ''); ?><br>
            <?php echo ($settings['company_phone'] ?? ''); ?>
        </div>
        <div class="report-title">SALES RECEIPT</div>
        <div style="font-size: 10px; margin-top: 5px;">
            ID: #<?php echo $sale['id']; ?><br>
            Date: <?php echo $sale['sale_date']; ?>
        </div>
    </div>

    <?php if ($sale['customer_id']): ?>
        <div style="margin: 10px 0; border-bottom: 1px dashed #000; padding-bottom: 5px;">
            <div class="fw-bold">CUSTOMER: <?php echo strtoupper($sale['customer_name']); ?></div>
            <?php if (!empty($sale['customer_tin'])): ?>
                <div style="font-size: 10px;">TIN: <?php echo $sale['customer_tin']; ?></div>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <table class="table" style="margin-bottom: 10px;">
        <thead>
            <tr>
                <th width="40%">Item</th>
                <th width="20%" class="text-center">Qty</th>
                <th width="40%" class="text-right">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($items as $item): ?>
                <tr>
                    <td><?php echo $item['name']; ?></td>
                    <td class="text-center"><?php echo $item['quantity']; ?></td>
                    <td class="text-right"><?php echo format_amount($item['subtotal']); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div style="border-top: 1px solid #000; padding-top: 5px;">
        <?php 
            $tax_rate = floatval($settings['tax_percent'] ?? 0);
            $total = floatval($sale['total_amount']);
        ?>
        <div style="display: flex; justify-content: space-between; font-weight: bold; font-size: 14px;">
            <span>TOTAL DUE</span>
            <span class="text-right"><?php echo $currency . ' ' . format_amount($total); ?></span>
        </div>
        <div style="font-size: 10px; margin-top: 5px;">
            Method: <?php echo $sale['payment_method']; ?><br>
            Paid: <?php echo $currency . ' ' . format_amount($sale['amount_paid']); ?><br>
            Change: <?php echo $currency . ' ' . format_amount($sale['change_amount']); ?>
        </div>
    </div>

    <div class="footer">
        <?php if (!empty($settings['receipt_footer'])) echo nl2br($settings['receipt_footer']) . '<br>'; ?>
        Thank you for your visit!<br>
        Cashier: <?php echo $sale['username']; ?>
    </div>
    <?php
} elseif ($paper === '58mm-text' || $paper === '80mm-text') {
    @ob_end_clean(); // Stop capturing for PDF
    $width = ($paper === '58mm-text' ? 32 : 48);
    $line = str_repeat('-', $width) . "\n";
    $doubleLine = str_repeat('=', $width) . "\n";
    
    $center = function($text) use ($width) {
        $text = trim($text);
        if (strlen($text) > $width) return substr($text, 0, $width) . "\n";
        return str_pad($text, $width, " ", STR_PAD_BOTH) . "\n";
    };

    $boldOn = "\x1b\x45\x01";
    $boldOff = "\x1b\x45\x00";

    $out = "";
    // -------------------------------------------------------------------------
    // Header
    // -------------------------------------------------------------------------
    $out .= "\n"; // Top Padding
    $out .= $boldOn . $center(strtoupper($settings['company_name'] ?? 'JUSTSALE')) . $boldOff;
    if (!empty($settings['company_address'])) $out .= $center($settings['company_address']);
    if (!empty($settings['company_city'])) $out .= $center($settings['company_city']);
    if (!empty($settings['company_phone'])) $out .= $center("Tel: " . $settings['company_phone']);
    if (!empty($settings['company_email'])) $out .= $center($settings['company_email']);
    if (!empty($settings['company_website'])) $out .= $center($settings['company_website']);
    
    // Tax Details
    $taxInfo = "";
    if (!empty($settings['company_tin'])) $taxInfo .= "TIN: " . $settings['company_tin'] . " ";
    if (!empty($settings['company_vrn'])) $taxInfo .= "VRN: " . $settings['company_vrn'];
    if (trim($taxInfo)) $out .= $center(trim($taxInfo));
    
    $out .= "\n";
    $out .= $boldOn . $center("SALES RECEIPT") . $boldOff;
    $out .= $center("ID: #" . $sale['id']);
    $out .= $center("Date: " . $sale['sale_date']);
    $out .= $line;
    
    // -------------------------------------------------------------------------
    // Customer Info (Now Centered)
    // -------------------------------------------------------------------------
    if ($sale['customer_id']) {
        $out .= $center("CUSTOMER: " . strtoupper($sale['customer_name']));
        if (!empty($sale['customer_tin'])) $out .= $center("TIN: " . $sale['customer_tin']);
        $out .= $line;
    }

    // -------------------------------------------------------------------------
    // Product Table
    // -------------------------------------------------------------------------
    $col1 = $width - 16; $col2 = 6; $col3 = 10;
    $out .= $boldOn . str_pad("Item", $col1) . str_pad("Qty", $col2, " ", STR_PAD_BOTH) . str_pad("Total", $col3, " ", STR_PAD_LEFT) . $boldOff . "\n";
    $out .= $line;
    
    foreach($items as $item) {
        $name = substr($item['name'], 0, $col1 - 1);
        $out .= str_pad($name, $col1) . 
                str_pad($item['quantity'], $col2, " ", STR_PAD_BOTH) . 
                str_pad(format_amount($item['subtotal']), $col3, " ", STR_PAD_LEFT) . "\n";
    }
    
    // -------------------------------------------------------------------------
    // Totals (Detailed with Tax)
    // -------------------------------------------------------------------------
    $tax_rate = floatval($settings['tax_percent'] ?? 0);
    $total_val = floatval($sale['total_amount']);
    $tax_val = ($total_val * $tax_rate) / (100 + $tax_rate);
    $sub_val = $total_val - $tax_val;

    if ($tax_rate > 0) {
        $out .= str_pad("Subtotal", $width - 12) . str_pad(format_amount($sub_val), 12, " ", STR_PAD_LEFT) . "\n";
        $out .= str_pad("VAT / Tax (".$tax_rate."%)", $width - 12) . str_pad(format_amount($tax_val), 12, " ", STR_PAD_LEFT) . "\n";
    }

    $out .= $boldOn . str_pad("TOTAL DUE", $width - 12) . str_pad($currency . " " . format_amount($total_val), 12, " ", STR_PAD_LEFT) . $boldOff . "\n";
    $out .= str_repeat('.', $width) . "\n";
    $out .= "Payment Method: " . ($sale['payment_method'] ?: 'CASH') . "\n";
    $out .= "Amount Paid   : " . $currency . " " . format_amount($sale['amount_paid']) . "\n";
    $out .= "Change Due    : " . $currency . " " . format_amount($sale['change_amount']) . "\n";
    $out .= $line;
    
    // -------------------------------------------------------------------------
    // Footer
    // -------------------------------------------------------------------------
    if (!empty($settings['receipt_footer'])) $out .= $center($settings['receipt_footer']);
    $out .= $center("Thank you for your visit!");
    $out .= $center("Cashier: " . $sale['username']);
    $out .= $line . "\n"; // Concluding line
    $out .= "\n\n\n\n\n"; // Feeds
    $out .= "\x1d\x56\x42\x00"; // GS V 66 0 (Standard Paper Cut)

    if (isset($return_content) && $return_content) {
        $pdf_output = $out;
    } else {
        header('Content-Type: text/plain');
        echo $out;
    }
    return;
} else {
    // Standard A4 Layout
    echo render_report_header("Official Sales Receipt", $settings, 'pdf', $meta);
    
    // Customer Top Position
    if ($customer_pos === 'top') echo $customer_html;
    
    if (!empty($settings['receipt_header'])) {
        echo '<div style="margin: 15px 0; font-style: italic; color: #555; text-align: center; border: 1px dashed #ddd; padding: 10px; border-radius: 5px;">' . nl2br($settings['receipt_header']) . '</div>';
    }
    ?>
    <table class="table">
        <thead>
            <tr>
                <th>Item Description</th>
                <th class="text-center">Qty</th>
                <th class="text-right">Unit Price</th>
                <th class="text-right">Subtotal</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($items as $item): ?>
                <tr>
                    <td><strong><?php echo $item['name']; ?></strong></td>
                    <td class="text-center"><?php echo $item['quantity']; ?></td>
                    <td class="text-right"><?php echo format_amount($item['price']); ?></td>
                    <td class="text-right fw-bold"><?php echo format_amount($item['subtotal']); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php 
        $tax_rate = floatval($settings['tax_percent'] ?? 0);
        $total = floatval($sale['total_amount']);
        $tax_amount = ($total * $tax_rate) / (100 + $tax_rate); // Inclusive
        $subtotal = $total - $tax_amount;
    ?>

    <div style="float: right; width: 300px; margin-top: 20px;">
        <table style="width: 100%; border-collapse: collapse;">
            <tr>
                <td style="padding: 5px 0;">Subtotal (Tax Excl.)</td>
                <td class="text-right"><?php echo format_amount($subtotal); ?></td>
            </tr>
            <tr>
                <td style="padding: 5px 0;">VAT / Tax (<?php echo $tax_rate; ?>%)</td>
                <td class="text-right"><?php echo format_amount($tax_amount); ?></td>
            </tr>
            <tr style="font-size: 16px;">
                <td style="padding: 10px 0; border-top: 2px solid #333; font-weight: bold;">TOTAL PAID</td>
                <td class="text-right fw-bold" style="padding: 10px 0; border-top: 2px solid #333; color: #4361ee;">
                    <?php echo $currency . ' ' . format_amount($total); ?>
                </td>
            </tr>
        </table>
    </div>
    <div style="clear: both;"></div>
    <?php if ($customer_pos === 'bottom') echo $customer_html; ?>
    <?php if(!empty($settings['receipt_footer'])) echo '<div style="margin-top: 30px; text-align: center; font-weight: bold; color: #333;">' . nl2br($settings['receipt_footer']) . '</div>'; ?>
    <?php echo render_report_footer($settings); ?>
    <?php
}

$html = ob_get_clean();

// --- NEW: PLAIN TEXT THERMAL GENERATION ---
if (strpos($paper, '-text') !== false) {
    $is_80 = (strpos($paper, '80mm') !== false);
    $width = $is_80 ? 42 : 32;
    $line = str_repeat('-', $width);
    
    $txt = str_pad(strtoupper($settings['company_name'] ?? 'JUSTSALE'), $width, ' ', STR_PAD_BOTH) . "\n";
    if (!empty($settings['company_address'])) $txt .= str_pad($settings['company_address'], $width, ' ', STR_PAD_BOTH) . "\n";
    if (!empty($settings['company_phone'])) $txt .= str_pad("Tel: ".$settings['company_phone'], $width, ' ', STR_PAD_BOTH) . "\n";
    if (!empty($settings['company_tin'])) $txt .= str_pad("TIN: ".$settings['company_tin'], $width, ' ', STR_PAD_BOTH) . "\n";
    
    $txt .= $line . "\n";
    $txt .= str_pad("SALES RECEIPT", $width, ' ', STR_PAD_BOTH) . "\n";
    $txt .= "ID: #".$sale['id']."\n";
    $txt .= "Date: ".$sale['sale_date']."\n";
    $txt .= "Cashier: ".$sale['username']."\n";
    if ($sale['customer_name']) $txt .= "Customer: ".strtoupper($sale['customer_name'])."\n";
    $txt .= $line . "\n";
    
    $txt .= str_pad("ITEM", $width - 15, ' ', STR_PAD_RIGHT) . str_pad("QTY", 5, ' ', STR_PAD_BOTH) . str_pad("TOTAL", 10, ' ', STR_PAD_LEFT) . "\n";
    foreach ($items as $i) {
        $name = substr($i['name'], 0, $width - 17);
        $txt .= str_pad($name, $width - 15, ' ', STR_PAD_RIGHT) . str_pad($i['quantity'], 5, ' ', STR_PAD_BOTH) . str_pad(format_amount($i['subtotal']), 10, ' ', STR_PAD_LEFT) . "\n";
    }
    $txt .= $line . "\n";
    
    $total_label = "TOTAL ".$currency;
    $txt .= str_pad($total_label, $width - 15, ' ', STR_PAD_RIGHT) . str_pad("", 5) . str_pad(format_amount($sale['total_amount']), 10, ' ', STR_PAD_LEFT) . "\n";
    $txt .= "Method: ".$sale['payment_method']."\n";
    $txt .= "Paid: ".format_amount($sale['amount_paid'])."\n";
    $txt .= $line . "\n";
    if (!empty($settings['receipt_footer'])) $txt .= str_pad($settings['receipt_footer'], $width, ' ', STR_PAD_BOTH) . "\n";
    $txt .= str_pad("Thank you!", $width, ' ', STR_PAD_BOTH) . "\n\n\n\n\n";
    $txt .= "\x1d\x56\x42\x00"; // GS V 66 0 (Standard Paper Cut)

    if (isset($return_content) && $return_content) {
        $pdf_output = $txt;
    } else {
        header("Content-Type: text/plain");
        echo $txt;
    }
    exit;
}

$fileName = "Receipt_{$sale_id}_" . date('Ymd');
if (isset($_GET['download']) && $_GET['download'] == 'excel') {
    if (isset($return_content) && $return_content) {
        $pdf_output = export_to_excel($html, $fileName . ".xls", "Sales Receipt", false);
    } else {
        export_to_excel($html, $fileName . ".xls", "Sales Receipt");
    }
} else {
    if (isset($return_content) && $return_content) {
        $pdf_output = export_to_pdf($html, $fileName . ".pdf", 'portrait', false, true, $paper);
    } else {
        $pdf_content = export_to_pdf($html, $fileName . ".pdf", 'portrait', false, true, $paper);
        
        if (!empty($pdf_content)) {
            // Save copy to receipts folder
            $savePath = __DIR__ . "/../receipts/" . $fileName . ".pdf";
            if (!is_dir(__DIR__ . "/../receipts/")) {
                mkdir(__DIR__ . "/../receipts/", 0777, true);
            }
            file_put_contents($savePath, $pdf_content);
        }
        
        // Output to browser
        header("Content-Type: application/pdf");
        header("Content-Disposition: inline; filename=\"$fileName.pdf\"");
        echo $pdf_content;
    }
}
