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

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

$user = $_SESSION['user'];
$user_id = $user['id'] ?? 1;
$shop_id = $user['shop_id'] ?? null;

// Get purchase ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: list_purchases.php");
    exit;
}

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

// Get purchase details
$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.address as shop_address,
               sh.phone as shop_phone
        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) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>
                <i class='fas fa-exclamation-circle'></i> Purchase not found.
            </div>
            <a href='list_purchases.php' class='btn btn-primary'>
                <i class='fas fa-arrow-left'></i> Back to Purchases
            </a>
          </div>";
    require_once '../includes/footer.php';
    exit;
}

// Get purchase items
$items_sql = "SELECT pl.*, 
                     pb.batch_no,
                     pb.expiry_date,
                     pb.cost_price as batch_cost,
                     pb.sell_price as batch_sell,
                     pr.name as product_name,
                     pr.sku,
                     pr.unit
              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);

// Calculate totals
$total_items = count($items);
$total_qty = array_sum(array_column($items, 'qty'));
$total_cost = array_sum(array_map(function($item) {
    return $item['qty'] * $item['cost_price'];
}, $items));
?>

<style>
    .receipt-card {
        border: 1px solid #dee2e6;
        border-radius: 10px;
        max-width: 800px;
        margin: 0 auto;
    }
    
    .receipt-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px 10px 0 0;
        padding: 20px;
    }
    
    .receipt-body {
        padding: 30px;
    }
    
    .receipt-footer {
        background-color: #f8f9fa;
        border-top: 1px solid #dee2e6;
        padding: 20px;
        border-radius: 0 0 10px 10px;
    }
    
    .company-info h4 {
        color: #2c3e50;
        font-weight: bold;
    }
    
    .purchase-details {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
    }
    
    .table-items {
        border: 1px solid #dee2e6;
    }
    
    .table-items thead {
        background-color: #2c3e50;
        color: white;
    }
    
    .total-row {
        background-color: #e8f5e8 !important;
        font-weight: bold;
    }
    
    .badge-status {
        font-size: 14px;
        padding: 5px 15px;
    }
    
    @media print {
        .no-print {
            display: none !important;
        }
        
        .receipt-card {
            border: none;
            box-shadow: none;
        }
        
        body {
            font-size: 12px;
        }
        
        .receipt-body {
            padding: 15px;
        }
    }
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <div>
            <h3 class="text-primary">
                <i class="fas fa-file-invoice"></i> Purchase Details
            </h3>
            <p class="text-muted mb-0">View purchase information and items</p>
        </div>
        <div>
            <a href="list_purchases.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <button onclick="window.print()" class="btn btn-secondary ml-2">
                <i class="fas fa-print"></i> Print
            </button>
            <a href="print_purchase.php?id=<?= $purchase_id ?>" target="_blank" class="btn btn-primary ml-2">
                <i class="fas fa-receipt"></i> Print Receipt
            </a>
        </div>
    </div>

    <div class="card receipt-card">
        <div class="receipt-header">
            <div class="row">
                <div class="col-md-6">
                    <h4 class="mb-0">Purchase Receipt</h4>
                    <p class="mb-0">Goodhope Pharmacy System</p>
                </div>
                <div class="col-md-6 text-right">
                    <h5 class="mb-0">INVOICE</h5>
                    <p class="mb-0">#<?= htmlspecialchars($purchase['invoice_no']) ?></p>
                </div>
            </div>
        </div>
        
        <div class="receipt-body">
            <!-- Company Info -->
            <div class="row company-info mb-4">
                <div class="col-md-6">
                    <h6 class="text-muted">FROM:</h6>
                    <h4 class="mb-1"><?= htmlspecialchars($purchase['shop_name'] ?? 'Goodhope Pharmacy') ?></h4>
                    <p class="mb-1"><?= htmlspecialchars($purchase['shop_address'] ?? 'Kamachumu, Bukoba') ?></p>
                    <p class="mb-0">Phone: <?= htmlspecialchars($purchase['shop_phone'] ?? '+255 000 000 000') ?></p>
                </div>
                <div class="col-md-6 text-right">
                    <h6 class="text-muted">TO:</h6>
                    <?php if ($purchase['supplier_name']): ?>
                        <h4 class="mb-1"><?= htmlspecialchars($purchase['supplier_name']) ?></h4>
                        <p class="mb-1"><?= htmlspecialchars($purchase['supplier_contact'] ?? '') ?></p>
                        <p class="mb-1"><?= htmlspecialchars($purchase['supplier_email'] ?? '') ?></p>
                        <p class="mb-0"><?= htmlspecialchars($purchase['supplier_address'] ?? '') ?></p>
                    <?php else: ?>
                        <h4 class="mb-1">Direct Stock Addition</h4>
                        <p class="mb-0">Internal batch creation</p>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Purchase Details -->
            <div class="purchase-details">
                <div class="row">
                    <div class="col-md-3">
                        <strong>Invoice #:</strong><br>
                        <?= htmlspecialchars($purchase['invoice_no']) ?>
                    </div>
                    <div class="col-md-3">
                        <strong>Purchase Date:</strong><br>
                        <?= date('F d, Y', strtotime($purchase['purchase_date'])) ?>
                    </div>
                    <div class="col-md-3">
                        <strong>Created By:</strong><br>
                        <?= htmlspecialchars($purchase['created_by_name'] ?? 'System') ?>
                    </div>
                    <div class="col-md-3">
                        <strong>Shop:</strong><br>
                        <?= htmlspecialchars($purchase['shop_name'] ?? 'N/A') ?>
                    </div>
                </div>
            </div>
            
            <!-- Items Table -->
            <div class="table-responsive mb-4">
                <table class="table table-bordered table-items">
                    <thead>
                        <tr>
                            <th width="5%">#</th>
                            <th width="20%">Product</th>
                            <th width="15%">Batch No</th>
                            <th width="10%">Unit</th>
                            <th width="10%" class="text-center">Quantity</th>
                            <th width="15%" class="text-right">Cost Price</th>
                            <th width="15%" class="text-right">Line Total</th>
                            <th width="10%">Expiry</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($items)): ?>
                            <tr>
                                <td colspan="8" class="text-center text-muted py-3">
                                    No items found for this purchase
                                </td>
                            </tr>
                        <?php else: 
                            $counter = 1;
                            foreach ($items as $item):
                                $line_total = $item['qty'] * $item['cost_price'];
                        ?>
                        <tr>
                            <td><?= $counter++ ?></td>
                            <td>
                                <strong><?= htmlspecialchars($item['product_name']) ?></strong><br>
                                <small class="text-muted">SKU: <?= htmlspecialchars($item['sku']) ?></small>
                            </td>
                            <td><?= htmlspecialchars($item['batch_no']) ?></td>
                            <td><?= htmlspecialchars($item['unit']) ?></td>
                            <td class="text-center">
                                <span class="badge badge-primary"><?= $item['qty'] ?></span>
                            </td>
                            <td class="text-right">
                                TSh <?= number_format($item['cost_price'], 2) ?>
                            </td>
                            <td class="text-right">
                                <strong>TSh <?= number_format($line_total, 2) ?></strong>
                            </td>
                            <td>
                                <?php if ($item['expiry_date']): ?>
                                    <?= date('M Y', strtotime($item['expiry_date'])) ?>
                                <?php else: ?>
                                    <span class="text-muted">N/A</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr class="total-row">
                            <td colspan="4" class="text-right"><strong>TOTALS:</strong></td>
                            <td class="text-center"><strong><?= $total_qty ?></strong></td>
                            <td colspan="2" class="text-right">
                                <h5 class="mb-0">TSh <?= number_format($purchase['total'], 2) ?></h5>
                            </td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            
            <!-- Summary -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">Purchase Summary</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-6">
                                    <p class="mb-1">Total Items:</p>
                                    <p class="mb-1">Total Quantity:</p>
                                    <p class="mb-1">Created Date:</p>
                                    <p class="mb-0">Invoice Type:</p>
                                </div>
                                <div class="col-6 text-right">
                                    <p class="mb-1"><strong><?= $total_items ?></strong></p>
                                    <p class="mb-1"><strong><?= $total_qty ?></strong></p>
                                    <p class="mb-1"><strong><?= date('d-M-Y H:i', strtotime($purchase['created_at'])) ?></strong></p>
                                    <p class="mb-0">
                                        <?php if (strpos($purchase['invoice_no'], 'DIRECT') === 0): ?>
                                            <span class="badge badge-success badge-status">Direct Batch</span>
                                        <?php else: ?>
                                            <span class="badge badge-primary badge-status">Supplier Invoice</span>
                                        <?php endif; ?>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">Amount Summary</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-6">
                                    <p class="mb-1">Total Cost:</p>
                                    <p class="mb-1">VAT (0%):</p>
                                    <p class="mb-1">Discount:</p>
                                    <h5 class="mb-0">Grand Total:</h5>
                                </div>
                                <div class="col-6 text-right">
                                    <p class="mb-1">TSh <?= number_format($purchase['total'], 2) ?></p>
                                    <p class="mb-1">TSh 0.00</p>
                                    <p class="mb-1">TSh 0.00</p>
                                    <h5 class="mb-0 text-success">TSh <?= number_format($purchase['total'], 2) ?></h5>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="receipt-footer">
            <div class="row">
                <div class="col-md-8">
                    <p class="mb-0 small text-muted">
                        <i class="fas fa-info-circle"></i> 
                        This is an official purchase receipt. For any queries, contact the pharmacy administration.
                    </p>
                </div>
                <div class="col-md-4 text-right">
                    <p class="mb-0">
                        <strong>Authorized Signature:</strong><br>
                        __________________________
                    </p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Action Buttons -->
    <div class="text-center mt-4 no-print">
        <a href="edit_purchase.php?id=<?= $purchase_id ?>" class="btn btn-warning">
            <i class="fas fa-edit"></i> Edit Purchase
        </a>
        <a href="delete_purchase.php?id=<?= $purchase_id ?>" class="btn btn-danger ml-2" 
           onclick="return confirm('Are you sure you want to delete this purchase? This action cannot be undone.');">
            <i class="fas fa-trash"></i> Delete Purchase
        </a>
    </div>
</div>

<script>
// Print functionality
function printReceipt() {
    window.print();
}

// Auto-print option (uncomment if needed)
// window.onload = function() {
//     if (window.location.search.includes('print=1')) {
//         window.print();
//     }
// };
</script>

<?php require_once '../includes/footer.php'; ?>