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

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

$success_message = "";
$error_message = "";

// Add Product
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_product'])) {
    // Generate product code automatically if not provided
    $product_code = mysqli_real_escape_string($conn, $_POST['product_code']);
    if(empty($product_code)) {
        $last_id_sql = "SELECT id FROM lube_products ORDER BY id DESC LIMIT 1";
        $last_id_result = mysqli_query($conn, $last_id_sql);
        $last_id = mysqli_num_rows($last_id_result) > 0 ? mysqli_fetch_assoc($last_id_result)['id'] + 1 : 1;
        $product_code = "LUBE-" . date('Ymd') . "-" . str_pad($last_id, 3, '0', STR_PAD_LEFT);
    }
    
    $product_name = mysqli_real_escape_string($conn, $_POST['product_name']);
    $brand = mysqli_real_escape_string($conn, $_POST['brand']);
    $pack_size = mysqli_real_escape_string($conn, $_POST['pack_size']);
    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $purchase_price = mysqli_real_escape_string($conn, $_POST['purchase_price']);
    $sale_price = mysqli_real_escape_string($conn, $_POST['sale_price']);
    $opening_stock = mysqli_real_escape_string($conn, $_POST['opening_stock']);
    $minimum_stock = mysqli_real_escape_string($conn, $_POST['minimum_stock']);
    $created_at = date('Y-m-d H:i:s');
    
    if(empty($product_name)) {
        $error_message = "Product Name is required!";
    } elseif($purchase_price <= 0 || $sale_price <= 0) {
        $error_message = "Prices must be greater than 0!";
    } elseif($opening_stock < 0) {
        $error_message = "Opening stock cannot be negative!";
    } else {
        $check_sql = "SELECT id FROM lube_products WHERE product_code='$product_code'";
        $check_result = mysqli_query($conn, $check_sql);
        
        if(mysqli_num_rows($check_result) > 0) {
            $error_message = "Product Code already exists!";
        } else {
            mysqli_begin_transaction($conn);
            try {
                $sql = "INSERT INTO lube_products (product_code, product_name, brand, pack_size, category, 
                        purchase_price, sale_price, current_stock, minimum_stock, status, created_at) 
                        VALUES ('$product_code', '$product_name', '$brand', '$pack_size', '$category', 
                        '$purchase_price', '$sale_price', '$opening_stock', '$minimum_stock', 'active', '$created_at')";
                
                if(mysqli_query($conn, $sql)) {
                    $product_id = mysqli_insert_id($conn);
                    
                    // Add opening stock movement
                    if($opening_stock > 0) {
                        $movement_sql = "INSERT INTO stock_movements (product_id, movement_type, reference_no, quantity_in, quantity_out, balance_stock, date_time, user_name) 
                                        VALUES ('$product_id', 'purchase', 'OPENING-$product_id', '$opening_stock', '0', '$opening_stock', '$created_at', '{$_SESSION['username']}')";
                        mysqli_query($conn, $movement_sql);
                    }
                    
                    mysqli_commit($conn);
                    $success_message = "Product added successfully! Opening Stock: " . number_format($opening_stock, 2);
                } else {
                    throw new Exception(mysqli_error($conn));
                }
            } catch(Exception $e) {
                mysqli_rollback($conn);
                $error_message = "Error: " . $e->getMessage();
            }
        }
    }
}

