<?php
session_start();
// Check if the user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Include database connection
include '../config/db.php';

// Fetch pharmacy details from settings table
$stmt = $pdo->prepare("SELECT * FROM settings WHERE id = 1"); // Assuming only one row in the settings table
$stmt->execute();
$pharmacy = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$pharmacy) {
    echo "Pharmacy details not found.";
    exit();
}

// Get the receipt number from the query string
$receipt_no = isset($_GET['receipt_no']) ? $_GET['receipt_no'] : '';

// Prepare the SQL statement to fetch sales records
$stmt = $pdo->prepare("SELECT * FROM sales WHERE receipt = ?");
$stmt->execute([$receipt_no]);

// Fetch the sale records
$sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$sales) {
    echo "No sale found for this receipt number.";
    exit();
}

// Calculate total amount and prepare items for display
$total_amount = 0;
$total_discount = 0;
$items = [];
foreach ($sales as $record) {
    $items[] = [
        'drug_name' => $record['drug_name'],
        'quantity' => $record['quantity'],
        'total' => $record['total'],
        'discount' => $record['discount'],
    ];
    $total_amount += $record['total'];
    $total_discount += $record['discount'];
}

// Display the receipt
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Receipt</title>
    <style>
        @page {
            margin: 0;
            size: 58mm auto; /* XP POS printer standard width */
        }

        body {
            margin: 0;
            padding: 0;
            font-family: 'Arial', sans-serif;
            font-size: 10px;
            width: 58mm;
            background: white;
        }

        .receipt {
            padding: 3mm 2mm;
            width: 54mm;
        }

        .header {
            text-align: center;
            margin-bottom: 3mm;
        }

        .store-name {
            font-size: 16px;
            font-weight: bold;
            margin: 0 0 2mm 0;
            text-transform: uppercase;
        }

        .store-info {
            font-size: 9px;
            margin: 2mm 0;
            line-height: 1.3;
        }

        .receipt-no {
            font-size: 10px;
            margin: 2mm 0;
            line-height: 1.4;
        }

        .divider {
            border-top: 1px dotted #000;
            margin: 2mm 0;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 2mm 0;
        }

        .items-table th {
            text-align: left;
            font-size: 9px;
            padding-bottom: 1mm;
            border-bottom: 1px solid #000;
        }

        .items-table td {
            font-size: 9px;
            padding: 1mm 0;
        }

        .amount {
            text-align: right;
            font-family: 'Consolas', monospace;
        }

        .total-section {
            margin: 2mm 0;
            text-align: right;
            line-height: 1.4;
        }

        .grand-total {
            font-size: 12px;
            font-weight: bold;
            margin-top: 1mm;
            border-top: 1px solid #000;
            padding-top: 1mm;
        }

        .footer {
            text-align: center;
            font-size: 9px;
            margin-top: 3mm;
            padding-top: 2mm;
            border-top: 1px dotted #000;
        }

        /* Enhanced styling */
        .receipt-wrapper {
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin: 20px auto;
            max-width: 58mm;
        }

        .item-row:nth-child(even) {
            background-color: #f9f9f9;
        }

        .payment-info {
            font-size: 9px;
            text-align: left;
            margin: 2mm 0;
            padding: 1mm;
            background: #f5f5f5;
            border-radius: 2px;
        }

        @media print {
            .receipt-wrapper {
                border: none;
                box-shadow: none;
                margin: 0;
            }

            .no-print {
                display: none !important;
            }

            body {
                width: 58mm !important;
            }

            .receipt {
                width: 54mm !important;
            }
        }
    </style>
    <style>
        /* Update the receipt-wrapper styles */
        .receipt-wrapper {
            /* Only show borders in screen view */
            border: none;
            margin: 0;
            padding: 0;
        }

        /* Preview borders only shown on screen */
        @media screen {
            .receipt-wrapper {
                border: 1px dashed #ccc;
                border-radius: 4px;
                box-shadow: 0 0 10px rgba(0,0,0,0.1);
                margin: 20px auto;
                max-width: 58mm;
                padding: 0;
            }
        }

        /* Enhanced print styles */
        @media print {
            @page {
                margin: 0;
                padding: 0;
                size: 58mm auto;
            }

            html, body {
                margin: 0;
                padding: 0;
                width: 58mm;
            }

            .receipt-wrapper {
                border: none !important;
                box-shadow: none !important;
                margin: 0 !important;
                padding: 0 !important;
                width: 58mm !important;
            }

            .receipt {
                width: 54mm !important;
                padding: 2mm !important;
            }

            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="receipt-wrapper">
        <div class="receipt">
            <div class="header">
                <p class="store-name"><?= htmlspecialchars($pharmacy['pharmacy_name']) ?></p>
                <p class="store-info">
                    <?= htmlspecialchars($pharmacy['pharmacy_address']) ?><br>
                    Tel: <?= htmlspecialchars($pharmacy['pharmacy_phone']) ?><br>
                    <?= htmlspecialchars($pharmacy['pharmacy_email']) ?>
                </p>
            </div>

            <div class="divider"></div>

            <p class="receipt-no">
                Receipt #: <?= htmlspecialchars($receipt_no) ?><br>
                Date: <?= date('d/m/Y H:i', strtotime($sales[0]['sale_date'])) ?><br>
                Cashier: <?= htmlspecialchars($_SESSION['username']) ?>
            </p>

            <div class="divider"></div>

            <table class="items-table">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Qty</th>
                        <th class="amount">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $item): ?>
                    <tr class="item-row">
                        <td><?= htmlspecialchars($item['drug_name']) ?></td>
                        <td><?= htmlspecialchars($item['quantity']) ?></td>
                        <td class="amount">₦<?= number_format($item['total'], 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="divider"></div>

            <div class="total-section">
                <?php if ($total_discount > 0): ?>
                <div class="subtotal">
                    Subtotal: ₦<?= number_format($total_amount + $total_discount, 2) ?><br>
                    Discount: ₦<?= number_format($total_discount, 2) ?>
                </div>
                <?php endif; ?>
                <div class="grand-total">
                    Total: ₦<?= number_format($total_amount, 2) ?>
                </div>
                <small><?= ucwords(num2words($total_amount)) ?> Naira Only</small>
            </div>

            <div class="payment-info">
                Payment Method: <?= htmlspecialchars($sales[0]['payment_method1']) ?>
                <?php if (!empty($sales[0]['payment_method2'])): ?>
                    , <?= htmlspecialchars($sales[0]['payment_method2']) ?>
                <?php endif; ?>
            </div>

            <div class="divider"></div>

            <div class="footer">
                <p>Thank you for your purchase!</p>
                <small>Powered by Ayaantec Limited</small>
            </div>
        </div>
    </div>

    <div class="no-print" style="text-align: center; margin: 20px;">
        <div style="margin-bottom: 10px; color: #666; font-size: 12px;">
            <strong>Printer Settings:</strong><br>
            Paper Size: 80mm x Auto<br>
            Scaling: None (100%)<br>
            Margins: None
        </div>
        <button onclick="window.print()" class="btn btn-primary">Print Receipt</button>
        <br><br>
        <a href="sell_drug.php" class="btn btn-link">Back to Sales</a>
    </div>

    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Set up print options
    const mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function(mql) {
        if (mql.matches) {
            document.body.style.width = '58mm';
            document.querySelector('.receipt-wrapper').style.width = '58mm';
            document.querySelector('.receipt').style.width = '54mm';
        }
    });

    // Auto print function with retry
    function autoPrint() {
        const printed = localStorage.getItem('receiptPrinted');
        if (!printed && window.location.search.includes('autoprint=true')) {
            // Small delay to ensure proper rendering
            setTimeout(() => {
                window.print();
                localStorage.setItem('receiptPrinted', 'true');
            }, 100);
        }
    }

    // Print button handler with confirmation
    document.querySelector('button').onclick = function() {
        if (confirm('Make sure your printer settings are correct:\n- Paper size: 58mm\n- Margins: None\n- Scale: 100%\n\nProceed with printing?')) {
            window.print();
        }
    };

    // Run auto print
    autoPrint();
});

