<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$message = '';

if (!isset($_GET['id'])) {
    header("Location: list_products.php");
    exit;
}

$id = $_GET['id'];

$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    echo "<div class='alert alert-danger'>Product not found.</div>";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sku = trim($_POST['sku']);
    $name = trim($_POST['name']);
    $generic_name = trim($_POST['generic_name']);
    $unit = trim($_POST['unit']);
    $category = trim($_POST['category']);
    $vat_percent = trim($_POST['vat_percent']);

    $stmt = $pdo->prepare("UPDATE products SET sku=?, name=?, generic_name=?, unit=?, category=?, vat_percent=? WHERE id=?");
    $stmt->execute([$sku, $name, $generic_name, $unit, $category, $vat_percent, $id]);
    $message = "<div class='alert alert-success'>Product updated successfully!</div>";

    // Refresh product data
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch();
}
?>

<style>
/* Edit product page specific styles */
.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);
}

.form-control {
    border-radius: 8px;
    padding: 10px 12px;
    border: 1px solid #ddd;
    transition: border 0.3s ease;
}

.form-control:focus {
    border-color: #4c1d95;
    box-shadow: 0 0 0 0.2rem rgba(76, 29, 149, 0.25);
}

.alert {
    border-radius: 10px;
    border: none;
}

