<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include config first
require_once __DIR__ . '/../includes/config.php';

// Use the same session system as navbar.php
$user = null;
$auth_token = $_COOKIE['rcp_auth'] ?? null;

if ($auth_token) {
    try {
        require_once __DIR__ . '/../includes/database.php';
        $pdo = Database::getInstance()->getConnection();
        
        $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
        $stmt->execute([$auth_token]);
        $session_data = $stmt->fetchColumn();
        
        if ($session_data) {
            $user = json_decode($session_data, true);
        }
    } catch (Throwable $t) {
        error_log("Session error: " . $t->getMessage());
    }
}

// Check if logged in
if (!$user || !isset($user['user_id'])) {
    header('Location: ' . WEB_BASE . 'pages/login.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Smart Serve Pro - Ingredients Management</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="<?= WEB_BASE ?>assets/css/style.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    body, .card, .card-title, .form-label, .table, .modal-content {
        color: #000000 !important;
    }
    .text-muted {
        color: #6c757d !important;
    }
    .upload-area {
        border: 2px dashed #dee2e6;
        border-radius: 8px;
        padding: 2rem;
        text-align: center;
        transition: all 0.3s ease;
        background: #f8f9fa;
    }
    .upload-area:hover {
        border-color: #28a745;
        background: #e9f7fe;
    }
    .upload-area.dragover {
        border-color: #28a745;
        background: #d1ecf1;
    }
    .csv-template {
        background: #f8f9fa;
        border-left: 4px solid #28a745;
    }
    
    /* Scrollable table container - only the table scrolls, not the whole page */
    .table-container {
        max-height: 500px;
        overflow-y: auto;
        border: 1px solid #dee2e6;
        border-radius: 8px;
    }
    
    /* Make table header sticky */
    .table-container table {
        margin-bottom: 0;
    }
    
    .table-container thead th {
        position: sticky;
        top: 0;
        background: #f8f9fa;
        z-index: 10;
        border-bottom: 2px solid #dee2e6;
    }
    
    /* Ensure table rows have proper spacing */
    .table-container tbody tr:last-child td {
        border-bottom: 1px solid #dee2e6;
    }
    
    /* Smooth scrolling */
    .table-container {
        scroll-behavior: smooth;
    }
    
    /* Custom scrollbar */
    .table-container::-webkit-scrollbar {
        width: 8px;
    }
    
    .table-container::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }
    
    .table-container::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
    }
    
    .table-container::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }
    
    /* Checkbox styling */
    .form-check-input:indeterminate {
        background-color: #0d6efd;
        border-color: #0d6efd;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10h8'/%3e%3c/svg%3e");
    }
    
    /* Bulk delete button animation */
    #bulkDeleteBtn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
    
    /* Responsive table */
    @media (max-width: 768px) {
        .table-container {
            font-size: 0.875rem;
        }
        .table-container th,
        .table-container td {
            padding: 0.5rem;
        }
    }
    
    /* Price comparison styles */
    .price-change {
        font-size: 0.85rem;
        font-weight: 500;
        padding: 2px 8px;
        border-radius: 12px;
        white-space: nowrap;
        display: inline-block;
    }
    
    .price-up {
        color: #dc3545;
        background-color: rgba(220, 53, 69, 0.1);
        border: 1px solid rgba(220, 53, 69, 0.2);
    }
    
    .price-down {
        color: #198754;
        background-color: rgba(25, 135, 84, 0.1);
        border: 1px solid rgba(25, 135, 84, 0.2);
    }
    
    .price-no-change {
        color: #6c757d;
        background-color: rgba(108, 117, 125, 0.1);
        border: 1px solid rgba(108, 117, 125, 0.2);
    }
    
    .price-new {
        color: #0d6efd;
        background-color: rgba(13, 110, 253, 0.1);
        border: 1px solid rgba(13, 110, 253, 0.2);
    }
    
    .old-price {
        text-decoration: line-through;
        color: #6c757d;
        font-size: 0.85rem;
        display: block;
        margin-top: 2px;
    }
    
    .last-updated {
        font-size: 0.85rem;
        color: #6c757d;
    }
    
    .today-badge {
        background-color: #198754;
        color: white;
        font-size: 0.75rem;
        padding: 2px 6px;
        border-radius: 4px;
        display: inline-block;
        margin-top: 4px;
    }
    
    /* Search box styles */
    .search-container {
        position: relative;
    }
    
    .search-container .search-icon {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        z-index: 10;
    }
    
    .search-container .search-input {
        padding-left: 40px;
        padding-right: 40px;
    }
    
    .search-container .search-clear {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        color: #6c757d;
        cursor: pointer;
        display: none;
        z-index: 10;
    }
    
    .search-container .search-clear:hover {
        color: #dc3545;
    }
    
    .no-results {
        text-align: center;
        padding: 2rem !important;
        color: #6c757d;
    }
    
    /* Loading indicator for search */
    .search-loading {
        position: absolute;
        right: 40px;
        top: 50%;
        transform: translateY(-50%);
        display: none;
    }
    
    /* Table column widths */
    .col-name { width: 20%; }
    .col-unit { width: 8%; }
    .col-current-price { width: 12%; }
    .col-previous-price { width: 12%; }
    .col-price-change { width: 12%; }
    .col-last-updated { width: 12%; }
    .col-category { width: 12%; }
    .col-supplier { width: 12%; }
    .col-actions { width: 12%; }
  </style>
