<?php
// Ensure session is started only once
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

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

$user = $_SESSION['user'];
$shop_id = $user['shop_id'];
$user_role = $user['role'] ?? 'cashier';

// Admin can filter by shop - default to user's own shop
$selected_shop = ($user_role === 'admin' && isset($_GET['shop_id'])) ? intval($_GET['shop_id']) : $shop_id;

// Check if user has permission to view other shops
if ($user_role !== 'admin' && $selected_shop != $shop_id) {
    $selected_shop = $shop_id; // Reset to own shop if not admin
}

// Get filter options
$filter_status = $_GET['status'] ?? 'active'; // active, inactive, all
$search_term = $_GET['search'] ?? '';

// Build query with filters
$params = [];
$where_clauses = [];

// Add shop filter - handle "All Shops" (0) for admin
if ($user_role === 'admin' && $selected_shop == 0) {
    // Admin viewing all shops - no shop filter
} else {
    $where_clauses[] = "p.shop_id = ?";
    $params[] = $selected_shop;
}

// Add status filter
if ($filter_status === 'active') {
    $where_clauses[] = "p.is_active = 1";
} elseif ($filter_status === 'inactive') {
    $where_clauses[] = "p.is_active = 0";
}
// 'all' shows both active and inactive

// Add search filter
if (!empty($search_term)) {
    $where_clauses[] = "(p.name LIKE ? OR p.sku LIKE ? OR p.generic_name LIKE ? OR p.category LIKE ?)";
    $search_like = "%$search_term%";
    $params[] = $search_like;
    $params[] = $search_like;
    $params[] = $search_like;
    $params[] = $search_like;
}

// Build the query
$where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';
$sql = "SELECT 
            p.*,
            COALESCE(ps.total_qty, 0) as current_stock,
            COALESCE(ps.batch_count, 0) as batch_count,
            ps.earliest_expiry,
            ps.latest_expiry
        FROM products p
        LEFT JOIN product_stock_view ps ON p.id = ps.product_id
        $where_sql
        ORDER BY p.is_active DESC, p.name ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get suppliers for the batch modal
$suppliers = $pdo->query("SELECT id, name FROM suppliers ORDER BY name")->fetchAll();

// Calculate summary statistics
$total_products = count($products);
$active_products = 0;
$inactive_products = 0;
$total_stock_value = 0;
$low_stock_count = 0;
$expired_count = 0;
$zero_stock_count = 0;

foreach ($products as $product) {
    if ($product['is_active'] == 1) {
        $active_products++;
    } else {
        $inactive_products++;
    }
    
    $stock_value = $product['current_stock'] * $product['buying_price'];
    $total_stock_value += $stock_value;
    
    if ($product['current_stock'] <= 0) {
        $zero_stock_count++;
    } elseif ($product['current_stock'] <= 20) {
        $low_stock_count++;
    }
    
    if ($product['earliest_expiry'] && strtotime($product['earliest_expiry']) < time()) {
        $expired_count++;
    }
}

// Get ALL shops from database for the dropdown
$all_shops = $pdo->query("SELECT id, name FROM shops ORDER BY name")->fetchAll();

// Get current shop name for display
$current_shop_name = '';
foreach ($all_shops as $shop) {
    if ($shop['id'] == $shop_id) {
        $current_shop_name = $shop['name'];
        break;
    }
}

// Get selected shop name for display (if viewing specific shop)
$selected_shop_name = '';
if ($user_role === 'admin') {
    if ($selected_shop == 0) {
        $selected_shop_name = 'All Shops';
    } else {
        foreach ($all_shops as $shop) {
            if ($shop['id'] == $selected_shop) {
                $selected_shop_name = $shop['name'];
                break;
            }
        }
    }
}
?>

<style>
/* Products page specific styles */
.table-hover tbody tr:hover {
    background-color: rgba(0,0,0,.075);
}
.table-secondary {
    background-color: #f8f9fa;
}
.table-danger {
    background-color: #f8d7da;
}
.table-warning {
    background-color: #fff3cd;
}
.badge {
    font-size: 0.85em;
}
.btn-group-sm > .btn {
    padding: 0.25rem 0.5rem;
}
.view-batches-btn:hover {
    transform: scale(1.05);
    transition: transform 0.2s;
}

/* Main content wrapper adjustments */
.main-content-wrapper {
    padding: 20px;
    min-height: calc(100vh - 80px);
    background-color: #f5f7fb;
}

