<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get inventory ID
$inventory_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$inventory_id) {
    header('Location: pharmacy_inventory.php');
    exit();
}

// Get inventory item details
$item_sql = "SELECT * FROM pharmacy_inventory WHERE inventory_id = ?";
$stmt = $conn->prepare($item_sql);
$stmt->bind_param('i', $inventory_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: pharmacy_inventory.php');
    exit();
}

$item = $result->fetch_assoc();

// Get stock movement history
$movements_sql = "SELECT 
                    psm.*, u.full_name as performed_by_name
                  FROM pharmacy_stock_movements psm
                  INNER JOIN users u ON psm.performed_by = u.user_id
                  WHERE psm.inventory_id = ?
                  ORDER BY psm.movement_date DESC
                  LIMIT 20";
$stmt = $conn->prepare($movements_sql);
$stmt->bind_param('i', $inventory_id);
$stmt->execute();
$movements = $stmt->get_result();

// Get dispensing history
$dispensing_sql = "SELECT 
                    pd.dispensing_number, pd.dispensing_date, pd.patient_name,
                    pdi.quantity, pdi.unit_price, pdi.total_price
                   FROM pharmacy_dispensing_items pdi
                   INNER JOIN pharmacy_dispensing pd ON pdi.dispensing_id = pd.dispensing_id
                   WHERE pdi.inventory_id = ?
                   ORDER BY pd.dispensing_date DESC
                   LIMIT 10";
$stmt = $conn->prepare($dispensing_sql);
$stmt->bind_param('i', $inventory_id);
$stmt->execute();
$dispensing_history = $stmt->get_result();