</head>
<body class="bg-white">
<?php include __DIR__ . '/../includes/navbar.php'; ?>

<main class="rcp-main">
  <div class="container-fluid py-4">
    <div class="row mb-4">
      <div class="col-12">
        <h1 class="h3 mb-1 text-dark">Ingredients Management</h1>
        <p class="text-muted">Manage your ingredients, pricing, and supplier information</p>
      </div>
    </div>

    <!-- Bulk Upload Section -->
    <div class="row mb-4">
      <div class="col-12">
        <div class="card border-0 shadow-sm bg-white">
          <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0 text-dark">
              <i class="fas fa-file-csv me-2"></i>Bulk Ingredients Upload
            </h5>
            <button class="btn btn-sm btn-outline-success" onclick="downloadTemplate()">
              <i class="fas fa-download me-1"></i>Download CSV Template
            </button>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-6">
                <div class="upload-area" id="uploadArea">
                  <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                  <h5 class="text-dark">Drag & Drop CSV File</h5>
                  <p class="text-muted">or click to browse</p>
                  <input type="file" id="csvFile" accept=".csv" class="d-none">
                  <button type="button" class="btn btn-success mt-2" onclick="document.getElementById('csvFile').click()">
                    <i class="fas fa-folder-open me-2"></i>Choose File
                  </button>
                  <div class="mt-3" id="fileInfo"></div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="csv-template p-3">
                  <h6 class="text-dark"><i class="fas fa-info-circle me-2"></i>CSV Format Requirements</h6>
                  <small class="text-muted">
                    <ul class="mb-2">
                      <li>File must be in CSV format</li>
                      <li>Include header row with: name,unit,price,category,supplier_info</li>
                      <li>Existing ingredients with same name will be updated</li>
                      <li>Price should be in decimal format (e.g., 15.99)</li>
                      <li>Category and supplier info are optional</li>
                    </ul>
                  </small>
                  <button type="button" class="btn btn-sm btn-outline-info" onclick="previewTemplate()">
                    <i class="fas fa-eye me-1"></i>Preview Template
                  </button>
                </div>
                
                <div class="mt-3">
                  <button type="button" class="btn btn-success w-100" id="uploadBtn" onclick="uploadCSV()" disabled>
                    <i class="fas fa-upload me-2"></i>Upload Ingredients
                  </button>
                  <div class="progress mt-2 d-none" id="uploadProgress">
                    <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                  </div>
                </div>
              </div>
            </div>
            
            <div id="uploadResults" class="mt-3 d-none">
              <!-- Results will be displayed here -->
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Ingredient Section -->
    <div class="row mb-4">
      <div class="col-12">
        <h4 class="mb-3 text-dark"><i class="fas fa-carrot me-2"></i>Add New Ingredient</h4>
      </div>
    </div>
    
    <div class="row g-4">
      <!-- Add Ingredient Card -->
      <div class="col-lg-4">
        <div class="card border-0 shadow-sm bg-white">
          <div class="card-header bg-white border-bottom">
            <h5 class="card-title mb-0 text-dark">Add Single Ingredient</h5>
          </div>
          <div class="card-body">
            <form id="ingredientForm">
              <div class="mb-3">
                <label for="ingredientName" class="form-label text-dark">Ingredient Name *</label>
                <input type="text" class="form-control" id="ingredientName" name="name" required>
              </div>
              
              <div class="mb-3">
                <label for="ingredientUnit" class="form-label text-dark">Unit *</label>
                <input type="text" class="form-control" id="ingredientUnit" name="unit" required 
                       placeholder="e.g., kg, g, ml, L, piece">
              </div>
              
              <div class="mb-3">
                <label for="ingredientPrice" class="form-label text-dark">Price *</label>
                <div class="input-group">
                  <span class="input-group-text">R</span>
                  <input type="number" class="form-control" id="ingredientPrice" name="price" 
                         step="0.01" min="0" required placeholder="0.00">
                </div>
              </div>
              
              <div class="mb-3">
                <label for="ingredientCategory" class="form-label text-dark">Category</label>
                <input type="text" class="form-control" id="ingredientCategory" name="category" 
                       placeholder="e.g., Vegetables, Meat, Dairy">
              </div>
              
              <div class="mb-3">
                <label for="ingredientSupplier" class="form-label text-dark">Supplier Information</label>
                <input type="text" class="form-control" id="ingredientSupplier" name="supplier_info" 
                       placeholder="e.g., Supplier name, contact details">
              </div>
              
              <button type="submit" class="btn btn-success w-100">
                <i class="fas fa-plus me-2"></i>Add Ingredient
              </button>
            </form>
          </div>
        </div>
      </div>
      
      <!-- Ingredients List Section -->
      <div class="col-lg-8">
        <div class="row mb-3">
          <div class="col-12">
            <h4 class="mb-3 text-dark"><i class="fas fa-list me-2"></i>My Ingredients</h4>
          </div>
        </div>
        
        <!-- Search Bar -->
        <div class="row mb-3">
          <div class="col-md-8">
            <div class="search-container">
              <i class="fas fa-search search-icon"></i>
              <input type="text" 
                     class="form-control search-input" 
                     id="ingredientSearch" 
                     placeholder="Search ingredients by name, category, or supplier..."
                     aria-label="Search ingredients">
              <button type="button" class="search-clear" id="searchClear" title="Clear search">
                <i class="fas fa-times"></i>
              </button>
              <div class="search-loading">
                <div class="spinner-border spinner-border-sm text-primary" role="status">
                  <span class="visually-hidden">Loading...</span>
                </div>
              </div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="d-flex justify-content-end">
              <button class="btn btn-sm btn-outline-primary me-2" onclick="loadIngredients()" title="Refresh list">
                <i class="fas fa-sync-alt"></i>
              </button>
              <span class="badge bg-success align-self-center me-2" id="ingredientCount">0 ingredients</span>
              <span class="badge bg-info align-self-center d-none" id="searchResultCount"></span>
            </div>
          </div>
        </div>
        
        <div class="card border-0 shadow-sm bg-white">
          <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0 text-dark">Ingredients List</h5>
            <div>
              <button class="btn btn-sm btn-outline-danger me-2" id="bulkDeleteBtn" onclick="showBulkDeleteModal()" disabled>
                <i class="fas fa-trash me-1"></i>Delete Selected
              </button>
            </div>
          </div>
          <div class="card-body p-0">
            <div class="table-container">
              <table class="table table-hover mb-0">
                <thead class="table-light">
                  <tr>
                    <th width="50" class="text-dark">
                      <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="selectAllCheckbox">
                      </div>
                    </th>
                    <th class="text-dark col-name">NAME</th>
                    <th class="text-dark col-unit">UNIT</th>
                    <th class="text-dark col-current-price">CURRENT PRICE</th>
                    <th class="text-dark col-previous-price">PREVIOUS PRICE</th>
                    <th class="text-dark col-price-change">PRICE CHANGE</th>
                    <th class="text-dark col-last-updated">LAST UPDATED</th>
                    <th class="text-dark col-category">CATEGORY</th>
                    <th class="text-dark col-supplier">SUPPLIER</th>
                    <th width="100" class="text-end text-dark col-actions">ACTIONS</th>
                  </tr>
                </thead>
                <tbody id="ingredientsTable">
                  <tr>
                    <td colspan="10" class="text-center py-4">
                      <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<!-- Edit Ingredient Modal -->
