<?php
session_start();
require_once '../assets/db_connect.php';

// Ensure user logged in
if (!isset($_SESSION['user'])) {
    header("Location: ../auth/login.php");
    exit;
}

// Get purchase ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid purchase ID");
}

$purchase_id = intval($_GET['id']);

// Get purchase details
$sql = "SELECT p.*, 
               s.name as supplier_name, 
               u.fullname as created_by_name,
               sh.name as shop_name
        FROM purchases p 
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        LEFT JOIN users u ON p.created_by = u.id
        LEFT JOIN shops sh ON p.shop_id = sh.id
        WHERE p.id = ?";
        
$stmt = $pdo->prepare($sql);
$stmt->execute([$purchase_id]);
$purchase = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$purchase) {
    die("Purchase not found");
}

// Get purchase items
$items_sql = "SELECT pl.*, 
                     pb.batch_no,
                     pr.name as product_name,
                     pr.sku
              FROM purchase_lines pl
              JOIN product_batches pb ON pl.batch_id = pb.id
              JOIN products pr ON pb.product_id = pr.id
              WHERE pl.purchase_id = ?
              ORDER BY pl.id";
              
$items_stmt = $pdo->prepare($items_sql);
$items_stmt->execute([$purchase_id]);
$items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Purchase Receipt</title>
    <style>
        /* Thermal printer style */
        @media print {
            @page {
                margin: 0;
                size: 80mm auto;
            }
            
            body {
                font-family: 'Courier New', monospace;
                font-size: 12px;
                line-height: 1.2;
                margin: 0;
                padding: 5mm;
                width: 80mm;
                color: black;
                background: white;
            }
            
            .no-print, .btn {
                display: none !important;
            }
            
            .receipt {
                width: 100%;
                border: none;
            }
            
            table {
                width: 100%;
                border-collapse: collapse;
            }
            
            th, td {
                padding: 2px 0;
                border-bottom: 1px dashed #ccc;
            }
            
            .total-row {
                border-top: 2px solid #000;
                font-weight: bold;
            }
        }
        
        /* Screen style */
        @media screen {
            body {
                font-family: Arial, sans-serif;
                font-size: 14px;
                padding: 20px;
                background: #f5f5f5;
            }
            
            .receipt {
                max-width: 80mm;
                margin: 0 auto;
                background: white;
                padding: 20px;
                border: 1px solid #ddd;
                box-shadow: 0 0 10px rgba(0,0,0,0.1);
            }
            
            .btn-group {
                text-align: center;
                margin-bottom: 20px;
            }
            
            .btn {
                padding: 10px 20px;
                margin: 5px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
            }
            
            .btn-print {
                background: #007bff;
                color: white;
            }
            
            .btn-close {
                background: #6c757d;
                color: white;
            }
        }
        
        /* Common styles */
        .text-center { text-align: center; }
        .text-right { text-align: right; }
        .text-bold { font-weight: bold; }
        .dashed-line { border-bottom: 1px dashed #000; padding-bottom: 5px; margin-bottom: 5px; }
        .double-line { border-top: 3px double #000; margin: 10px 0; }
        .company-name { font-size: 16px; font-weight: bold; }
        .receipt-title { font-size: 14px; margin: 5px 0; }
        .small-text { font-size: 10px; }
        .thank-you { margin-top: 20px; font-style: italic; }
    </style>
</head>
<body>
    <div class="btn-group no-print">
        <button class="btn btn-print" onclick="window.print()">
            <i class="fas fa-print"></i> Print Receipt
        </button>
        <button class="btn btn-close" onclick="window.close()">
            <i class="fas fa-times"></i> Close
        </button>
    </div>
    
    <div class="receipt">
        <!-- Header -->
        <div class="text-center">
            <div class="company-name">GOODHOPE PHARMACY</div>
            <div class="small-text">Kamachumu, Bukoba</div>
            <div class="small-text">Tel: +255 000 000 000</div>
            <div class="dashed-line"></div>
            <div class="receipt-title">PURCHASE RECEIPT</div>
            <div class="small-text"><?= date('Y-m-d H:i:s') ?></div>
        </div>
        
        <!-- Purchase Info -->
        <div style="margin: 10px 0;">
            <div><strong>Invoice:</strong> <?= htmlspecialchars($purchase['invoice_no']) ?></div>
            <div><strong>Date:</strong> <?= date('d-M-Y', strtotime($purchase['purchase_date'])) ?></div>
            <?php if ($purchase['supplier_name']): ?>
                <div><strong>Supplier:</strong> <?= htmlspecialchars($purchase['supplier_name']) ?></div>
            <?php else: ?>
                <div><strong>Type:</strong> Direct Batch Addition</div>
            <?php endif; ?>
            <div><strong>Shop:</strong> <?= htmlspecialchars($purchase['shop_name'] ?? 'Main Shop') ?></div>
        </div>
        
        <div class="dashed-line"></div>
        
        <!-- Items Table -->
        <table>
            <thead>
                <tr>
                    <th>Qty</th>
                    <th>Item</th>
                    <th class="text-right">Price</th>
                    <th class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $total_qty = 0;
                $total_amount = 0;
                
                foreach ($items as $item): 
                    $line_total = $item['qty'] * $item['cost_price'];
                    $total_qty += $item['qty'];
                    $total_amount += $line_total;
                ?>
                <tr>
                    <td><?= $item['qty'] ?></td>
                    <td>
                        <?= htmlspecialchars(substr($item['product_name'], 0, 20)) ?>
                        <?php if (strlen($item['product_name']) > 20): ?>...<?php endif; ?>
                        <br>
                        <span class="small-text"><?= htmlspecialchars($item['batch_no']) ?></span>
                    </td>
                    <td class="text-right"><?= number_format($item['cost_price'], 2) ?></td>
                    <td class="text-right"><?= number_format($line_total, 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <div class="double-line"></div>
        
        <!-- Totals -->
        <table>
            <tr>
                <td>Total Items:</td>
                <td class="text-right"><?= count($items) ?></td>
            </tr>
            <tr>
                <td>Total Quantity:</td>
                <td class="text-right"><?= $total_qty ?></td>
            </tr>
            <tr class="total-row">
                <td><strong>TOTAL AMOUNT:</strong></td>
                <td class="text-right"><strong>TSh <?= number_format($purchase['total'], 2) ?></strong></td>
            </tr>
        </table>
        
        <div class="double-line"></div>
        
        <!-- Footer -->
        <div class="text-center small-text">
            <div>Created by: <?= htmlspecialchars($purchase['created_by_name'] ?? 'System') ?></div>
            <div>Receipt #: <?= $purchase_id ?></div>
            <div class="thank-you">Thank you for your business!</div>
            <div style="margin-top: 10px;">*** END OF RECEIPT ***</div>
        </div>
    </div>
    
    <script>
        // Auto-print on page load
        window.onload = function() {
            // Small delay to ensure everything is loaded
            setTimeout(function() {
                window.print();
            }, 500);
        };
        
        // Close window after print (optional)
        window.onafterprint = function() {
            // Uncomment to auto-close after printing
            // setTimeout(function() {
            //     window.close();
            // }, 1000);
        };
    </script>
    
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</body>
</html>