.btn-success {
    background: linear-gradient(135deg, #28a745, #20c997);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.btn-secondary {
    background: linear-gradient(135deg, #6c757d, #495057);
    border: none;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-secondary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .main-content-wrapper {
        padding: 15px 10px;
    }
    
    .card {
        margin-bottom: 15px;
    }
    
    .btn {
        width: 100%;
        margin-bottom: 10px;
    }
    
    .d-flex {
        flex-direction: column;
        gap: 10px;
    }
}
</style>

<!-- MAIN CONTENT WRAPPER - This will shift when sidebar collapses -->
<div class="main-content-wrapper" id="mainContent">
    <div class="container-fluid">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div>
                            <h3 class="text-success mb-0">
                                <i class="fas fa-edit"></i> Edit Product
                            </h3>
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb bg-transparent p-0 mt-2">
                                    <li class="breadcrumb-item"><a href="list_products.php">Products</a></li>
                                    <li class="breadcrumb-item"><a href="view_product.php?id=<?= $id ?>"><?= htmlspecialchars($product['name']) ?></a></li>
                                    <li class="breadcrumb-item active">Edit</li>
                                </ol>
                            </nav>
                        </div>
                        <a href="view_product.php?id=<?= $id ?>" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> Back to View
                        </a>
                    </div>

                    <?= $message ?>

                    <form method="POST" action="" id="editProductForm">
                        <div class="form-group mb-3">
                            <label>SKU</label>
                            <input type="text" name="sku" class="form-control" 
                                   value="<?= htmlspecialchars($product['sku']) ?>">
                            <small class="text-muted">Unique product identifier</small>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label>Product Name *</label>
                            <input type="text" name="name" class="form-control" 
                                   value="<?= htmlspecialchars($product['name']) ?>" required>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label>Generic Name</label>
                            <input type="text" name="generic_name" class="form-control" 
                                   value="<?= htmlspecialchars($product['generic_name']) ?>">
                        </div>
                        
                        <div class="form-group mb-3">
                            <label>Unit</label>
                            <select name="unit" class="form-control">
                                <option value="">-- Select Unit --</option>
                                <option value="tablet" <?= $product['unit'] == 'tablet' ? 'selected' : '' ?>>Tablet</option>
                                <option value="capsule" <?= $product['unit'] == 'capsule' ? 'selected' : '' ?>>Capsule</option>
                                <option value="syrup" <?= $product['unit'] == 'syrup' ? 'selected' : '' ?>>Syrup</option>
                                <option value="injection" <?= $product['unit'] == 'injection' ? 'selected' : '' ?>>Injection</option>
                                <option value="cream" <?= $product['unit'] == 'cream' ? 'selected' : '' ?>>Cream</option>
                                <option value="gel" <?= $product['unit'] == 'gel' ? 'selected' : '' ?>>Gel</option>
                                <option value="drops" <?= $product['unit'] == 'drops' ? 'selected' : '' ?>>Drops</option>
                                <option value="bottle" <?= $product['unit'] == 'bottle' ? 'selected' : '' ?>>Bottle</option>
                                <option value="pack" <?= $product['unit'] == 'pack' ? 'selected' : '' ?>>Pack</option>
                                <option value="box" <?= $product['unit'] == 'box' ? 'selected' : '' ?>>Box</option>
                                <?php if (!in_array($product['unit'], ['tablet','capsule','syrup','injection','cream','gel','drops','bottle','pack','box',''])): ?>
                                <option value="<?= htmlspecialchars($product['unit']) ?>" selected>
                                    <?= htmlspecialchars($product['unit']) ?> (Custom)
                                </option>
                                <?php endif; ?>
                            </select>
                            <small class="text-muted">Unit of measurement</small>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label>Category</label>
                            <select name="category" class="form-control">
                                <option value="">-- Select Category --</option>
                                <option value="Anti-pain" <?= $product['category'] == 'Anti-pain' ? 'selected' : '' ?>>Anti-pain</option>
                                <option value="Antibiotic" <?= $product['category'] == 'Antibiotic' ? 'selected' : '' ?>>Antibiotic</option>
                                <option value="Antacid" <?= $product['category'] == 'Antacid' ? 'selected' : '' ?>>Antacid</option>
                                <option value="Antimalarial" <?= $product['category'] == 'Antimalarial' ? 'selected' : '' ?>>Antimalarial</option>
                                <option value="Antihypertensive" <?= $product['category'] == 'Antihypertensive' ? 'selected' : '' ?>>Antihypertensive</option>
                                <option value="Antidiabetic" <?= $product['category'] == 'Antidiabetic' ? 'selected' : '' ?>>Antidiabetic</option>
                                <option value="Cough & Cold" <?= $product['category'] == 'Cough & Cold' ? 'selected' : '' ?>>Cough & Cold</option>
                                <option value="Skin Care" <?= $product['category'] == 'Skin Care' ? 'selected' : '' ?>>Skin Care</option>
                                <option value="First Aid" <?= $product['category'] == 'First Aid' ? 'selected' : '' ?>>First Aid</option>
                                <option value="Supplements" <?= $product['category'] == 'Supplements' ? 'selected' : '' ?>>Supplements</option>
                                <?php if (!in_array($product['category'], ['Anti-pain','Antibiotic','Antacid','Antimalarial','Antihypertensive','Antidiabetic','Cough & Cold','Skin Care','First Aid','Supplements',''])): ?>
                                <option value="<?= htmlspecialchars($product['category']) ?>" selected>
                                    <?= htmlspecialchars($product['category']) ?> (Custom)
                                </option>
                                <?php endif; ?>
                            </select>
                            <small class="text-muted">Product category</small>
                        </div>
                        
                        <div class="form-group mb-4">
                            <label>VAT %</label>
                            <input type="number" step="0.01" min="0" max="100" name="vat_percent" class="form-control" 
                                   value="<?= htmlspecialchars($product['vat_percent']) ?>">
                            <small class="text-muted">Value Added Tax percentage (0-100)</small>
                        </div>
                        
                        <!-- Hidden field for product ID -->
                        <input type="hidden" name="id" value="<?= $id ?>">
                        
                        <div class="alert alert-info mb-4">
                            <small>
                                <i class="fas fa-info-circle"></i> 
                                <strong>Note:</strong> This updates the product information. Stock quantities, pricing, 
                                and batch information are managed separately.
                            </small>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-save"></i> Update Product
                            </button>
                            <a href="list_products.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('editProductForm');
    
    // Prevent duplicate form submission
    let isSubmitting = false;
    
    form.addEventListener('submit', function(e) {
        if (isSubmitting) {
            e.preventDefault();
            return false;
        }
        isSubmitting = true;
        
        // Disable submit button
        const submitBtn = form.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
        
        return true;
    });
    
    // Form validation
    form.addEventListener('input', function() {
        const nameInput = form.querySelector('input[name="name"]');
        const vatInput = form.querySelector('input[name="vat_percent"]');
        
        // Reset any previous error styles
        nameInput.classList.remove('is-invalid');
        vatInput.classList.remove('is-invalid');
        
        // Validate name
        if (nameInput.value.trim().length < 2) {
            nameInput.classList.add('is-invalid');
        }
        
        // Validate VAT
        const vatValue = parseFloat(vatInput.value);
        if (isNaN(vatValue) || vatValue < 0 || vatValue > 100) {
            vatInput.classList.add('is-invalid');
        }
    });
    
    // Custom unit handling
    const unitSelect = form.querySelector('select[name="unit"]');
    const unitContainer = document.createElement('div');
    unitContainer.className = 'mt-2';
    unitContainer.style.display = 'none';
    unitContainer.innerHTML = `
        <label>Custom Unit</label>
        <input type="text" name="custom_unit" class="form-control" placeholder="Enter custom unit">
    `;
    
    unitSelect.parentNode.appendChild(unitContainer);
    
    unitSelect.addEventListener('change', function() {
        if (this.value === '') {
            unitContainer.style.display = 'block';
            unitContainer.querySelector('input').required = true;
        } else {
            unitContainer.style.display = 'none';
            unitContainer.querySelector('input').required = false;
            unitContainer.querySelector('input').value = '';
        }
    });
    
    // Custom category handling
    const categorySelect = form.querySelector('select[name="category"]');
    const categoryContainer = document.createElement('div');
    categoryContainer.className = 'mt-2';
    categoryContainer.style.display = 'none';
    categoryContainer.innerHTML = `
        <label>Custom Category</label>
        <input type="text" name="custom_category" class="form-control" placeholder="Enter custom category">
    `;
    
    categorySelect.parentNode.appendChild(categoryContainer);
    
    categorySelect.addEventListener('change', function() {
        if (this.value === '') {
            categoryContainer.style.display = 'block';
            categoryContainer.querySelector('input').required = true;
        } else {
            categoryContainer.style.display = 'none';
            categoryContainer.querySelector('input').required = false;
            categoryContainer.querySelector('input').value = '';
        }
    });
    
    // Handle custom values on load
    if (unitSelect.value === '' && unitSelect.options[unitSelect.selectedIndex]?.text.includes('Custom')) {
        const customUnit = unitSelect.value;
        unitSelect.value = '';
        unitContainer.style.display = 'block';
        unitContainer.querySelector('input').value = customUnit;
    }
    
    if (categorySelect.value === '' && categorySelect.options[categorySelect.selectedIndex]?.text.includes('Custom')) {
        const customCategory = categorySelect.value;
        categorySelect.value = '';
        categoryContainer.style.display = 'block';
        categoryContainer.querySelector('input').value = customCategory;
    }
});
</script>

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