<div class="modal fade" id="editIngredientModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-white">
        <h5 class="modal-title text-dark">Edit Ingredient</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="editIngredientForm">
        <div class="modal-body">
          <input type="hidden" id="editIngredientId" name="id">
          
          <div class="mb-3">
            <label for="editName" class="form-label text-dark">Ingredient Name *</label>
            <input type="text" class="form-control" id="editName" name="name" required>
          </div>
          
          <div class="mb-3">
            <label for="editUnit" class="form-label text-dark">Unit *</label>
            <input type="text" class="form-control" id="editUnit" name="unit" required>
          </div>
          
          <div class="mb-3">
            <label for="editPrice" class="form-label text-dark">Price *</label>
            <div class="input-group">
              <span class="input-group-text">R</span>
              <input type="number" class="form-control" id="editPrice" name="price" step="0.01" min="0" required>
            </div>
          </div>
          
          <div class="mb-3">
            <label for="editCategory" class="form-label text-dark">Category</label>
            <input type="text" class="form-control" id="editCategory" name="category">
          </div>
          
          <div class="mb-3">
            <label for="editSupplier" class="form-label text-dark">Supplier Information</label>
            <input type="text" class="form-control" id="editSupplier" name="supplier_info" 
                   placeholder="e.g., Supplier name, contact details">
          </div>
        </div>
        <div class="modal-footer bg-white">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="saveChangesBtn">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteIngredientModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-white">
        <h5 class="modal-title text-dark">Confirm Delete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>Are you sure you want to delete ingredient: <strong id="deleteIngredientName" class="text-dark">Unknown Ingredient</strong>?</p>
        <p class="text-danger">This action cannot be undone and may affect existing recipes.</p>
      </div>
      <div class="modal-footer bg-white">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="confirmDeleteIngredient">Delete Ingredient</button>
      </div>
    </div>
  </div>
