<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : 0;
$product = null;
$stock_movements = [];

if($product_id > 0) {
    $product_sql = "SELECT * FROM lube_products WHERE id = $product_id";
    $product_result = mysqli_query($conn, $product_sql);
    $product = mysqli_fetch_assoc($product_result);
    
    if($product) {
        $movement_sql = "SELECT * FROM stock_movements WHERE product_id = $product_id ORDER BY id DESC LIMIT 100";
        $stock_movements = mysqli_query($conn, $movement_sql);
    }
}

// Get all products for dropdown
$all_products_sql = "SELECT id, product_code, product_name, current_stock, minimum_stock FROM lube_products ORDER BY product_name";
$all_products_result = mysqli_query($conn, $all_products_sql);
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="lube-stock-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-chart-line"></i> Stock Management</h2>
            <p>Track inventory movements and stock levels</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-boxes"></i>
                <span>Stock Movement History</span>
            </div>
        </div>
    </div>

    <!-- Product Selection -->
    <div class="selection-card">
        <div class="selection-header">
            <i class="fas fa-filter"></i>
            <h4>Select Product</h4>
        </div>
        <div class="selection-body">
            <form method="GET" action="" class="selection-form">
                <div class="selection-row">
                    <div class="selection-group">
                        <select name="product_id" id="product_id" class="form-control-modern" onchange="this.form.submit()">
                            <option value="">-- Select Product --</option>
                            <?php 
                            mysqli_data_seek($all_products_result, 0);
                            while($prod = mysqli_fetch_assoc($all_products_result)): 
                                $selected = ($product_id == $prod['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $prod['id']; ?>" <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($prod['product_code']) . ' - ' . htmlspecialchars($prod['product_name']); ?>
                                    (Stock: <?php echo number_format($prod['current_stock'], 2); ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="selection-group">
                        <a href="lube_products.php" class="btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Products
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php if($product): ?>
        <!-- Product Info Cards -->
        <div class="product-info-grid">
            <div class="info-card">
                <div class="info-icon"><i class="fas fa-oil-can"></i></div>
                <div class="info-content">
                    <h3><?php echo htmlspecialchars($product['product_name']); ?></h3>
                    <div class="info-details">
                        <span><i class="fas fa-barcode"></i> Code: <?php echo $product['product_code']; ?></span>
                        <span><i class="fas fa-building"></i> Brand: <?php echo $product['brand'] ?: '-'; ?></span>
                        <span><i class="fas fa-box"></i> Pack: <?php echo $product['pack_size'] ?: '-'; ?></span>
                    </div>
                </div>
            </div>
            <div class="stock-summary-grid">
                <div class="stock-summary-card">
                    <div class="summary-label">Current Stock</div>
                    <div class="summary-value <?php echo $product['current_stock'] <= $product['minimum_stock'] ? 'low' : ''; ?>">
                        <?php echo number_format($product['current_stock'], 2); ?>
                    </div>
                    <div class="summary-unit">Units</div>
                </div>
                <div class="stock-summary-card">
                    <div class="summary-label">Minimum Stock</div>
                    <div class="summary-value">
                        <?php echo number_format($product['minimum_stock'], 2); ?>
                    </div>
                    <div class="summary-unit">Alert Level</div>
                </div>
                <div class="stock-summary-card">
                    <div class="summary-label">Stock Value</div>
                    <div class="summary-value">
                        Rs <?php echo number_format($product['current_stock'] * $product['purchase_price'], 2); ?>
                    </div>
                    <div class="summary-unit">At Purchase Price</div>
                </div>
                <div class="stock-summary-card">
                    <div class="summary-label">Sale Value</div>
                    <div class="summary-value">
                        Rs <?php echo number_format($product['current_stock'] * $product['sale_price'], 2); ?>
                    </div>
                    <div class="summary-unit">At Sale Price</div>
                </div>
            </div>
        </div>

        <!-- Stock Movement Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-history"></i>
                    <h4>Stock Movement History</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search movements..." class="search-input">
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="movementTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Date & Time</th>
                                <th>Movement Type</th>
                                <th>Reference No</th>
                                <th>Quantity In</th>
                                <th>Quantity Out</th>
                                <th>Balance</th>
                                <th>User</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $sr_no = 1;
                            if($stock_movements && mysqli_num_rows($stock_movements) > 0):
                                while($movement = mysqli_fetch_assoc($stock_movements)): 
                                    $type_class = $movement['movement_type'] == 'purchase' ? 'type-purchase' : ($movement['movement_type'] == 'sale' ? 'type-sale' : 'type-adjustment');
                                    $type_icon = $movement['movement_type'] == 'purchase' ? 'fa-arrow-down' : ($movement['movement_type'] == 'sale' ? 'fa-arrow-up' : 'fa-exchange-alt');
                            ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sr_no++; ?></td>
                                        <td data-label="Date"><?php echo date('d-m-Y H:i:s', strtotime($movement['date_time'])); ?></td>
                                        <td data-label="Type">
                                            <span class="movement-badge <?php echo $type_class; ?>">
                                                <i class="fas <?php echo $type_icon; ?>"></i>
                                                <?php echo ucfirst($movement['movement_type']); ?>
                                            </span>
                                        </div>
                                        <td data-label="Reference"><?php echo htmlspecialchars($movement['reference_no'] ?: '-'); ?></div>
                                        <td data-label="Quantity In" class="qty-in">
                                            <?php echo $movement['quantity_in'] > 0 ? number_format($movement['quantity_in'], 2) : '-'; ?>
                                        </div>
                                        <td data-label="Quantity Out" class="qty-out">
                                            <?php echo $movement['quantity_out'] > 0 ? number_format($movement['quantity_out'], 2) : '-'; ?>
                                        </div>
                                        <td data-label="Balance" class="balance-stock">
                                            <strong><?php echo number_format($movement['balance_stock'], 2); ?></strong>
                                        </div>
                                        <td data-label="User"><?php echo htmlspecialchars($movement['user_name'] ?: '-'); ?></div>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="empty-state">
                                        <i class="fas fa-chart-line"></i>
                                        <p>No stock movements found</p>
                                        <small>Stock movements will appear when purchases or sales are made</small>
                                    </div>
                                    </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Low Stock Warning -->
        <?php if($product['current_stock'] <= $product['minimum_stock'] && $product['minimum_stock'] > 0): ?>
            <div class="warning-card">
                <i class="fas fa-exclamation-triangle"></i>
                <div class="warning-content">
                    <strong>Low Stock Alert!</strong>
                    <p>Current stock (<?php echo number_format($product['current_stock'], 2); ?>) is below minimum stock level (<?php echo number_format($product['minimum_stock'], 2); ?>). Please reorder soon.</p>
                </div>
                <a href="lube_purchase.php" class="btn-reorder">
                    <i class="fas fa-shopping-cart"></i> Reorder Now
                </a>
            </div>
        <?php endif; ?>

    <?php elseif($product_id > 0 && !$product): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle"></i> Product not found!
        </div>
    <?php else: ?>
        <div class="empty-card">
            <div class="empty-state-large">
                <i class="fas fa-boxes"></i>
                <h4>Select a product to view stock details</h4>
                <p>Choose a product from the dropdown above to see stock movement history</p>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
/* Lube Stock Management Styles - Page Specific Only */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.selection-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

.lube-stock-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    margin: 0 0 3px 0;
    font-size: 22px;
}

.page-header p {
    margin: 0;
    font-size: 12px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 16px;
    border-radius: 12px;
    font-weight: 500;
    font-size: 12px;
}

/* Selection Card */
.selection-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    width: 100%;
}

.selection-header {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 12px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
}

.selection-header h4 {
    margin: 0;
    font-size: 15px;
}

.selection-body {
    padding: 18px;
}

.selection-row {
    display: flex;
    gap: 12px;
    align-items: flex-end;
}

.selection-group {
    flex: 1;
}

.form-control-modern {
    width: 100%;
    padding: 10px 14px;
    border: 2px solid #e8e8e8;
    border-radius: 10px;
    font-size: 13px;
    transition: all 0.3s;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
}

.btn-secondary {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 10px 20px;
    background: #f0f0f0;
    color: #555;
    border-radius: 10px;
    text-decoration: none;
    font-weight: 600;
    font-size: 13px;
    transition: all 0.3s;
}

.btn-secondary:hover {
    background: #e0e0e0;
    text-decoration: none;
    color: #555;
}

/* Product Info Grid */
.product-info-grid {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 20px;
    margin-bottom: 20px;
    width: 100%;
}

.info-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    border-left: 4px solid #A04657;
}

