<?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();
}

// Handle filters
$filter_category = isset($_GET['category']) ? $_GET['category'] : '';
$filter_stock = isset($_GET['stock_status']) ? $_GET['stock_status'] : '';
$search_term = isset($_GET['search']) ? $_GET['search'] : '';

// Build query
$where_clauses = ["is_active = 1"];

if ($filter_category) {
    $where_clauses[] = "category = '" . $conn->real_escape_string($filter_category) . "'";
}

if ($filter_stock == 'low') {
    $where_clauses[] = "current_stock <= reorder_level";
} elseif ($filter_stock == 'out') {
    $where_clauses[] = "current_stock = 0";
} elseif ($filter_stock == 'normal') {
    $where_clauses[] = "current_stock > reorder_level";
}

if ($search_term) {
    $search_term = $conn->real_escape_string($search_term);
    $where_clauses[] = "(item_name LIKE '%$search_term%' OR generic_name LIKE '%$search_term%' OR brand_name LIKE '%$search_term%' OR item_code LIKE '%$search_term%')";
}

$where_sql = implode(' AND ', $where_clauses);

// Get inventory items
$inventory_sql = "SELECT * FROM pharmacy_inventory 
                  WHERE $where_sql
                  ORDER BY item_name ASC";
$inventory_items = $conn->query($inventory_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_items,
                SUM(current_stock) as total_units,
                SUM(current_stock * unit_cost) as total_value,
                SUM(CASE WHEN current_stock <= reorder_level THEN 1 ELSE 0 END) as low_stock_count
              FROM pharmacy_inventory 
              WHERE is_active = 1";
$stats = $conn->query($stats_sql)->fetch_assoc();

// Get categories for filter
$categories_sql = "SELECT DISTINCT category FROM pharmacy_inventory WHERE is_active = 1 ORDER BY category";
$categories = $conn->query($categories_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pharmacy Inventory')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .stock-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .stock-normal { background: #d1fae5; color: #059669; }
        .stock-low { background: #fef3c7; color: #d97706; }
        .stock-out { background: #fee2e2; color: #dc2626; }
        
        .filter-card {
            background: white;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
    </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">Pharmacy Inventory</h4>
                                <div class="page-title-right">
                                    <div class="d-flex gap-2">
                                        <a href="pharmacy_inventory_add.php" class="btn btn-primary">
                                            <i class="ri-add-line me-1"></i>Add Item
                                        </a>
                                        <button class="btn btn-success" onclick="exportInventory()">
                                            <i class="ri-file-excel-line me-1"></i>Export
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Total Items</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['total_items']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="ri-medicine-bottle-line text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Total Units</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['total_units']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success rounded fs-3">
                                                <i class="ri-archive-line text-success"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Total Value</p>
                                            <h4 class="mb-0">KES <?php echo number_format($stats['total_value'], 0); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info rounded fs-3">
                                                <i class="ri-money-dollar-circle-line text-info"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Low Stock Items</p>
                                            <h4 class="mb-0"><?php echo $stats['low_stock_count']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="ri-alert-line text-warning"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="filter-card">
                                <form method="GET" action="" class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Search</label>
                                        <input type="text" class="form-control" name="search" 
                                               value="<?php echo htmlspecialchars($search_term); ?>"
                                               placeholder="Search by name, code, or brand...">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Category</label>
                                        <select class="form-control" name="category">
                                            <option value="">All Categories</option>
                                            <?php while ($cat = $categories->fetch_assoc()): ?>
                                                <option value="<?php echo $cat['category']; ?>" 
                                                        <?php echo $filter_category == $cat['category'] ? 'selected' : ''; ?>>
                                                    <?php echo ucwords(str_replace('_', ' ', strtolower($cat['category']))); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Stock Status</label>
                                        <select class="form-control" name="stock_status">
                                            <option value="">All</option>
                                            <option value="normal" <?php echo $filter_stock == 'normal' ? 'selected' : ''; ?>>Normal Stock</option>
                                            <option value="low" <?php echo $filter_stock == 'low' ? 'selected' : ''; ?>>Low Stock</option>
                                            <option value="out" <?php echo $filter_stock == 'out' ? 'selected' : ''; ?>>Out of Stock</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2 d-flex align-items-end">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-search-line me-1"></i>Filter
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Inventory Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="inventoryTable" class="table table-hover table-striped">
                                            <thead>
                                                <tr>
                                                    <th>Item Code</th>
                                                    <th>Item Name</th>
                                                    <th>Category</th>
                                                    <th>Form</th>
                                                    <th>Strength</th>
                                                    <th>Stock</th>
                                                    <th>Reorder Level</th>
                                                    <th>Unit Cost</th>
                                                    <th>Selling Price</th>
                                                    <th>Expiry Date</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($item = $inventory_items->fetch_assoc()): 
                                                    $stock_status = 'normal';
                                                    if ($item['current_stock'] == 0) {
                                                        $stock_status = 'out';
                                                    } elseif ($item['current_stock'] <= $item['reorder_level']) {
                                                        $stock_status = 'low';
                                                    }
                                                    
                                                    $expiry_warning = '';
                                                    if ($item['expiry_date']) {
                                                        $days_to_expiry = (strtotime($item['expiry_date']) - time()) / (60 * 60 * 24);
                                                        if ($days_to_expiry < 0) {
                                                            $expiry_warning = 'text-danger';
                                                        } elseif ($days_to_expiry < 30) {
                                                            $expiry_warning = 'text-warning';
                                                        }
                                                    }
                                                ?>
                                                    <tr>
                                                        <td><strong><?php echo htmlspecialchars($item['item_code']); ?></strong></td>
                                                        <td>
                                                            <?php echo htmlspecialchars($item['item_name']); ?>
                                                            <?php if ($item['generic_name']): ?>
                                                                <br><small class="text-muted"><?php echo htmlspecialchars($item['generic_name']); ?></small>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?php echo ucwords(str_replace('_', ' ', strtolower($item['category']))); ?></td>
                                                        <td><?php echo ucwords(strtolower($item['dosage_form'])); ?></td>
                                                        <td><?php echo htmlspecialchars($item['strength']); ?></td>
                                                        <td>
                                                            <span class="stock-badge stock-<?php echo $stock_status; ?>">
                                                                <?php echo $item['current_stock']; ?>
                                                            </span>
                                                        </td>
                                                        <td><?php echo $item['reorder_level']; ?></td>
                                                        <td>KES <?php echo number_format($item['unit_cost'], 2); ?></td>
                                                        <td>KES <?php echo number_format($item['selling_price'], 2); ?></td>
                                                        <td class="<?php echo $expiry_warning; ?>">
                                                            <?php echo $item['expiry_date'] ? date('d M Y', strtotime($item['expiry_date'])) : '-'; ?>
                                                        </td>
                                                        <td>
                                                            <div class="dropdown">
                                                                <button class="btn btn-sm btn-soft-secondary dropdown-toggle" 
                                                                        type="button" data-bs-toggle="dropdown">
                                                                    Actions
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li><a class="dropdown-item" href="pharmacy_inventory_view.php?id=<?php echo $item['inventory_id']; ?>">
                                                                        <i class="ri-eye-line me-2"></i>View Details
                                                                    </a></li>
                                                                    <li><a class="dropdown-item" href="pharmacy_inventory_edit.php?id=<?php echo $item['inventory_id']; ?>">
                                                                        <i class="ri-edit-line me-2"></i>Edit
                                                                    </a></li>
                                                                    <li><a class="dropdown-item" href="#" onclick="adjustStock(<?php echo $item['inventory_id']; ?>)">
                                                                        <i class="ri-stock-line me-2"></i>Adjust Stock
                                                                    </a></li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li><a class="dropdown-item text-danger" href="#" onclick="deactivateItem(<?php echo $item['inventory_id']; ?>)">
                                                                        <i class="ri-close-circle-line me-2"></i>Deactivate
                                                                    </a></li>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </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/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
    $(document).ready(function() {
        $('#inventoryTable').DataTable({
            pageLength: 25,
            order: [[1, 'asc']],
            columnDefs: [
                { orderable: false, targets: -1 }
            ]
        });
    });

    function adjustStock(inventoryId) {
        Swal.fire({
            title: 'Adjust Stock',
            html: `
                <div class="text-start">
                    <label class="form-label">Adjustment Type</label>
                    <select id="adjustment_type" class="form-control mb-3">
                        <option value="IN">Stock In (Add)</option>
                        <option value="OUT">Stock Out (Remove)</option>
                    </select>
                    <label class="form-label">Quantity</label>
                    <input type="number" id="adjustment_quantity" class="form-control mb-3" min="1" value="1">
                    <label class="form-label">Reason</label>
                    <textarea id="adjustment_reason" class="form-control" rows="2"></textarea>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Adjust',
            preConfirm: () => {
                const type = document.getElementById('adjustment_type').value;
                const quantity = document.getElementById('adjustment_quantity').value;
                const reason = document.getElementById('adjustment_reason').value;
                
                if (!quantity || quantity < 1) {
                    Swal.showValidationMessage('Please enter a valid quantity');
                    return false;
                }
                
                return { type, quantity, reason };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Submit adjustment via AJAX
                $.post('pharmacy_stock_adjust.php', {
                    inventory_id: inventoryId,
                    adjustment_type: result.value.type,
                    quantity: result.value.quantity,
                    reason: result.value.reason
                }, function(response) {
                    if (response.success) {
                        Swal.fire('Success', 'Stock adjusted successfully', 'success')
                            .then(() => location.reload());
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }, 'json');
            }
        });
    }

    function deactivateItem(inventoryId) {
        Swal.fire({
            title: 'Deactivate Item?',
            text: 'This item will be hidden from the active inventory list',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc2626',
            confirmButtonText: 'Yes, deactivate'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('pharmacy_inventory_deactivate.php', {
                    inventory_id: inventoryId
                }, function(response) {
                    if (response.success) {
                        Swal.fire('Deactivated', 'Item has been deactivated', 'success')
                            .then(() => location.reload());
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }, 'json');
            }
        });
    }

    function exportInventory() {
        window.location.href = 'pharmacy_inventory_export.php?<?php echo http_build_query($_GET); ?>';
    }
    </script>
</body>
</html>