</div>

<!-- Bulk Delete Confirmation Modal -->
<div class="modal fade" id="bulkDeleteModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-white">
        <h5 class="modal-title text-dark">Confirm Bulk Delete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>Are you sure you want to delete <strong id="bulkDeleteCount" class="text-dark">0</strong> selected ingredients?</p>
        <p class="text-danger">
          <i class="fas fa-exclamation-triangle me-1"></i>
          This action cannot be undone and may affect existing recipes.
        </p>
        <div id="bulkDeletePreview" class="mt-3 small text-muted" style="max-height: 150px; overflow-y: auto;">
          <!-- Selected ingredient names will appear here -->
        </div>
      </div>
      <div class="modal-footer bg-white">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="confirmBulkDelete">
          <i class="fas fa-trash me-1"></i>Delete Selected
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Template Preview Modal -->
<div class="modal fade" id="templateModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-white">
        <h5 class="modal-title text-dark">CSV Template Preview</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="table-responsive">
          <table class="table table-bordered">
            <thead class="table-light">
              <tr>
                <th>name</th>
                <th>unit</th>
                <th>price</th>
                <th>category</th>
                <th>supplier_info</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>Tomatoes</td>
                <td>kg</td>
                <td>25.99</td>
                <td>Vegetables</td>
                <td>Fresh Produce Co.</td>
              </tr>
              <tr>
                <td>Chicken Breast</td>
                <td>kg</td>
                <td>89.99</td>
                <td>Meat</td>
                <td>Quality Meats Ltd</td>
              </tr>
              <tr>
                <td>Milk</td>
                <td>L</td>
                <td>18.50</td>
                <td>Dairy</td>
                <td>Dairy Fresh Suppliers</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="alert alert-info">
          <strong>Note:</strong> The first row must contain the header names exactly as shown above.
        </div>
      </div>
      <div class="modal-footer bg-white">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success" onclick="downloadTemplate()">
          <i class="fas fa-download me-2"></i>Download Template
        </button>
      </div>
    </div>
  </div>
</div>

<script>
// Ingredients Management Functionality
let selectedFile = null;
let currentEditIngredientId = null;
let currentDeleteIngredientId = null;
let allIngredients = []; // Store all ingredients for search filtering
let searchTimeout = null;

function setupCSVUpload() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('csvFile');
    
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelect(files[0]);
        }
    });
    
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            handleFileSelect(e.target.files[0]);
        }
    });
}

function handleFileSelect(file) {
    if (file.type !== 'text/csv' && !file.name.endsWith('.csv')) {
        alert('Please select a CSV file.');
        return;
    }
    
    selectedFile = file;
    document.getElementById('fileInfo').innerHTML = `
        <div class="alert alert-success">
            <i class="fas fa-check-circle me-2"></i>
            <strong>File selected:</strong> ${file.name}<br>
            <small>Size: ${(file.size / 1024).toFixed(2)} KB</small>
        </div>
    `;
    document.getElementById('uploadBtn').disabled = false;
}