// Before print handler
window.onbeforeprint = function() {
    document.body.style.width = '58mm';
    document.querySelector('.receipt-wrapper').style.width = '58mm';
    document.querySelector('.receipt').style.width = '54mm';
};
</script>
</body>
</html>

<?php
function num2words($num) {
    // Handle invalid input
    if (!is_numeric($num)) {
        return '';
    }

    // Limit to 2 decimal places and convert to integer (multiply by 100)
    $num = round($num, 2);
    $whole = floor($num);
    $fraction = round(($num - $whole) * 100);

    $ones = [
        0 => 'zero', 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five',
        6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten',
        11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen',
        15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen'
    ];

    $tens = [
        2 => 'twenty', 3 => 'thirty', 4 => 'forty', 5 => 'fifty',
        6 => 'sixty', 7 => 'seventy', 8 => 'eighty', 9 => 'ninety'
    ];

    if ($whole < 20) {
        $str = $ones[$whole];
    } elseif ($whole < 100) {
        $str = $tens[floor($whole / 10)];
        $digit = $whole % 10;
        if ($digit > 0) {
            $str .= '-' . $ones[$digit];
        }
    } elseif ($whole < 1000) {
        $str = $ones[floor($whole / 100)] . ' hundred';
        $remainder = $whole % 100;
        if ($remainder > 0) {
            $str .= ' and ' . num2words($remainder);
        }
    } elseif ($whole < 1000000) {
        $str = num2words(floor($whole / 1000)) . ' thousand';
        $remainder = $whole % 1000;
        if ($remainder > 0) {
            $str .= ' ' . num2words($remainder);
        }
    } else {
        return 'amount too large';
    }

    // Add decimal part if exists
    if ($fraction > 0) {
        $str .= ' point';
        if ($fraction < 20) {
            $str .= ' ' . $ones[$fraction];
        } else {
            $tens_digit = floor($fraction / 10);
            $ones_digit = $fraction % 10;
            $str .= ' ' . $tens[$tens_digit];
            if ($ones_digit > 0) {
                $str .= '-' . $ones[$ones_digit];
            }
        }
    }

    return $str;
}
?>