// Calculate stock value
$stock_value_cost = $item['current_stock'] * $item['unit_cost'];
$stock_value_selling = $item['current_stock'] * $item['selling_price'];
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Inventory Item Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        .info-row {
            display: flex;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .info-row:last-child {
            border-bottom: none;
        }
        .info-label {
            font-weight: 600;
            color: #64748b;
            width: 40%;
        }
        .info-value {
            color: #1e293b;
            width: 60%;
        }
        .stock-badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 1.25rem;
            font-weight: 700;
        }
        .stock-normal { background: #d1fae5; color: #059669; }
        .stock-low { background: #fef3c7; color: #d97706; }
        .stock-out { background: #fee2e2; color: #dc2626; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Inventory Item Details</h4>
                                <div class="page-title-right">
                                    <div class="d-flex gap-2">
                                        <a href="pharmacy_inventory_edit.php?id=<?php echo $inventory_id; ?>" 
                                           class="btn btn-primary">
                                            <i class="ri-edit-line me-1"></i>Edit Item
                                        </a>
                                        <a href="pharmacy_inventory.php" class="btn btn-light">
                                            <i class="ri-arrow-left-line me-1"></i>Back to Inventory
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Item Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card bg-primary text-white">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <h3 class="text-white mb-2"><?php echo htmlspecialchars($item['item_name']); ?></h3>
                                            <p class="mb-1"><strong>Code:</strong> <?php echo htmlspecialchars($item['item_code']); ?></p>
                                            <?php if ($item['generic_name']): ?>
                                                <p class="mb-1"><strong>Generic:</strong> <?php echo htmlspecialchars($item['generic_name']); ?></p>
                                            <?php endif; ?>
                                            <?php if ($item['brand_name']): ?>
                                                <p class="mb-0"><strong>Brand:</strong> <?php echo htmlspecialchars($item['brand_name']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <?php
                                            $stock_status = 'normal';
                                            if ($item['current_stock'] == 0) {
                                                $stock_status = 'out';
                                            } elseif ($item['current_stock'] <= $item['reorder_level']) {
                                                $stock_status = 'low';
                                            }
                                            ?>
                                            <div class="stock-badge stock-<?php echo $stock_status; ?>">
                                                <?php echo $item['current_stock']; ?> <?php echo $item['unit_of_measure']; ?>
                                            </div>
                                            <p class="mt-2 mb-0">Current Stock</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-lg-6">
                            <!-- Basic Information -->
                            <div class="info-card">
                                <h5 class="mb-3"><i class="ri-information-line me-2"></i>Basic Information</h5>
                                <div class="info-row">
                                    <div class="info-label">Category</div>
                                    <div class="info-value"><?php echo ucwords(str_replace('_', ' ', strtolower($item['category']))); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Dosage Form</div>
                                    <div class="info-value"><?php echo ucwords(strtolower($item['dosage_form'])); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Strength</div>
                                    <div class="info-value"><?php echo htmlspecialchars($item['strength'] ?: '-'); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Manufacturer</div>
                                    <div class="info-value"><?php echo htmlspecialchars($item['manufacturer'] ?: '-'); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Supplier</div>
                                    <div class="info-value"><?php echo htmlspecialchars($item['supplier'] ?: '-'); ?></div>
                                </div>
                            </div>

                            <!-- Stock Information -->
                            <div class="info-card">
                                <h5 class="mb-3"><i class="ri-stock-line me-2"></i>Stock Information</h5>
                                <div class="info-row">
                                    <div class="info-label">Current Stock</div>
                                    <div class="info-value"><strong><?php echo $item['current_stock']; ?> <?php echo $item['unit_of_measure']; ?></strong></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Reorder Level</div>
                                    <div class="info-value"><?php echo $item['reorder_level']; ?> <?php echo $item['unit_of_measure']; ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Minimum Stock</div>
                                    <div class="info-value"><?php echo $item['minimum_stock']; ?> <?php echo $item['unit_of_measure']; ?></div>
                                </div>
                                <?php if ($item['maximum_stock']): ?>
                                    <div class="info-row">
                                        <div class="info-label">Maximum Stock</div>
                                        <div class="info-value"><?php echo $item['maximum_stock']; ?> <?php echo $item['unit_of_measure']; ?></div>
                                    </div>
                                <?php endif; ?>
                                <div class="info-row">
                                    <div class="info-label">Batch Number</div>
                                    <div class="info-value"><?php echo htmlspecialchars($item['batch_number'] ?: '-'); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Expiry Date</div>
                                    <div class="info-value">
                                        <?php if ($item['expiry_date']): ?>
                                            <?php
                                            $days_to_expiry = (strtotime($item['expiry_date']) - time()) / (60 * 60 * 24);
                                            $expiry_class = '';
                                            if ($days_to_expiry < 0) {
                                                $expiry_class = 'text-danger';
                                            } elseif ($days_to_expiry < 30) {
                                                $expiry_class = 'text-warning';
                                            }
                                            ?>
                                            <span class="<?php echo $expiry_class; ?>">
                                                <?php echo date('d M Y', strtotime($item['expiry_date'])); ?>
                                                <?php if ($days_to_expiry < 30 && $days_to_expiry >= 0): ?>
                                                    (<?php echo round($days_to_expiry); ?> days remaining)
                                                <?php elseif ($days_to_expiry < 0): ?>
                                                    (EXPIRED)
                                                <?php endif; ?>
                                            </span>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Storage -->
                            <div class="info-card">
                                <h5 class="mb-3"><i class="ri-archive-line me-2"></i>Storage</h5>
                                <div class="info-row">
                                    <div class="info-label">Storage Location</div>
                                    <div class="info-value"><?php echo htmlspecialchars($item['storage_location'] ?: '-'); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Storage Temperature</div>
                                    <div class="info-value"><?php echo htmlspecialchars($item['storage_temperature'] ?: '-'); ?></div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="col-lg-6">
                            <!-- Pricing -->
                            <div class="info-card">
                                <h5 class="mb-3"><i class="ri-money-dollar-circle-line me-2"></i>Pricing</h5>
                                <div class="info-row">
                                    <div class="info-label">Unit Cost</div>
                                    <div class="info-value">KES <?php echo number_format($item['unit_cost'], 2); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Selling Price</div>
                                    <div class="info-value">KES <?php echo number_format($item['selling_price'], 2); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Markup</div>
                                    <div class="info-value"><?php echo number_format($item['markup_percentage'], 2); ?>%</div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Stock Value (Cost)</div>
                                    <div class="info-value"><strong>KES <?php echo number_format($stock_value_cost, 2); ?></strong></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Stock Value (Selling)</div>
                                    <div class="info-value"><strong>KES <?php echo number_format($stock_value_selling, 2); ?></strong></div>
                                </div>
                            </div>

                            <!-- Regulations -->
                            <div class="info-card">
                                <h5 class="mb-3"><i class="ri-shield-check-line me-2"></i>Regulations</h5>
                                <div class="info-row">
                                    <div class="info-label">Requires Prescription</div>
                                    <div class="info-value">
                                        <?php if ($item['requires_prescription']): ?>
                                            <span class="badge badge-soft-warning">Yes</span>
                                        <?php else: ?>
                                            <span class="badge badge-soft-success">No</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Controlled Substance</div>
                                    <div class="info-value">
                                        <?php if ($item['is_controlled_substance']): ?>
                                            <span class="badge badge-soft-danger">Yes</span>
                                        <?php else: ?>
                                            <span class="badge badge-soft-info">No</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Notes -->
                            <?php if ($item['notes']): ?>
                                <div class="info-card">
                                    <h5 class="mb-3"><i class="ri-file-text-line me-2"></i>Notes</h5>
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($item['notes'])); ?></p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Stock Movement History -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="ri-history-line me-2"></i>Recent Stock Movements</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Movement Type</th>
                                                    <th>Quantity</th>
                                                    <th>Balance Before</th>
                                                    <th>Balance After</th>
                                                    <th>Reason</th>
                                                    <th>Performed By</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($movements->num_rows > 0): ?>
                                                    <?php while ($movement = $movements->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('d M Y, h:i A', strtotime($movement['movement_date'])); ?></td>
                                                            <td>
                                                                <?php
                                                                $badge_class = 'badge-primary';
                                                                if ($movement['movement_type'] == 'STOCK_IN') $badge_class = 'badge-success';
                                                                elseif ($movement['movement_type'] == 'STOCK_OUT') $badge_class = 'badge-warning';
                                                                elseif ($movement['movement_type'] == 'EXPIRED' || $movement['movement_type'] == 'DAMAGE') $badge_class = 'badge-danger';
                                                                ?>
                                                                <span class="badge <?php echo $badge_class; ?>">
                                                                    <?php echo str_replace('_', ' ', $movement['movement_type']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo $movement['quantity']; ?></td>
                                                            <td><?php echo $movement['balance_before']; ?></td>
                                                            <td><?php echo $movement['balance_after']; ?></td>
                                                            <td><?php echo htmlspecialchars($movement['reason'] ?: '-'); ?></td>
                                                            <td><?php echo htmlspecialchars($movement['performed_by_name']); ?></td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-4">
                                                            <p class="text-muted mb-0">No stock movements recorded</p>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Dispensing History -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="ri-capsule-line me-2"></i>Recent Dispensing History</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Dispensing #</th>
                                                    <th>Patient</th>
                                                    <th>Quantity</th>
                                                    <th>Unit Price</th>
                                                    <th>Total</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($dispensing_history->num_rows > 0): ?>
                                                <?php while ($disp = $dispensing_history->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('d M Y, h:i A', strtotime($disp['dispensing_date'])); ?></td>
                                                            <td><?php echo htmlspecialchars($disp['dispensing_number']); ?></td>
                                                            <td><?php echo htmlspecialchars($disp['patient_name']); ?></td>
                                                            <td><?php echo $disp['quantity']; ?></td>
                                                            <td>KES <?php echo number_format($disp['unit_price'], 2); ?></td>
                                                            <td>KES <?php echo number_format($disp['total_price'], 2); ?></td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center py-4">
                                                            <p class="text-muted mb-0">No dispensing records found</p>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>