.card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    transition: transform 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.12);
}

/* Modal Styles */
#addBatchModal .modal-dialog,
#viewProductModal .modal-dialog {
    max-width: 800px;
}

#addBatchModal .modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

#viewProductModal .modal-header {
    background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
    color: white;
}

#batchModal .modal-header {
    background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
    color: white;
}

.modal-body {
    max-height: 70vh;
    overflow-y: auto;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .main-content-wrapper {
        padding: 15px 10px;
    }
    
    .card {
        margin-bottom: 15px;
    }
    
    .table-responsive {
        font-size: 14px;
    }
    
    .modal-dialog {
        margin: 10px;
    }
}

/* Form styles */
.form-control:focus, .form-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.25);
}

.required::after {
    content: " *";
    color: #dc3545;
}

.input-group-text {
    background-color: #f8f9fa;
    border-color: #dee2e6;
}
</style>

<!-- MAIN CONTENT WRAPPER - This will shift when sidebar collapses -->
<div class="main-content-wrapper" id="mainContent">
    <div class="container-fluid">
        <h3 class="text-success mb-4">
            <i class="fas fa-capsules"></i> Products Inventory
            <?php if($user_role === 'admin'): ?>
            <small class="text-muted">
                <?= htmlspecialchars($selected_shop_name) ?>
            </small>
            <?php endif; ?>
        </h3>

        <!-- Summary Cards -->
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="card bg-light">
                    <div class="card-body p-2 text-center">
                        <h6 class="card-title mb-1">Total</h6>
                        <h4 class="mb-0"><?= $total_products ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-success text-white">
                    <div class="card-body p-2 text-center">
                        <h6 class="card-title mb-1">Active</h6>
                        <h4 class="mb-0"><?= $active_products ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-secondary text-white">
                    <div class="card-body p-2 text-center">
                        <h6 class="card-title mb-1">Inactive</h6>
                        <h4 class="mb-0"><?= $inactive_products ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card <?= $low_stock_count > 0 ? 'bg-warning text-white' : 'bg-light' ?>">
                    <div class="card-body p-2 text-center">
                        <h6 class="card-title mb-1">Low Stock</h6>
                        <h4 class="mb-0"><?= $low_stock_count ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card <?= $zero_stock_count > 0 ? 'bg-danger text-white' : 'bg-light' ?>">
                    <div class="card-body p-2 text-center">
                        <h6 class="card-title mb-1">Out of Stock</h6>
                        <h4 class="mb-0"><?= $zero_stock_count ?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-info text-white">
                    <div class="card-body p-2 text-center">
                        <h6 class="card-title mb-1">Stock Value</h6>
                        <h4 class="mb-0"><?= number_format($total_stock_value, 2) ?></h4>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters Card -->
        <div class="card p-3 mb-3">
            <form method="GET" id="filterForm" class="row g-3 align-items-end">
                <?php if($user_role === 'admin'): ?>
                <div class="col-md-3">
                    <label class="form-label">Shop</label>
                    <select name="shop_id" class="form-control" onchange="this.form.submit()">
                        <!-- First option: All Shops -->
                        <option value="0" <?= $selected_shop == 0 ? 'selected' : '' ?>>?? All Shops</option>
                        
                        <!-- All shops from database -->
                        <?php foreach($all_shops as $shop): ?>
                        <option value="<?= $shop['id'] ?>" 
                                <?= $selected_shop == $shop['id'] ? 'selected' : '' ?>
                                <?= $shop['id'] == $shop_id ? 'class="fw-bold text-success"' : '' ?>>
                            <?= htmlspecialchars($shop['name']) ?>
                            <?= $shop['id'] == $shop_id ? ' (My Shop)' : '' ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                
                <div class="col-md-3">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-control" onchange="this.form.submit()">
                        <option value="active" <?= $filter_status == 'active' ? 'selected' : '' ?>>Active Only</option>
                        <option value="inactive" <?= $filter_status == 'inactive' ? 'selected' : '' ?>>Inactive Only</option>
                        <option value="all" <?= $filter_status == 'all' ? 'selected' : '' ?>>All Products</option>
                    </select>
                </div>
                
                <div class="col-md-4">
                    <label class="form-label">Search</label>
                    <div class="input-group">
                        <input type="text" name="search" class="form-control" placeholder="Search by SKU, Name, Category..." 
                               value="<?= htmlspecialchars($search_term) ?>">
                        <button class="btn btn-primary" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                        <?php if(!empty($search_term)): ?>
                        <a href="?" class="btn btn-outline-secondary">
                            <i class="fas fa-times"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="col-md-2">
                    <div class="d-grid gap-2">
                        <a href="add_product.php" class="btn btn-success">
                            <i class="fas fa-plus"></i> Add Product
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Products Table -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="productsTable">
                        <thead class="thead-dark">
                            <tr>
                                <th>Status</th>
                                <th>SKU</th>
                                <th>Product Name</th>
                                <th>Category</th>
                                <th class="text-center">Current Stock</th>
                                <th class="text-center">Batches</th>
                                <th class="text-right">Buying Price</th>
                                <th class="text-right">Selling Price</th>
                                <th class="text-center">VAT %</th>
                                <th class="text-center">Expiry Alert</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($products)): ?>
                            <tr>
                                <td colspan="11" class="text-center text-muted py-4">
                                    <i class="fas fa-box-open fa-2x mb-2"></i><br>
                                    No products found. 
                                    <a href="add_product.php" class="btn btn-sm btn-outline-primary mt-2">
                                        <i class="fas fa-plus"></i> Add Your First Product
                                    </a>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($products as $row): 
                                // Determine stock status
                                $stock_qty = $row['current_stock'];
                                $is_active = $row['is_active'] == 1;
                                
                                if (!$is_active) {
                                    $status_class = 'bg-secondary';
                                    $status_icon = '<i class="fas fa-ban"></i>';
                                    $row_class = 'table-secondary';
                                } elseif ($stock_qty <= 0) {
                                    $status_class = 'bg-danger text-white';
                                    $status_icon = '<i class="fas fa-times-circle"></i>';
                                    $row_class = 'table-danger';
                                } elseif ($stock_qty <= 20) {
                                    $status_class = 'bg-warning';
                                    $status_icon = '<i class="fas fa-exclamation-triangle"></i>';
                                    $row_class = 'table-warning';
                                } else {
                                    $status_class = 'bg-success text-white';
                                    $status_icon = '<i class="fas fa-check-circle"></i>';
                                    $row_class = '';
                                }
                                
                                // Check expiry
                                $expiry_warning = '';
                                if ($row['earliest_expiry'] && $is_active) {
                                    $days_to_expiry = floor((strtotime($row['earliest_expiry']) - time()) / (60 * 60 * 24));
                                    if ($days_to_expiry < 0) {
                                        $expiry_warning = '<span class="badge badge-danger">Expired</span>';
                                    } elseif ($days_to_expiry <= 30) {
                                        $expiry_warning = '<span class="badge badge-warning">' . $days_to_expiry . 'd</span>';
                                    } elseif ($days_to_expiry <= 90) {
                                        $expiry_warning = '<span class="badge badge-info">' . $days_to_expiry . 'd</span>';
                                    }
                                }
                            ?>
                            <tr id="row-<?= $row['id'] ?>" class="<?= $row_class ?>">
                                <td>
                                    <span class="badge <?= $status_class ?> p-2">
                                        <?= $status_icon ?>
                                        <?= $is_active ? 'Active' : 'Inactive' ?>
                                    </span>
                                </td>
                                <td>
                                    <strong><?= htmlspecialchars($row['sku'] ?? 'N/A') ?></strong>
                                    <br><small class="text-muted">ID: <?= $row['id'] ?></small>
                                </td>
                                <td>
                                    <strong><?= htmlspecialchars($row['name']) ?></strong>
                                    <?php if(!empty($row['generic_name'])): ?>
                                    <br><small class="text-muted"><?= htmlspecialchars($row['generic_name']) ?></small>
                                    <?php endif; ?>
                                    <br><small class="text-muted"><?= htmlspecialchars($row['unit']) ?></small>
                                </td>
                                <td>
                                    <span class="badge badge-secondary"><?= htmlspecialchars($row['category'] ?? 'Uncategorized') ?></span>
                                </td>
                                <td class="text-center">
                                    <span class="badge <?= $is_active ? $status_class : 'bg-light text-dark' ?> p-2">
                                        <?php if($is_active): ?>
                                            <?= $status_icon ?> <?= $stock_qty ?>
                                        <?php else: ?>
                                            <i class="fas fa-ban"></i> <?= $stock_qty ?>
                                        <?php endif; ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <?php if ($row['batch_count'] > 0): ?>
                                    <button class="btn btn-sm btn-outline-info view-batches-btn" 
                                            data-product-id="<?= $row['id'] ?>"
                                            data-product-name="<?= htmlspecialchars($row['name']) ?>">
                                        <i class="fas fa-boxes"></i> <?= $row['batch_count'] ?>
                                    </button>
                                    <?php else: ?>
                                    <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-right"><?= number_format($row['buying_price'], 2) ?></td>
                                <td class="text-right">
                                    <strong><?= number_format($row['selling_price'], 2) ?></strong>
                                </td>
                                <td class="text-center"><?= $row['vat_percent'] ?>%</td>
                                <td class="text-center"><?= $expiry_warning ?></td>
                                <td class="text-center">
                                
                                    <div class="btn-group btn-group-sm" role="group">
                                        <!-- View Button - Now opens modal -->
                                        <button class="btn btn-info view-product-btn" 
                                                data-product-id="<?= $row['id'] ?>"
                                                title="View Product Details">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        
                                        <!-- Add New Batch Button -->
                                        <button class="btn btn-success add-batch-btn" 
                                                data-product-id="<?= $row['id'] ?>"
                                                data-product-name="<?= htmlspecialchars($row['name']) ?>"
                                                data-product-sku="<?= htmlspecialchars($row['sku']) ?>"
                                                title="Add New Batch">
                                            <i class="fas fa-plus"></i>
                                        </button>
                                        
                                        <!-- Delete/Restore Button -->
                                        <?php if($is_active): ?>
                                        <?php if($_SESSION['user']['role']=='admin'){ ?>
                                        <button class="btn btn-danger delete-product-btn" 
                                                data-product-id="<?= $row['id'] ?>"
                                                data-product-name="<?= htmlspecialchars($row['name']) ?>"
                                                title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        <?php }
										else
										{
											echo"";
											} ?>
                                        <?php else: ?>
                                        <button class="btn btn-warning restore-product-btn" 
                                                data-product-id="<?= $row['id'] ?>"
                                                data-product-name="<?= htmlspecialchars($row['name']) ?>"
                                                title="Restore">
                                            <i class="fas fa-undo"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View Product Details Modal -->