function downloadTemplate() {
    const csvContent = "name,unit,price,category,supplier_info\n" +
                      "Tomatoes,kg,25.99,Vegetables,Fresh Produce Co.\n" +
                      "Chicken Breast,kg,89.99,Meat,Quality Meats Ltd\n" +
                      "Milk,L,18.50,Dairy,Dairy Fresh Suppliers\n" +
                      "Rice,kg,15.75,Grains,Grains Wholesalers\n" +
                      "Olive Oil,L,45.00,Oils,Import Specialists";
    
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'ingredients_upload_template.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

function previewTemplate() {
    const templateModal = new bootstrap.Modal(document.getElementById('templateModal'));
    templateModal.show();
}

async function uploadCSV() {
    if (!selectedFile) {
        alert('Please select a CSV file first.');
        return;
    }
    
    const uploadBtn = document.getElementById('uploadBtn');
    const progressBar = document.getElementById('uploadProgress');
    const progress = progressBar.querySelector('.progress-bar');
    const resultsDiv = document.getElementById('uploadResults');
    
    uploadBtn.disabled = true;
    uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Uploading...';
    progressBar.classList.remove('d-none');
    progress.style.width = '0%';
    
    const formData = new FormData();
    formData.append('csv_file', selectedFile);
    
    try {
        progress.style.width = '30%';
        
        const response = await fetch('<?= WEB_BASE ?>api/ingredients/bulk_upload.php', {
            method: 'POST',
            body: formData
        });
        
        progress.style.width = '70%';
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const responseText = await response.text();
        console.log('Raw response:', responseText);
        
        let result;
        try {
            result = JSON.parse(responseText);
        } catch (parseError) {
            console.error('JSON parse error:', parseError);
            throw new Error('Invalid response from server.');
        }
        
        progress.style.width = '100%';
        
        if (result.success) {
            resultsDiv.innerHTML = `
                <div class="alert alert-success">
                    <h6><i class="fas fa-check-circle me-2"></i>Bulk Upload Completed</h6>
                    <p><strong>Added:</strong> ${result.data.added_count} new ingredients</p>
                    <p><strong>Updated:</strong> ${result.data.updated_count} existing ingredients</p>
                    ${result.data.errors.length > 0 ? `
                        <p><strong>Errors:</strong> ${result.data.errors.length} rows failed</p>
                        <div class="mt-2">
                            <button class="btn btn-sm btn-outline-danger" type="button" 
                                    onclick="showUploadErrors(${JSON.stringify(result.data.errors).replace(/"/g, '&quot;')})">
                                View Errors
                            </button>
                        </div>
                    ` : ''}
                </div>
            `;
            resultsDiv.classList.remove('d-none');
            
            setTimeout(() => {
                loadIngredients();
            }, 1000);
            
        } else {
            resultsDiv.innerHTML = `
                <div class="alert alert-danger">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>Upload Failed</h6>
                    <p>${result.message}</p>
                </div>
            `;
            resultsDiv.classList.remove('d-none');
        }
        
    } catch (error) {
        console.error('Upload error:', error);
        resultsDiv.innerHTML = `
            <div class="alert alert-danger">
                <h6><i class="fas fa-exclamation-triangle me-2"></i>Upload Error</h6>
                <p>${error.message}</p>
            </div>
        `;
        resultsDiv.classList.remove('d-none');
    } finally {
        uploadBtn.disabled = false;
        uploadBtn.innerHTML = '<i class="fas fa-upload me-2"></i>Upload Ingredients';
        setTimeout(() => {
            progressBar.classList.add('d-none');
        }, 2000);
    }
}

// Bulk Delete Functions
function setupBulkDelete() {
    // Select All Checkbox
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.ingredient-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            updateBulkDeleteButton();
        });
    }
    
    // Individual checkbox change
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('ingredient-checkbox')) {
            updateBulkDeleteButton();
            
            // Update select all checkbox state
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            if (selectAllCheckbox) {
                const checkboxes = document.querySelectorAll('.ingredient-checkbox');
                const allChecked = Array.from(checkboxes).every(cb => cb.checked);
                const someChecked = Array.from(checkboxes).some(cb => cb.checked);
                selectAllCheckbox.checked = allChecked;
                selectAllCheckbox.indeterminate = someChecked && !allChecked;
            }
        }
    });
}

function updateBulkDeleteButton() {
    const selectedCount = getSelectedIngredients().length;
    const bulkDeleteBtn = document.getElementById('bulkDeleteBtn');
    if (bulkDeleteBtn) {
        bulkDeleteBtn.disabled = selectedCount === 0;
        bulkDeleteBtn.innerHTML = `<i class="fas fa-trash me-1"></i>Delete Selected (${selectedCount})`;
    }
}

function getSelectedIngredients() {
    const checkboxes = document.querySelectorAll('.ingredient-checkbox:checked');
    return Array.from(checkboxes).map(checkbox => ({
        id: parseInt(checkbox.value),
        name: checkbox.dataset.name
    }));
}