// Add Stock
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_stock'])) {
    $product_id = mysqli_real_escape_string($conn, $_POST['product_id']);
    $add_stock = mysqli_real_escape_string($conn, $_POST['add_stock']);
    $reference_no = mysqli_real_escape_string($conn, $_POST['reference_no']);
    $date_time = date('Y-m-d H:i:s');
    
    if($add_stock <= 0) {
        $error_message = "Please enter valid stock quantity!";
    } else {
        mysqli_begin_transaction($conn);
        try {
            $current_sql = "SELECT current_stock FROM lube_products WHERE id='$product_id'";
            $current_result = mysqli_query($conn, $current_sql);
            $current = mysqli_fetch_assoc($current_result);
            $new_stock = $current['current_stock'] + $add_stock;
            
            $update_sql = "UPDATE lube_products SET current_stock = '$new_stock' WHERE id='$product_id'";
            mysqli_query($conn, $update_sql);
            
            $movement_sql = "INSERT INTO stock_movements (product_id, movement_type, reference_no, quantity_in, quantity_out, balance_stock, date_time, user_name) 
                            VALUES ('$product_id', 'purchase', '$reference_no', '$add_stock', '0', '$new_stock', '$date_time', '{$_SESSION['username']}')";
            mysqli_query($conn, $movement_sql);
            
            mysqli_commit($conn);
            $success_message = "Stock added successfully! +" . number_format($add_stock, 2) . " units added.";
        } catch(Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Delete Product
if(isset($_GET['delete'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete']);
    
    $check_sales = "SELECT id FROM lube_sale_items WHERE product_id='$delete_id' LIMIT 1";
    $sales_result = mysqli_query($conn, $check_sales);
    
    if(mysqli_num_rows($sales_result) > 0) {
        $error_message = "Cannot delete! Product has sale records.";
    } else {
        $sql = "DELETE FROM lube_products WHERE id='$delete_id'";
        if(mysqli_query($conn, $sql)) {
            $success_message = "Product deleted successfully!";
        } else {
            $error_message = "Error deleting product";
        }
    }
}

// Get all products
$sql = "SELECT * FROM lube_products ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
$total_products = mysqli_num_rows($result);
$total_stock_value = 0;
$low_stock_count = 0;

while($row = mysqli_fetch_assoc($result)) {
    $total_stock_value += $row['current_stock'] * $row['purchase_price'];
    if($row['current_stock'] <= $row['minimum_stock'] && $row['minimum_stock'] > 0) {
        $low_stock_count++;
    }
}
mysqli_data_seek($result, 0);
?>

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

<div class="lube-products-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-oil-can"></i> Lube Products</h2>
            <p>Manage lubricant products, stock and prices</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_products; ?> Total Products</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-boxes"></i></div>
            <div class="stat-info">
                <h3><?php echo $total_products; ?></h3>
                <p>Total Products</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-rupee-sign"></i></div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_stock_value, 2); ?></h3>
                <p>Stock Value</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="stat-info">
                <h3><?php echo $low_stock_count; ?></h3>
                <p>Low Stock Items</p>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>

    <div class="content-grid">
        <!-- Add Product Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4>Add New Product</h4>
            </div>
            <div class="form-card-body">
                <form method="POST" action="">
                    <div class="input-group-custom">
                        <label><i class="fas fa-barcode"></i> Product Code</label>
                        <input type="text" name="product_code" class="form-control-modern" placeholder="Leave empty for auto-generation">
                        <small class="input-help">Auto-generated if left empty</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-tag"></i> Product Name <span class="required">*</span></label>
                        <input type="text" name="product_name" class="form-control-modern" required placeholder="e.g., Engine Oil 10W-40">
                    </div>

                    <div class="row-inputs">
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-building"></i> Brand</label>
                                <input type="text" name="brand" class="form-control-modern" placeholder="e.g., Shell, Castrol">
                            </div>
                        </div>
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-box"></i> Pack Size</label>
                                <input type="text" name="pack_size" class="form-control-modern" placeholder="e.g., 1L, 5L">
                            </div>
                        </div>
                    </div>

                    <div class="row-inputs">
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-layer-group"></i> Category</label>
                                <select name="category" class="form-control-modern">
                                    <option value="">Select Category</option>
                                    <option value="Engine Oil">Engine Oil</option>
                                    <option value="Gear Oil">Gear Oil</option>
                                    <option value="Hydraulic Oil">Hydraulic Oil</option>
                                    <option value="Grease">Grease</option>
                                    <option value="Coolant">Coolant</option>
                                    <option value="Brake Fluid">Brake Fluid</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row-inputs">
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-shopping-cart"></i> Purchase Price (Rs) <span class="required">*</span></label>
                                <input type="number" step="0.01" name="purchase_price" id="purchase_price" class="form-control-modern" required value="0">
                            </div>
                        </div>
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-tag"></i> Sale Price (Rs) <span class="required">*</span></label>
                                <input type="number" step="0.01" name="sale_price" id="sale_price" class="form-control-modern" required value="0">
                            </div>
                        </div>
                    </div>

                    <div class="row-inputs">
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-database"></i> Opening Stock <span class="required">*</span></label>
                                <input type="number" step="0.01" name="opening_stock" id="opening_stock" class="form-control-modern" required value="0" placeholder="Initial stock quantity">
                            </div>
                        </div>
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-exclamation-triangle"></i> Minimum Stock Alert</label>
                                <input type="number" step="0.01" name="minimum_stock" class="form-control-modern" value="0" placeholder="Alert when stock below this level">
                            </div>
                        </div>
                    </div>

                    <div class="profit-preview" id="profitPreview" style="display: none;">
                        <div class="preview-row">
                            <span><i class="fas fa-chart-line"></i> Profit per Unit:</span>
                            <strong id="previewProfit">Rs 0.00</strong>
                        </div>
                        <div class="preview-row">
                            <span><i class="fas fa-percent"></i> Margin:</span>
                            <strong id="previewMargin">0%</strong>
                        </div>
                    </div>

                    <button type="submit" name="add_product" class="btn-submit">
                        <i class="fas fa-save"></i> Add Product
                    </button>
                </form>
            </div>
        </div>

        <!-- Products List -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-list"></i>
                    <h4>Products List</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search product..." class="search-input">
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="productsTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Code</th>
                                <th>Product Name</th>
                                <th>Brand</th>
                                <th>Pack</th>
                                <th>Purchase Price</th>
                                <th>Sale Price</th>
                                <th>Stock</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($result) > 0): ?>
                                <?php 
                                $sr_no = 1;
                                while($row = mysqli_fetch_assoc($result)): 
                                    $stock_status = ($row['current_stock'] <= $row['minimum_stock'] && $row['minimum_stock'] > 0) ? 'low' : 'normal';
                                    if($row['current_stock'] <= 0) $stock_status = 'low';
                                    $stock_text = $stock_status == 'low' ? 'Low Stock' : 'In Stock';
                                ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sr_no++; ?></td>
                                        <td data-label="Code"><?php echo htmlspecialchars($row['product_code']); ?></td>
                                        <td data-label="Product Name">
                                            <div class="product-name-cell">
                                                <div class="avatar"><i class="fas fa-oil-can"></i></div>
                                                <strong><?php echo htmlspecialchars($row['product_name']); ?></strong>
                                            </div>
                                        </div>
                                        <td data-label="Brand"><?php echo htmlspecialchars($row['brand'] ?: '-'); ?></td>
                                        <td data-label="Pack"><?php echo htmlspecialchars($row['pack_size'] ?: '-'); ?></td>
                                        <td data-label="Purchase Price" class="purchase-price">Rs <?php echo number_format($row['purchase_price'], 2); ?></td>
                                        <td data-label="Sale Price" class="sale-price">Rs <?php echo number_format($row['sale_price'], 2); ?></td>
                                        <td data-label="Stock">
                                            <span class="stock-badge <?php echo $stock_status; ?>">
                                                <?php echo number_format($row['current_stock'], 2); ?>
                                            </span>
                                        </div>
                                        <td data-label="Status">
                                            <span class="status-badge <?php echo $stock_status; ?>">
                                                <i class="fas <?php echo $stock_status == 'low' ? 'fa-exclamation-triangle' : 'fa-check-circle'; ?>"></i>
                                                <?php echo $stock_text; ?>
                                            </span>
                                        </div>
                                        <td data-label="Actions">
                                            <div class="action-buttons">
                                                <button class="btn-action btn-stock" data-bs-toggle="modal" data-bs-target="#addStockModal" 
                                                        data-id="<?php echo $row['id']; ?>" data-name="<?php echo htmlspecialchars($row['product_name']); ?>"
                                                        title="Add Stock">
                                                    <i class="fas fa-plus-circle"></i>
                                                </button>
                                                <a href="lube_stock.php?product_id=<?php echo $row['id']; ?>" class="btn-action btn-stock" title="Stock History">
                                                    <i class="fas fa-chart-line"></i>
                                                </a>
                                                <a href="?delete=<?php echo $row['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Delete this product?')" title="Delete Product">
                                                    <i class="fas fa-trash-alt"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="10" class="empty-state">
                                        <i class="fas fa-oil-can"></i>
                                        <p>No products found</p>
                                        <small>Click "Add New Product" to get started</small>
                                    </div>
                                    </tr>
                            <?php endif; ?>
                        </tbody>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Stock Modal -->
<div class="modal fade" id="addStockModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header-custom">
                <i class="fas fa-plus-circle"></i>
                <h5 class="modal-title">Add Stock</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="">
                <div class="modal-body p-3">
                    <input type="hidden" name="product_id" id="stock_product_id">
                    <div class="bg-light p-2 rounded mb-3">
                        <i class="fas fa-oil-can" style="color:#A04657;"></i>
                        <strong id="stock_product_name" class="ms-2"></strong>
                    </div>
                    <div class="input-group-custom mb-2">
                        <label><i class="fas fa-database"></i> Quantity to Add <span class="required">*</span></label>
                        <input type="number" step="0.01" name="add_stock" class="form-control-modern" required placeholder="Enter quantity">
                    </div>
                    <div class="input-group-custom mb-2">
                        <label><i class="fas fa-file-invoice"></i> Reference No (Optional)</label>
                        <input type="text" name="reference_no" class="form-control-modern" placeholder="PO-123, INV-456">
                    </div>
                </div>
                <div class="modal-footer border-0 pb-3 px-3">
                    <button type="button" class="btn btn-light btn-sm px-3" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="update_stock" class="btn-update btn-sm px-3" style="background:#A04657; color:#fff; border:none; padding:6px 15px; border-radius:20px;">Add Stock</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

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

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

h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-info h3,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Times New Roman', serif;
}

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

.lube-products-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: 18px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    box-shadow: 0 4px 15px rgba(160,70,87,0.2);
    width: 100%;
}

.page-header h2 {
    margin: 0 0 4px 0;
    font-size: 22px;
    font-weight: 700;
}

.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: 40px;
    font-size: 12px;
    font-weight: 600;
}