<div class="modal fade" id="viewProductModal" tabindex="-1" role="dialog" aria-labelledby="viewProductModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewProductModalLabel">
                    <i class="fas fa-info-circle"></i> Product Details
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="viewProductModalBody">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                    <p class="mt-3">Loading product details...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <?php if($_SESSION['user']['role']=='admin'){ ?>
                <a href="#" class="btn btn-primary" id="editProductBtn" style="display: none;">
                    <i class="fas fa-edit"></i> Edit Product
                </a>
                <?php 
				}
				else
				{
				echo"";	
				}
				?>
            </div>
        </div>
    </div>
</div>

<!-- Add New Batch Modal -->
<div class="modal fade" id="addBatchModal" tabindex="-1" role="dialog" aria-labelledby="addBatchModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addBatchModalLabel">
                    <i class="fas fa-plus-circle"></i> Add New Batch
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addBatchForm">
                    <input type="hidden" id="batch_product_id" name="product_id" value="">
                    
                    <!-- Product Info -->
                    <div class="card mb-3 bg-light">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group mb-2">
                                        <label class="text-muted mb-1">Product</label>
                                        <h5 id="batch_product_name" class="mb-0 text-primary">Loading product...</h5>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group mb-2">
                                        <label class="text-muted mb-1">SKU</label>
                                        <h6 id="batch_product_sku" class="mb-0">Loading...</h6>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Batch Details -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="batch_no" class="required">Batch Number</label>
                                <input type="text" class="form-control" id="batch_no" name="batch_no" 
                                       placeholder="Enter batch number" required>
                                <small class="form-text text-muted">Unique identifier for this batch</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="expiry_date" class="required">Expiry Date</label>
                                <input type="date" class="form-control" id="expiry_date" name="expiry_date" required>
                                <small class="form-text text-muted">When this batch expires</small>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="supplier_id" class="required">Supplier</label>
                                <select class="form-control" id="supplier_id" name="supplier_id" required>
                                    <option value="">Select Supplier</option>
                                    <?php foreach($suppliers as $supplier): ?>
                                    <option value="<?= $supplier['id'] ?>"><?= htmlspecialchars($supplier['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="quantity" class="required">Quantity</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="quantity" name="quantity" 
                                           min="1" value="1" required>
                                    <div class="input-group-append">
                                        <span class="input-group-text">units</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="cost_price" class="required">Cost Price (per unit)</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">TSh</span>
                                    </div>
                                    <input type="number" class="form-control" id="cost_price" name="cost_price" 
                                           min="0.01" step="0.01" placeholder="0.00" required>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="sell_price" class="required">Selling Price (per unit)</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">TSh</span>
                                    </div>
                                    <input type="number" class="form-control" id="sell_price" name="sell_price" 
                                           min="0.01" step="0.01" placeholder="0.00" required>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="notes">Notes (Optional)</label>
                        <textarea class="form-control" id="notes" name="notes" rows="2" 
                                  placeholder="Any additional information about this batch"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveBatchBtn">
                    <i class="fas fa-save"></i> Save Batch
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Batch Details Modal -->
<div class="modal fade" id="batchModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="batchModalTitle">
                    <i class="fas fa-boxes"></i> Batch Details
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="batchModalBody">
                <div class="text-center py-4">
                    <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
                    <p class="mt-2">Loading batch details...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-info" id="viewBatchHistoryBtn" style="display: none;">
                    <i class="fas fa-history"></i> View Batch History
                </button>
                <button type="button" class="btn btn-primary" id="viewBatchDetailsBtn" style="display: none;">
                    <i class="fas fa-info-circle"></i> View Batch Details
                </button>
            </div>
        </div>
    </div>
</div>

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    console.log("? Document ready - Checking dependencies...");
    
    // Debug: Check if required libraries are loaded
    console.log("jQuery loaded:", typeof $ !== 'undefined');
    console.log("Bootstrap modal loaded:", typeof $.fn.modal !== 'undefined');
    console.log("SweetAlert loaded:", typeof Swal !== 'undefined');
    
    // Initialize tooltips
    $('[title]').tooltip();
    console.log("? Tooltips initialized");
    
    // Global variables for batch history
    let currentBatchId = null;
    let currentProductId = null;
    let batchDetailsContent = null;
    
    // Set expiry date to 1 year from today by default
    const oneYearFromNow = new Date();
    oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
    const formattedDate = oneYearFromNow.toISOString().split('T')[0];
    $('#expiry_date').val(formattedDate);
    
    // View Product button click
    $(document).on('click', '.view-product-btn', function(e) {
        e.preventDefault();
        console.log("??? View Product button clicked!");
        
        const productId = $(this).data('product-id');
        
        if (!productId) {
            console.error("? No product ID found!");
            return;
        }
        
        // Show loading
        $('#viewProductModalBody').html(`
            <div class="text-center py-5">
                <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
                <p class="mt-3">Loading product details...</p>
            </div>
        `);
        
        // Show modal
        $('#viewProductModal').modal('show');
        console.log("? View Product modal should be visible now");
        
        // Load product details
        $.ajax({
            url: 'ajax/get_product_details.php',
            type: 'GET',
            data: { 
                product_id: productId,
                _t: new Date().getTime()
            },
            success: function(response) {
                console.log("? Product details loaded successfully");
                $('#viewProductModalBody').html(response);
                
                // Show edit button
                $('#editProductBtn').attr('href', `edit_product.php?id=${productId}`).show();
            },
            error: function(xhr, status, error) {
                console.error("? AJAX Error:", {
                    status: status,
                    error: error,
                    statusCode: xhr.status
                });
                
                $('#viewProductModalBody').html(`
                    <div class="alert alert-danger">
                        <h5><i class="fas fa-exclamation-triangle"></i> Error Loading Product Details</h5>
                        <p>Failed to load product information.</p>
                        <button class="btn btn-sm btn-primary mt-2" onclick="location.reload()">
                            <i class="fas fa-redo"></i> Reload Page
                        </button>
                    </div>
                `);
            }
        });
    });
    
    // Add New Batch button click (from main table)
    $(document).on('click', '.add-batch-btn', function(e) {
        e.preventDefault();
        console.log("? Add Batch button clicked!");
        
        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        const productSku = $(this).data('product-sku');
        
        console.log(`Product ID: ${productId}, Name: ${productName}, SKU: ${productSku}`);
        
        if (!productId) {
            console.error("? No product ID found!");
            showErrorNotification('Product ID missing. Please refresh the page and try again.');
            return;
        }
        
        // DEBUG: Check if form elements exist
        console.log('Checking form elements:');
        console.log('batch_product_id element:', $('#batch_product_id').length > 0);
        console.log('batch_product_name element:', $('#batch_product_name').length > 0);
        
        // Set form values
        $('#batch_product_id').val(productId);
        $('#batch_product_name').text(productName);
        $('#batch_product_sku').text(productSku);
        
        // Reset form
        $('#addBatchForm')[0].reset();
        
        // Set default expiry date
        const oneYearFromNow = new Date();
        oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
        const formattedDate = oneYearFromNow.toISOString().split('T')[0];
        $('#expiry_date').val(formattedDate);
        
        // Show modal
        $('#addBatchModal').modal('show');
        
        // DEBUG: Check values after setting
        console.log('Form values after setting:');
        console.log('Product ID in form:', $('#batch_product_id').val());
        console.log('Product name in form:', $('#batch_product_name').text());
    });
    
    // Save Batch button click
    $('#saveBatchBtn').click(function() {
        console.log("?? Save Batch button clicked");
        
        // Validate form
        const form = $('#addBatchForm')[0];
        if (!form.checkValidity()) {
            // Show validation messages
            form.reportValidity();
            return;
        }
        
        // Get form data
        const formData = {
            product_id: $('#batch_product_id').val(),
            batch_no: $('#batch_no').val(),
            expiry_date: $('#expiry_date').val(),
            supplier_id: $('#supplier_id').val(),
            quantity: $('#quantity').val(),
            cost_price: $('#cost_price').val(),
            sell_price: $('#sell_price').val(),
            notes: $('#notes').val(),
            action: 'add_batch'
        };
        
        console.log("?? Form data to save:", formData);
        
        // Validate product_id
        if (!formData.product_id) {
            Swal.fire({
                title: 'Error!',
                text: 'Product ID is missing. Please close the modal and try again.',
                icon: 'error',
                confirmButtonText: 'OK'
            });
            return;
        }
        
        // Show loading
        Swal.fire({
            title: 'Adding Batch...',
            text: 'Please wait while we save the batch details',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Send AJAX request
        $.ajax({
            url: 'ajax/save_batch.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                Swal.close();
                console.log("? AJAX response:", response);
                
                if (response.status === 'success') {
                    // Show success message
                    Swal.fire({
                        title: 'Success!',
                        text: response.message,
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        // Close modal
                        $('#addBatchModal').modal('hide');
                        
                        // Reload the page to show updated data
                        location.reload();
                    });
                } else {
                    // Show error message
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'Failed to add batch. Please try again.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.close();
                console.error("? AJAX Error:", {
                    status: status,
                    error: error,
                    statusCode: xhr.status,
                    responseText: xhr.responseText?.substring(0, 200)
                });
                
                Swal.fire({
                    title: 'Error!',
                    html: `
                        <p>Failed to add batch due to server error.</p>
                        <p class="small text-muted">Status: ${xhr.status}</p>
                        <p class="small text-muted">Error: ${error}</p>
                        <p class="small text-muted">Product ID sent: ${formData.product_id || 'NOT SENT'}</p>
                    `,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    });
    
    // View batches button click
    $(document).on('click', '.view-batches-btn', function(e) {
        e.preventDefault();
        console.log("?? View Batches button clicked!");
        
        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        
        console.log(`Product ID: ${productId}, Name: ${productName}`);
        
        if (!productId) {
            console.error("? No product ID found!");
            return;
        }
        
        currentProductId = productId;
        
        // Update modal title
        $('#batchModalTitle').html(`<i class="fas fa-boxes"></i> ${productName} - All Batches`);
        
        // Show loading state
        $('#batchModalBody').html(`
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
                <p class="mt-2">Loading batch details...</p>
                <small class="text-muted">Product ID: ${productId}</small>
            </div>
        `);
        
        // Hide history buttons initially
        $('#viewBatchHistoryBtn').hide();
        $('#viewBatchDetailsBtn').hide();
        
        // Show modal
        $('#batchModal').modal('show');
        console.log("? Batch modal should be visible now");
        
        // Load batch details
        $.ajax({
            url: 'ajax/get_batches.php',
            type: 'GET',
            data: { 
                product_id: productId,
                _t: new Date().getTime()
            },
            success: function(response) {
                console.log("? AJAX success, response length:", response.length);
                $('#batchModalBody').html(response);
            },
            error: function(xhr, status, error) {
                console.error("? AJAX Error:", {
                    status: status,
                    error: error,
                    statusCode: xhr.status,
                    responseText: xhr.responseText?.substring(0, 200)
                });
                
                $('#batchModalBody').html(`
                    <div class="alert alert-danger">
                        <h5><i class="fas fa-exclamation-triangle"></i> Error Loading Batch Details</h5>
                        <p>Failed to load batch information.</p>
                        <hr>
                        <div class="text-left">
                            <h6>Troubleshooting:</h6>
                            <ol class="small">
                                <li>Check if file exists: <code>ajax/get_batches.php</code></li>
                                <li>Check browser console for errors</li>
                                <li>Try direct access: <a href="ajax/get_batches.php?product_id=${productId}" target="_blank">Open directly</a></li>
                            </ol>
                        </div>
                        <button class="btn btn-sm btn-primary" onclick="location.reload()">
                            <i class="fas fa-redo"></i> Reload Page
                        </button>
                    </div>
                `);
            }
        });
    });
    
    // Add New Batch from batches list modal
    $(document).on('click', '.add-new-batch-from-list-btn', function(e) {
        e.preventDefault();
        console.log("?? Add New Batch from list button clicked!");
        
        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        const productSku = $(this).data('product-sku');
        
        console.log(`Opening add batch for product: ${productId} - ${productName}`);
        
        // Close batches modal
        $('#batchModal').modal('hide');
        
        // Open add batch modal after delay
        setTimeout(function() {
            // Set product info
            $('#batch_product_id').val(productId);
            $('#batch_product_name').text(productName);
            $('#batch_product_sku').text(productSku);
            
            // Reset form
            $('#addBatchForm')[0].reset();
            
            // Set default expiry date (1 year from now)
            const oneYearFromNow = new Date();
            oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
            const formattedDate = oneYearFromNow.toISOString().split('T')[0];
            $('#expiry_date').val(formattedDate);
            
            // Show modal
            $('#addBatchModal').modal('show');
            $('#batch_no').focus();
            
            console.log('Add batch form populated with product:', {
                id: $('#batch_product_id').val(),
                name: $('#batch_product_name').text(),
                sku: $('#batch_product_sku').text()
            });
        }, 300);
    });
    
    // Delete product button click (soft delete)
    $(document).on('click', '.delete-product-btn', function() {
        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        
        Swal.fire({
            title: 'Deactivate Product',
            html: `Are you sure you want to deactivate <strong>${productName}</strong>?<br>
                   <small class="text-muted">This will mark the product as inactive. It can be restored later.</small>`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, deactivate it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Deactivating...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });
                
                $.ajax({
                    url: 'ajax/deactivate_product.php',
                    type: 'POST',
                    data: { id: productId },
                    dataType: 'json',
                    success: function(response) {
                        Swal.close();
                        if (response.status === 'success') {
                            Swal.fire({
                                title: 'Deactivated!',
                                text: response.message,
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error!',
                                text: response.message,
                                icon: 'error'
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        Swal.close();
                        Swal.fire({
                            title: 'Error!',
                            html: 'An error occurred while deactivating the product.',
                            icon: 'error'
                        });
                        console.error("AJAX Error:", error);
                    }
                });
            }
        });
    });
    
    // Restore product button click
    $(document).on('click', '.restore-product-btn', function() {
        const productId = $(this).data('product-id');
        const productName = $(this).data('product-name');
        
        Swal.fire({
            title: 'Restore Product',
            html: `Are you sure you want to restore <strong>${productName}</strong>?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, restore it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Restoring...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });
                
                $.ajax({
                    url: 'ajax/restore_product.php',
                    type: 'POST',
                    data: { id: productId },
                    dataType: 'json',
                    success: function(response) {
                        Swal.close();
                        if (response.status === 'success') {
                            Swal.fire({
                                title: 'Restored!',
                                text: response.message,
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error!',
                                text: response.message,
                                icon: 'error'
                            });
                        }
                    },
                    error: function(xhr) {
                        Swal.close();
                        Swal.fire({
                            title: 'Error!',
                            text: 'Failed to restore product.',
                            icon: 'error'
                        });
                    }
                });
            }
        });
    });
    
    // Helper function for error notifications
    function showErrorNotification(message, title = 'Error') {
        Swal.fire({
            title: title,
            text: message,
            icon: 'error',
            confirmButtonText: 'OK'
        });
    }
});
</script>