.info-icon i {
    font-size: 40px;
    color: #A04657;
    background: rgba(160,70,87,0.1);
    padding: 10px;
    border-radius: 14px;
}

.info-content h3 {
    margin: 0 0 8px 0;
    font-size: 18px;
    font-weight: 700;
}

.info-details {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
}

.info-details span {
    font-size: 12px;
    color: #666;
}

.info-details span i {
    color: #A04657;
    margin-right: 4px;
}

/* Stock Summary Grid */
.stock-summary-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
    margin-bottom: 20px;
    width: 100%;
}

.stock-summary-card {
    background: #fff;
    border-radius: 14px;
    padding: 12px;
    text-align: center;
    border: 1px solid #f0f0f0;
}

.summary-label {
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    color: #999;
}

.summary-value {
    font-size: 22px;
    font-weight: 800;
    margin: 6px 0;
    color: #1a1a2e;
}

.summary-value.low {
    color: #dc3545;
}

.summary-unit {
    font-size: 9px;
    color: #999;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    margin-bottom: 20px;
    width: 100%;
}

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-info i {
    font-size: 18px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 15px;
}

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
    font-size: 12px;
}

.search-input {
    padding: 7px 12px 7px 36px;
    border: 2px solid #e8e8e8;
    border-radius: 30px;
    width: 220px;
    font-size: 12px;
}