/* Statistics Row */
.stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.stat-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    transition: all 0.3s;
    border: 1px solid #f0f0f0;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 18px rgba(160,70,87,0.1);
}

.stat-icon {
    width: 52px;
    height: 52px;
    background: rgba(160,70,87,0.1);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon i {
    font-size: 26px;
    color: #A04657;
}

.stat-info h3 {
    font-size: 24px;
    margin: 0;
    font-weight: 700;
    color: #1a1a2e;
}

.stat-info p {
    margin: 3px 0 0;
    color: #666;
    font-size: 11px;
    font-weight: 500;
}

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

.alert-success {
    background: #d4edda;
    color: #155724;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    opacity: 0.6;
}

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 380px 1fr;
    gap: 20px;
    width: 100%;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    border: 1px solid #f0f0f0;
    height: fit-content;
}

.form-card-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
}

.form-card-header i {
    font-size: 18px;
}

.form-card-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #fff;
}

.form-card-body {
    padding: 20px;
}

.input-group-custom {
    margin-bottom: 16px;
}

.input-group-custom label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    color: #333;
    font-size: 12px;
}

.input-group-custom label i {
    color: #A04657;
    margin-right: 5px;
    width: 16px;
}

.required {
    color: #dc3545;
}

.input-help {
    display: block;
    font-size: 10px;
    color: #999;
    margin-top: 4px;
}

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

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
    box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
}