function showBulkDeleteModal() {
    const selectedIngredients = getSelectedIngredients();
    
    if (selectedIngredients.length === 0) {
        alert('Please select at least one ingredient to delete.');
        return;
    }
    
    document.getElementById('bulkDeleteCount').textContent = selectedIngredients.length;
    
    // Show preview of selected ingredients
    const previewDiv = document.getElementById('bulkDeletePreview');
    let previewHtml = '<strong>Selected ingredients:</strong><br>';
    selectedIngredients.slice(0, 10).forEach(ingredient => {
        previewHtml += `• ${escapeHtml(ingredient.name)}<br>`;
    });
    
    if (selectedIngredients.length > 10) {
        previewHtml += `• ...and ${selectedIngredients.length - 10} more`;
    }
    
    previewDiv.innerHTML = previewHtml;
    
    const bulkDeleteModal = new bootstrap.Modal(document.getElementById('bulkDeleteModal'));
    bulkDeleteModal.show();
}

async function performBulkDelete() {
    const selectedIngredients = getSelectedIngredients();
    const ingredientIds = selectedIngredients.map(ingredient => ingredient.id);
    
    try {
        const response = await fetch('<?= WEB_BASE ?>api/ingredients/bulk_delete.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ ids: ingredientIds })
        });
        
        const result = await response.json();
        
        if (result.success) {
            const bulkDeleteModal = bootstrap.Modal.getInstance(document.getElementById('bulkDeleteModal'));
            bulkDeleteModal.hide();
            
            // Clear all checkboxes
            document.getElementById('selectAllCheckbox').checked = false;
            
            alert(`Successfully deleted ${result.deleted_count} ingredient(s)!`);
            loadIngredients();
        } else {
            alert('Error deleting ingredients: ' + result.message);
        }
    } catch (error) {
        alert('Error deleting ingredients: ' + error.message);
    }
}

// Search Functionality
function setupSearch() {
    const searchInput = document.getElementById('ingredientSearch');
    const searchClear = document.getElementById('searchClear');
    const searchLoading = document.querySelector('.search-loading');
    
    if (!searchInput) return;
    
    // Real-time search with debouncing
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        
        const searchTerm = this.value.trim();
        
        // Show/hide clear button
        searchClear.style.display = searchTerm ? 'block' : 'none';
        
        if (searchTerm.length === 0) {
            displayIngredients(allIngredients);
            document.getElementById('searchResultCount').classList.add('d-none');
            return;
        }
        
        // Show loading indicator
        searchLoading.style.display = 'block';
        
        searchTimeout = setTimeout(() => {
            performSearch(searchTerm);
            searchLoading.style.display = 'none';
        }, 300); // 300ms delay for better UX
    });
    
    // Clear search
    searchClear.addEventListener('click', function() {
        searchInput.value = '';
        searchClear.style.display = 'none';
        searchInput.focus();
        displayIngredients(allIngredients);
        document.getElementById('searchResultCount').classList.add('d-none');
    });
    
    // Keyboard shortcuts
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            this.value = '';
            searchClear.style.display = 'none';
            displayIngredients(allIngredients);
            document.getElementById('searchResultCount').classList.add('d-none');
        }
    });
}

function performSearch(searchTerm) {
    const normalizedSearch = searchTerm.toLowerCase();
    
    const filteredIngredients = allIngredients.filter(ingredient => {
        return ingredient.name.toLowerCase().includes(normalizedSearch) ||
               (ingredient.category && ingredient.category.toLowerCase().includes(normalizedSearch)) ||
               (ingredient.supplier_info && ingredient.supplier_info.toLowerCase().includes(normalizedSearch));
    });
    
    displayIngredients(filteredIngredients);
    
    // Update search result count
    const resultCount = document.getElementById('searchResultCount');
    resultCount.textContent = `${filteredIngredients.length} result${filteredIngredients.length !== 1 ? 's' : ''}`;
    resultCount.classList.remove('d-none');
}

// Price comparison functions
function calculatePriceChange(oldPrice, newPrice) {
    if (!oldPrice || oldPrice === 0) return null;
    
    const change = ((newPrice - oldPrice) / oldPrice) * 100;
    return parseFloat(change.toFixed(1));
}

function getPriceChangeClass(change, hasOldPrice) {
    if (!hasOldPrice) return 'price-new';
    if (change === null || change === 0) return 'price-no-change';
    if (change > 0) return 'price-up';
    if (change < 0) return 'price-down';
    return 'price-no-change';
}

function getPriceChangeText(change, hasOldPrice) {
    if (!hasOldPrice) return '—';
    if (change === null || change === 0) return 'No change';
    return change > 0 ? `+${change}%` : `${change}%`;
}

