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

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

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

$purchase_id = intval($_GET['id']);
$user = $_SESSION['user'];
$user_role = $user['role'] ?? 'cashier';
$user_shop_id = $user['shop_id'] ?? 0;

// Get purchase details
try {
    $sql = "SELECT p.*, s.name as supplier_name, s.contact as supplier_contact, 
                   s.email as supplier_email, s.address as supplier_address,
                   u.fullname as created_by_name, sh.name as shop_name,
                   sh.phone as shop_phone, sh.address as shop_address
            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 = ?";
    
    $params = [$purchase_id];
    
    // Add shop restriction for non-admin users
    if ($user_role !== 'admin' && $user_shop_id > 0) {
        $sql .= " AND p.shop_id = ?";
        $params[] = $user_shop_id;
    }
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $purchase = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$purchase) {
        die("Purchase not found or access denied");
    }
    
    // Get purchase items
    $sql = "SELECT pl.*, pb.batch_no, pb.expiry_date, pb.sell_price,
                   p.name as product_name, p.sku as product_sku, p.unit,
                   p.category, p.generic_name
            FROM purchase_lines pl
            LEFT JOIN product_batches pb ON pl.batch_id = pb.id
            LEFT JOIN products p ON pb.product_id = p.id
            WHERE pl.purchase_id = ?
            ORDER BY pl.id";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$purchase_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate totals
    $total_qty = 0;
    $total_items = count($items);
    
    foreach ($items as &$item) {
        $item['line_total'] = $item['qty'] * $item['cost_price'];
        $total_qty += $item['qty'];
    }
    
} catch (Exception $e) {
    die("Error loading purchase: " . $e->getMessage());
}