.row-inputs {
    display: flex;
    gap: 10px;
}

.input-half {
    flex: 1;
}

.profit-preview {
    background: #e8f5e9;
    border-radius: 10px;
    padding: 10px;
    margin-bottom: 16px;
}

.preview-row {
    display: flex;
    justify-content: space-between;
    padding: 3px 0;
    font-size: 12px;
}

.btn-submit {
    width: 100%;
    padding: 10px;
    background: linear-gradient(135deg, #A04657, #6b2a36);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    border: 1px solid #f0f0f0;
    width: 100%;
}

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

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

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

.header-info h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.table-search {
    position: relative;
}

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

.search-input {
    padding: 8px 12px 8px 35px;
    border: 2px solid #e8e8e8;
    border-radius: 30px;
    width: 200px;
    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: 900px;
}

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

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

.product-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.product-name-cell .avatar {
    width: 28px;
    height: 28px;
    background: rgba(160,70,87,0.1);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.product-name-cell .avatar i {
    font-size: 14px;
    color: #A04657;
}

.purchase-price, .sale-price {
    font-weight: 600;
}

.stock-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 700;
}

.stock-badge.normal {
    background: #e8f5e9;
    color: #2e7d32;
}

.stock-badge.low {
    background: #ffebee;
    color: #c62828;
}

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

.status-badge.normal {
    background: #e8f5e9;
    color: #2e7d32;
}

.status-badge.low {
    background: #ffebee;
    color: #c62828;
}

.action-buttons {
    display: flex;
    gap: 5px;
}

.btn-action {
    width: 28px;
    height: 28px;
    border-radius: 8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: all 0.2s;
    border: none;
    cursor: pointer;
}

.btn-stock {
    background: #e3f2fd;
    color: #1976d2;
}

.btn-stock:hover {
    background: #1976d2;
    color: #fff;
    transform: scale(1.05);
}

.btn-delete {
    background: #ffebee;
    color: #d32f2f;
}

.btn-delete:hover {
    background: #d32f2f;
    color: #fff;
    transform: scale(1.05);
}

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

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

.empty-state p {
    font-size: 13px;
    color: #666;
    margin-bottom: 4px;
}

.empty-state small {
    font-size: 11px;
    color: #999;
}

/* Modal */
.modal-content {
    border-radius: 12px;
    border: none;
}

.modal-header-custom {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 12px 15px;
    color: #fff;
    border-radius: 12px 12px 0 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.modal-header-custom .modal-title {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
}

.btn-close-white {
    filter: brightness(0) invert(1);
}

/* Responsive */
@media (max-width: 1100px) {
    .content-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;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .row-inputs {
        flex-direction: column;
        gap: 0;
    }
    .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: 11px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
    .stat-card {
        padding: 12px 16px;
    }
    .stat-icon {
        width: 44px;
        height: 44px;
    }
    .stat-icon i {
        font-size: 22px;
    }
    .stat-info h3 {
        font-size: 20px;
    }
    .form-card-body {
        padding: 16px;
    }
}

/* 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>
// Table search
const searchInput = document.getElementById('tableSearch');
if(searchInput) {
    searchInput.addEventListener('keyup', function() {
        let searchValue = this.value.toLowerCase();
        let table = document.getElementById('productsTable');
        let rows = table.getElementsByTagName('tr');
        for (let i = 1; i < rows.length; i++) {
            let text = rows[i].textContent.toLowerCase();
            rows[i].style.display = text.includes(searchValue) ? '' : 'none';
        }
    });
}

// Profit preview
const purchasePrice = document.getElementById('purchase_price');
const salePrice = document.getElementById('sale_price');
const profitPreview = document.getElementById('profitPreview');
const previewProfit = document.getElementById('previewProfit');
const previewMargin = document.getElementById('previewMargin');

function updateProfitPreview() {
    let purchase = parseFloat(purchasePrice?.value) || 0;
    let sale = parseFloat(salePrice?.value) || 0;
    
    if(sale > 0 && profitPreview) {
        profitPreview.style.display = 'block';
        let profit = sale - purchase;
        let margin = sale > 0 ? (profit / sale) * 100 : 0;
        previewProfit.innerHTML = 'Rs ' + profit.toFixed(2);
        previewMargin.innerHTML = margin.toFixed(2) + '%';
        previewProfit.style.color = profit > 0 ? '#28a745' : (profit < 0 ? '#dc3545' : '#666');
    } else if(profitPreview) {
        profitPreview.style.display = 'none';
    }
}

if(purchasePrice && salePrice) {
    purchasePrice.addEventListener('input', updateProfitPreview);
    salePrice.addEventListener('input', updateProfitPreview);
}

// Modal data
const addStockModal = document.getElementById('addStockModal');
if(addStockModal) {
    addStockModal.addEventListener('show.bs.modal', function(event) {
        const button = event.relatedTarget;
        document.getElementById('stock_product_id').value = button.getAttribute('data-id');
        document.getElementById('stock_product_name').innerHTML = button.getAttribute('data-name');
    });
}

// Auto hide alerts
document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => {
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 300);
    }, 5000);
});
</script>

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