function formatLastUpdated(dateString) {
    if (!dateString) return '—';
    
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now - date;
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    
    if (diffHours < 24) {
        return `<span class="today-badge">Today</span>`;
    } else if (diffDays === 1) {
        return 'Yesterday';
    } else if (diffDays < 7) {
        return `${diffDays} days ago`;
    } else {
        return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    }
}

// Ingredients CRUD Operations
async function loadIngredients() {
    const tbody = document.getElementById('ingredientsTable');
    tbody.innerHTML = `
        <tr>
            <td colspan="10" class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </td>
        </tr>
    `;
    
    try {
        const response = await fetch('<?= WEB_BASE ?>api/ingredients/read.php');
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        console.log('Load ingredients response:', result); // Debug log
        
        if (result.success && result.data) {
            // Ensure data is an array
            const ingredients = Array.isArray(result.data) ? result.data : [result.data];
            allIngredients = ingredients;
            
            displayIngredients(ingredients);
            document.getElementById('ingredientCount').textContent = `${ingredients.length} ingredients`;
            
            // Reset checkboxes
            document.getElementById('selectAllCheckbox').checked = false;
            document.getElementById('selectAllCheckbox').indeterminate = false;
            updateBulkDeleteButton();
        } else {
            console.error('API returned error:', result.message);
            allIngredients = [];
            displayIngredients([]);
            document.getElementById('ingredientCount').textContent = '0 ingredients';
            document.getElementById('bulkDeleteBtn').disabled = true;
        }
    } catch (error) {
        console.error('Load ingredients error:', error);
        tbody.innerHTML = `
            <tr>
                <td colspan="10" class="text-center py-4 text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Error loading ingredients: ${error.message}
                </td>
            </tr>`;
    }
}