.search-input:focus {
    border-color: #A04657;
    outline: none;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 700px;
}

.modern-table th {
    padding: 10px 12px;
    background: #f8f9fc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    text-transform: uppercase;
    border-bottom: 2px solid #e8e8e8;
}

.modern-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 12px;
    vertical-align: middle;
}

.movement-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
}

.type-purchase {
    background: #e8f5e9;
    color: #2e7d32;
}

.type-sale {
    background: #ffebee;
    color: #c62828;
}

.type-adjustment {
    background: #fff3e0;
    color: #e65100;
}

.qty-in {
    color: #28a745;
    font-weight: 600;
}

.qty-out {
    color: #dc3545;
    font-weight: 600;
}

.balance-stock {
    font-weight: 600;
}

/* Warning Card */
.warning-card {
    background: #fff3e0;
    border-radius: 14px;
    padding: 14px 18px;
    display: flex;
    align-items: center;
    gap: 12px;
    border-left: 4px solid #ff9800;
    margin-bottom: 20px;
    width: 100%;
}

.warning-card i {
    font-size: 24px;
    color: #ff9800;
}

.warning-content {
    flex: 1;
}

.warning-content strong {
    display: block;
    font-size: 13px;
    color: #e65100;
}

.warning-content p {
    margin: 4px 0 0;
    font-size: 11px;
    color: #666;
}

.btn-reorder {
    padding: 6px 16px;
    background: #ff9800;
    color: #fff;
    border-radius: 30px;
    text-decoration: none;
    font-weight: 600;
    font-size: 11px;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
}

.btn-reorder:hover {
    background: #e65100;
    text-decoration: none;
    color: #fff;
}

/* Empty States */
.empty-state {
    text-align: center;
    padding: 40px !important;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.3;
    margin-bottom: 12px;
    display: block;
}

.empty-card {
    background: #fff;
    border-radius: 16px;
    padding: 40px;
    text-align: center;
    width: 100%;
}

.empty-state-large i {
    font-size: 64px;
    color: #A04657;
    opacity: 0.3;
    margin-bottom: 16px;
    display: block;
}

.empty-card p {
    font-size: 13px;
    color: #666;
}

/* Alerts */
.alert-custom {
    padding: 12px 18px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 13px;
    width: 100%;
}

.alert-danger {
    background: #ffebee;
    color: #c62828;
    border-left: 4px solid #dc3545;
}

/* Responsive */
@media (max-width: 1100px) {
    .stock-summary-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    .product-info-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px 12px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 10px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .selection-row {
        flex-direction: column;
        gap: 10px;
    }
    .selection-group {
        width: 100%;
    }
    .btn-secondary {
        width: 100%;
        justify-content: center;
    }
    .stock-summary-grid {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .product-info-grid {
        gap: 15px;
    }
    .info-card {
        padding: 12px 16px;
    }
    .info-icon i {
        font-size: 32px;
        padding: 8px;
    }
    .info-content h3 {
        font-size: 16px;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .search-input {
        width: 100%;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 12px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
    .warning-card {
        padding: 10px 14px;
    }
    .warning-card i {
        font-size: 20px;
    }
    .empty-card {
        padding: 30px;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<script>
document.getElementById('tableSearch')?.addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase();
    let rows = document.querySelectorAll('#movementTable tbody tr');
    rows.forEach(row => {
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchValue) ? '' : 'none';
    });
});
</script>

<?php include('../includes/ft.php'); ?>