// Set headers for printing
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase Receipt - <?php echo htmlspecialchars($purchase['invoice_no'] ?? 'N/A'); ?></title>
    <style>
        /* Print-friendly styles */
        @media print {
            body {
                margin: 0;
                padding: 0;
                font-family: 'Helvetica Neue', Arial, sans-serif;
                font-size: 12px;
                color: #000;
                background: #fff;
            }
            
            .no-print {
                display: none !important;
            }
            
            .page-break {
                page-break-before: always;
            }
            
            /* Ensure tables don't break across pages */
            table {
                page-break-inside: avoid;
                break-inside: avoid;
            }
            
            tr {
                page-break-inside: avoid;
                break-inside: avoid;
            }
        }
        
        @media screen {
            body {
                font-family: 'Helvetica Neue', Arial, sans-serif;
                font-size: 14px;
                color: #333;
                background: #f5f5f5;
                padding: 20px;
                max-width: 800px;
                margin: 0 auto;
            }
            
            .receipt-container {
                background: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 0 20px rgba(0,0,0,0.1);
                margin-bottom: 20px;
            }
            
            .print-controls {
                text-align: center;
                margin-bottom: 20px;
                padding: 15px;
                background: white;
                border-radius: 8px;
                box-shadow: 0 0 10px rgba(0,0,0,0.1);
            }
        }
        
        /* Common styles for both print and screen */
        * {
            box-sizing: border-box;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        .receipt-header {
            text-align: center;
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 2px solid #333;
        }
        
        .shop-name {
            font-size: 28px;
            font-weight: bold;
            margin: 0 0 5px 0;
            color: #2c3e50;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .shop-address {
            font-size: 14px;
            color: #666;
            margin: 0 0 10px 0;
            line-height: 1.4;
        }
        
        .receipt-title {
            font-size: 22px;
            font-weight: bold;
            color: #2c3e50;
            margin: 15px 0;
            text-align: center;
            text-transform: uppercase;
        }
        
        .receipt-info {
            margin: 20px 0;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .info-box {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            border-left: 4px solid #3498db;
        }
        
        .info-box h4 {
            margin: 0 0 10px 0;
            font-size: 14px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .info-box p {
            margin: 0;
            font-size: 15px;
            font-weight: 500;
            color: #2c3e50;
        }
        
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .items-table th {
            background: #2c3e50;
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 0.5px;
            padding: 12px 8px;
            text-align: left;
        }
        
        .items-table td {
            padding: 10px 8px;
            border-bottom: 1px solid #eee;
            font-size: 13px;
        }
        
        .items-table tr:hover {
            background: #f8f9fa;
        }
        
        .items-table tr:nth-child(even) {
            background: #f8f9fa;
        }
        
        .text-right {
            text-align: right;
        }
        
        .text-center {
            text-align: center;
        }
        
        .text-bold {
            font-weight: bold;
        }
        
        .total-row {
            background: #2c3e50 !important;
            color: white;
        }
        
        .total-row td {
            padding: 15px 8px;
            font-size: 14px;
            font-weight: bold;
        }
        
        .footer {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            text-align: center;
            color: #666;
            font-size: 12px;
        }
        
        .footer p {
            margin: 5px 0;
        }
        
        .signature-area {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px dashed #999;
        }
        
        .signature-line {
            display: inline-block;
            width: 200px;
            border-top: 1px solid #333;
            margin: 0 20px;
        }
        
        .signature-label {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        
        .logo {
            max-width: 120px;
            margin-bottom: 10px;
        }
        
        .invoice-no {
            font-size: 16px;
            color: #e74c3c;
            font-weight: bold;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 8px;
            background: #3498db;
            color: white;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .date-time {
            color: #666;
            font-size: 13px;
        }
        
        .qty-badge {
            display: inline-block;
            padding: 2px 8px;
            background: #f1f8ff;
            border: 1px solid #c8e1ff;
            border-radius: 10px;
            font-weight: 600;
            font-size: 12px;
        }
        
        .batch-info {
            font-size: 11px;
            color: #666;
            margin-top: 2px;
        }
        
        .total-amount {
            font-size: 20px;
            color: #27ae60;
            font-weight: bold;
        }
        
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            margin: 5px;
            transition: background 0.3s;
        }
        
        .btn:hover {
            background: #2980b9;
        }
        
        .btn-print {
            background: #27ae60;
        }
        
        .btn-print:hover {
            background: #219653;
        }
        
        .btn-back {
            background: #95a5a6;
        }
        
        .btn-back:hover {
            background: #7f8c8d;
        }
    </style>
    <script>
        function printReceipt() {
            window.print();
        }
        
        function closeWindow() {
            window.close();
        }
    </script>
</head>
<body>
    <!-- Print Controls (Hidden when printing) -->
    <div class="print-controls no-print">
        <h3>Purchase Receipt</h3>
        <p>Purchase #<?php echo htmlspecialchars($purchase['invoice_no'] ?? $purchase_id); ?> - Ready for printing</p>
        <button class="btn btn-print" onclick="printReceipt()">
            <i class="fas fa-print"></i> Print Receipt
        </button>
        <button class="btn btn-back" onclick="closeWindow()">
            <i class="fas fa-times"></i> Close
        </button>
        <button class="btn" onclick="window.location.href='dashboard.php'">
            <i class="fas fa-home"></i> Back to Dashboard
        </button>
    </div>
    
    <!-- Receipt Content -->
    <div class="receipt-container">
        <!-- Header -->
        <div class="receipt-header">
            <!-- Logo can be added here if available -->
            <div style="text-align: center; margin-bottom: 10px;">
                <!-- <img src="../assets/logo.png" alt="Logo" class="logo"> -->
            </div>
            <h1 class="shop-name"><?php echo htmlspecialchars($purchase['shop_name'] ?? 'Pharmacy'); ?></h1>
            <p class="shop-address">
                <?php 
                echo htmlspecialchars($purchase['shop_address'] ?? '');
                if ($purchase['shop_phone'] ?? '') {
                    echo '<br>Tel: ' . htmlspecialchars($purchase['shop_phone']);
                }
                ?>
            </p>
            <div class="receipt-title">PURCHASE RECEIPT</div>
            <div class="invoice-no">Invoice: <?php echo htmlspecialchars($purchase['invoice_no'] ?? 'N/A'); ?></div>
            <div class="date-time">Printed: <?php echo date('d-M-Y H:i:s'); ?></div>
        </div>
        
        <!-- Purchase Information -->
        <div class="receipt-info">
            <div class="info-grid">
                <div class="info-box">
                    <h4>Supplier Information</h4>
                    <p class="text-bold"><?php echo htmlspecialchars($purchase['supplier_name'] ?? 'Direct Batch'); ?></p>
                    <?php if ($purchase['supplier_contact'] ?? ''): ?>
                    <p>Contact: <?php echo htmlspecialchars($purchase['supplier_contact']); ?></p>
                    <?php endif; ?>
                    <?php if ($purchase['supplier_email'] ?? ''): ?>
                    <p>Email: <?php echo htmlspecialchars($purchase['supplier_email']); ?></p>
                    <?php endif; ?>
                    <?php if ($purchase['supplier_address'] ?? ''): ?>
                    <p>Address: <?php echo htmlspecialchars($purchase['supplier_address']); ?></p>
                    <?php endif; ?>
                </div>
                
                <div class="info-box">
                    <h4>Purchase Details</h4>
                    <p>Date: <?php echo date('d-M-Y', strtotime($purchase['purchase_date'])); ?></p>
                    <p>Invoice #: <?php echo htmlspecialchars($purchase['invoice_no'] ?? 'N/A'); ?></p>
                    <p>Created By: <?php echo htmlspecialchars($purchase['created_by_name'] ?? 'Unknown'); ?></p>
                    <p>Shop: <?php echo htmlspecialchars($purchase['shop_name'] ?? 'Unknown'); ?></p>
                </div>
            </div>
        </div>
        
        <!-- Purchase Items -->
        <h3>Purchase Items (<?php echo $total_items; ?> items)</h3>
        <table class="items-table">
            <thead>
                <tr>
                    <th width="5%">#</th>
                    <th>Product</th>
                    <th width="15%">Batch No</th>
                    <th width="10%" class="text-center">Qty</th>
                    <th width="12%" class="text-right">Unit Cost</th>
                    <th width="15%" class="text-right">Line Total</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($items)): ?>
                <tr>
                    <td colspan="6" class="text-center">No items found for this purchase</td>
                </tr>
                <?php else: 
                $counter = 0;
                foreach ($items as $item): 
                    $counter++;
                ?>
                <tr>
                    <td><?php echo $counter; ?></td>
                    <td>
                        <div class="text-bold"><?php echo htmlspecialchars($item['product_name'] ?? 'Unknown Product'); ?></div>
                        <?php if ($item['product_sku'] ?? ''): ?>
                        <div class="batch-info">SKU: <?php echo htmlspecialchars($item['product_sku']); ?></div>
                        <?php endif; ?>
                        <?php if ($item['generic_name'] ?? ''): ?>
                        <div class="batch-info">Generic: <?php echo htmlspecialchars($item['generic_name']); ?></div>
                        <?php endif; ?>
                        <?php if ($item['category'] ?? ''): ?>
                        <div class="batch-info">Category: <?php echo htmlspecialchars($item['category']); ?></div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php echo htmlspecialchars($item['batch_no'] ?? 'N/A'); ?>
                        <?php if ($item['expiry_date'] ?? ''): ?>
                        <div class="batch-info">
                            Exp: <?php echo date('M-Y', strtotime($item['expiry_date'])); ?>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td class="text-center">
                        <span class="qty-badge"><?php echo $item['qty']; ?></span>
                        <?php if ($item['unit'] ?? ''): ?>
                        <div class="batch-info"><?php echo htmlspecialchars($item['unit']); ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="text-right">
                        TSh <?php echo number_format($item['cost_price'], 2); ?>
                    </td>
                    <td class="text-right text-bold">
                        TSh <?php echo number_format($item['line_total'], 2); ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
            <tfoot>
                <tr class="total-row">
                    <td colspan="3">
                        <strong>GRAND TOTAL</strong><br>
                        <span style="font-size: 11px;"><?php echo $total_items; ?> items, <?php echo $total_qty; ?> units</span>
                    </td>
                    <td class="text-center">
                        <strong><?php echo $total_qty; ?></strong>
                    </td>
                    <td></td>
                    <td class="text-right total-amount">
                        TSh <?php echo number_format($purchase['total'], 2); ?>
                    </td>
                </tr>
            </tfoot>
        </table>
        
        <!-- Additional Information -->
        <?php if ($purchase['notes'] ?? ''): ?>
        <div class="info-box" style="margin-top: 20px;">
            <h4>Notes</h4>
            <p><?php echo nl2br(htmlspecialchars($purchase['notes'])); ?></p>
        </div>
        <?php endif; ?>
        
        <!-- Summary -->
        <div class="info-grid" style="margin-top: 30px;">
            <div class="info-box">
                <h4>Summary</h4>
                <p>Total Items: <strong><?php echo $total_items; ?></strong></p>
                <p>Total Quantity: <strong><?php echo $total_qty; ?></strong></p>
                <p>Average Unit Cost: <strong>TSh <?php echo $total_qty > 0 ? number_format($purchase['total'] / $total_qty, 2) : '0.00'; ?></strong></p>
            </div>
            
            <div class="info-box">
                <h4>Financial Summary</h4>
                <p>Subtotal: TSh <?php echo number_format($purchase['total'], 2); ?></p>
                <p>VAT (0%): TSh 0.00</p>
                <p style="font-size: 16px; color: #27ae60;">Total Amount: <strong>TSh <?php echo number_format($purchase['total'], 2); ?></strong></p>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <p><strong>Thank you for your business!</strong></p>
            <p>This is a computer generated receipt. No signature required.</p>
            <p>For inquiries, contact: <?php echo htmlspecialchars($purchase['shop_phone'] ?? 'N/A'); ?></p>
            <p>Receipt ID: PUR-<?php echo str_pad($purchase_id, 6, '0', STR_PAD_LEFT); ?></p>
            <p>Printed on: <?php echo date('d-M-Y H:i:s'); ?> by <?php echo htmlspecialchars($user['fullname'] ?? 'System'); ?></p>
        </div>
        
        <!-- Signatures Area (for manual signing if needed) -->
        <div class="signature-area no-print">
            <div style="text-align: center;">
                <div style="display: inline-block; margin: 0 40px;">
                    <div class="signature-line"></div>
                    <div class="signature-label">Supplier's Signature</div>
                </div>
                <div style="display: inline-block; margin: 0 40px;">
                    <div class="signature-line"></div>
                    <div class="signature-label">Receiver's Signature</div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Font Awesome for icons (screen only) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <script>
        // Auto-print if specified in URL
        if (window.location.search.includes('autoprint=true')) {
            window.print();
        }
        
        // Close window after print (optional)
        window.onafterprint = function() {
            // Uncomment the next line to automatically close window after printing
            // window.close();
        };
    </script>
</body>
</html>