function displayIngredients(ingredients) {
    const tbody = document.getElementById('ingredientsTable');
    
    if (ingredients.length === 0) {
        const searchTerm = document.getElementById('ingredientSearch').value.trim();
        if (searchTerm) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="10" class="no-results">
                        <i class="fas fa-search fa-lg mb-2"></i>
                        <h6 class="text-muted">No ingredients found</h6>
                        <p class="small">No results for "${escapeHtml(searchTerm)}"</p>
                        <button class="btn btn-sm btn-outline-primary mt-2" onclick="document.getElementById('ingredientSearch').value='';setupSearch();loadIngredients();">
                            Clear Search
                        </button>
                    </td>
                </tr>`;
        } else {
            tbody.innerHTML = `
                <tr>
                    <td colspan="10" class="text-center py-4 text-muted">
                        <i class="fas fa-carrot me-2"></i>
                        No ingredients found. Add your first ingredient above.
                    </td>
                </tr>`;
        }
        return;
    }
    
    let html = '';
    ingredients.forEach(ingredient => {
        const hasOldPrice = ingredient.previous_price && ingredient.previous_price > 0;
        const priceChange = hasOldPrice ? 
            calculatePriceChange(parseFloat(ingredient.previous_price), parseFloat(ingredient.price)) : 
            null;
        const priceChangeClass = getPriceChangeClass(priceChange, hasOldPrice);
        const priceChangeText = getPriceChangeText(priceChange, hasOldPrice);
        const lastUpdated = ingredient.last_updated_formatted || formatLastUpdated(ingredient.last_updated);
        
        html += `
        <tr>
            <td>
                <div class="form-check">
                    <input class="form-check-input ingredient-checkbox" type="checkbox" value="${ingredient.id}" data-name="${escapeHtml(ingredient.name)}">
                </div>
            </td>
            <td class="text-dark">${escapeHtml(ingredient.name)}</td>
            <td class="text-dark">${escapeHtml(ingredient.unit)}</td>
            <td class="text-dark">
                R ${parseFloat(ingredient.price).toFixed(2)}
            </td>
            <td class="text-dark">
                ${hasOldPrice ? `R ${parseFloat(ingredient.previous_price).toFixed(2)}` : '—'}
            </td>
            <td>
                <span class="price-change ${priceChangeClass}">
                    ${priceChangeText}
                </span>
            </td>
            <td class="last-updated">
                ${lastUpdated}
            </td>
            <td class="text-dark">${escapeHtml(ingredient.category || '—')}</td>
            <td class="text-dark">${escapeHtml(ingredient.supplier_info || '—')}</td>
            <td class="text-end">
                <button class="btn btn-sm btn-outline-primary me-1" onclick="editIngredient(${ingredient.id})" title="Edit Ingredient">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="showDeleteIngredientModal(${ingredient.id}, '${escapeHtml(ingredient.name)}')" title="Delete Ingredient">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>`;
    });
    tbody.innerHTML = html;
    
    updateBulkDeleteButton();
}

function escapeHtml(text) {
    if (text === null || text === undefined) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

async function editIngredient(ingredientId) {
    try {
        // Fetch the specific ingredient
        const response = await fetch(`<?= WEB_BASE ?>api/ingredients/read.php?id=${ingredientId}`);
        const result = await response.json();
        
        console.log('Edit API response:', result); // Debug log
        
        if (result.success && result.data) {
            const ingredient = result.data;
            
            // Populate the edit form
            document.getElementById('editIngredientId').value = ingredient.id;
            document.getElementById('editName').value = ingredient.name;
            document.getElementById('editUnit').value = ingredient.unit;
            document.getElementById('editPrice').value = ingredient.price;
            document.getElementById('editCategory').value = ingredient.category || '';
            document.getElementById('editSupplier').value = ingredient.supplier_info || '';
            
            currentEditIngredientId = ingredientId;
            
            // Show the modal
            const editModal = new bootstrap.Modal(document.getElementById('editIngredientModal'));
            editModal.show();
        } else {
            alert('Error loading ingredient: ' + (result.message || 'Ingredient not found'));
        }
    } catch (error) {
        console.error('Edit ingredient error:', error);
        alert('Error loading ingredient data: ' + error.message);
    }
}

function showDeleteIngredientModal(ingredientId, ingredientName) {
    currentDeleteIngredientId = ingredientId;
    document.getElementById('deleteIngredientName').textContent = ingredientName;
    
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteIngredientModal'));
    deleteModal.show();
}

async function deleteIngredient(ingredientId) {
    try {
        const response = await fetch('<?= WEB_BASE ?>api/ingredients/delete.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: ingredientId })
        });
        
        const result = await response.json();
        
        if (result.success) {
            const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteIngredientModal'));
            deleteModal.hide();
            
            alert('Ingredient deleted successfully!');
            loadIngredients();
        } else {
            alert('Error deleting ingredient: ' + result.message);
        }
    } catch (error) {
        alert('Error deleting ingredient: ' + error.message);
    }
}

function showUploadErrors(errors) {
    if (!errors || errors.length === 0) {
        alert('No errors to display');
        return;
    }
    
    let errorList = 'Upload Errors:\n\n';
    errors.forEach((error, index) => {
        errorList += `${index + 1}. Row ${error.row}: ${error.message}\n`;
    });
    
    alert(errorList);
}

// Form submission handlers
document.addEventListener('DOMContentLoaded', function() {
    setupCSVUpload();
    setupBulkDelete();
    setupSearch();
    loadIngredients();
    
    // Add Ingredient Form
    document.getElementById('ingredientForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const data = Object.fromEntries(formData);
        data.price = parseFloat(data.price);
        
        try {
            const response = await fetch('<?= WEB_BASE ?>api/ingredients/create.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            
            const result = await response.json();
            
            if (result.success) {
                alert('Ingredient added successfully!');
                this.reset();
                loadIngredients();
            } else {
                alert('Error: ' + result.message);
            }
        } catch (error) {
            alert('Error adding ingredient: ' + error.message);
        }
    });
    
    // Edit Ingredient Form - Fixed to prevent transaction error
    document.getElementById('editIngredientForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // Disable the save button to prevent double-clicking
        const saveButton = document.getElementById('saveChangesBtn');
        const originalText = saveButton.innerHTML;
        saveButton.disabled = true;
        saveButton.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
        
        const formData = new FormData(this);
        const data = Object.fromEntries(formData);
        data.price = parseFloat(data.price);
        
        try {
            const response = await fetch('<?= WEB_BASE ?>api/ingredients/update.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            
            const result = await response.json();
            
            if (result.success) {
                const editModal = bootstrap.Modal.getInstance(document.getElementById('editIngredientModal'));
                editModal.hide();
                
                alert('Ingredient updated successfully!');
                loadIngredients();
            } else {
                alert('Error: ' + result.message);
                // Re-enable the button if there's an error
                saveButton.disabled = false;
                saveButton.innerHTML = originalText;
            }
        } catch (error) {
            alert('Error updating ingredient: ' + error.message);
            // Re-enable the button if there's an error
            saveButton.disabled = false;
            saveButton.innerHTML = originalText;
        }
    });
    
    // Delete Confirmation
    document.getElementById('confirmDeleteIngredient').addEventListener('click', function() {
        if (currentDeleteIngredientId) {
            deleteIngredient(currentDeleteIngredientId);
        }
    });
    
    // Bulk Delete Confirmation
    document.getElementById('confirmBulkDelete').addEventListener('click', function() {
        performBulkDelete();
    });
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>