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

if (!isset($_SESSION['user']['id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

$product_id = $_GET['id'] ?? 0;
$product_id = intval($product_id);
$shop_id = $_SESSION['user']['shop_id'];

// Get product details
$sql = "SELECT * FROM products WHERE id = ? AND shop_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$product_id, $shop_id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Get categories for dropdown
$categories = $pdo->query("SELECT DISTINCT category FROM products WHERE category IS NOT NULL AND category != '' ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);
?>

<div class="container-fluid p-0">
    <div class="card border-0">
        <div class="card-header bg-warning text-white d-flex justify-content-between align-items-center">
            <h4 class="mb-0"><i class="fas fa-edit"></i> Edit Product</h4>
            <button type="button" class="btn btn-sm btn-light" onclick="Swal.close()">
                <i class="fas fa-times"></i> Close
            </button>
        </div>
        <div class="card-body">
            <form id="editProductForm">
                <input type="hidden" name="id" value="<?= $product_id ?>">
                <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
                <input type="hidden" name="action" value="update">
                
                <!-- Product Name Alert -->
                <div class="alert alert-info mb-3">
                    <small><i class="fas fa-info-circle"></i> Editing: <strong><?= htmlspecialchars($product['name']) ?></strong> (ID: <?= $product_id ?>)</small>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Product Name *</label>
                            <input type="text" name="name" class="form-control" 
                                   value="<?= htmlspecialchars($product['name']) ?>" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Generic Name</label>
                            <input type="text" name="generic_name" class="form-control" 
                                   value="<?= htmlspecialchars($product['generic_name'] ?? '') ?>">
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>SKU Code</label>
                            <input type="text" name="sku" class="form-control" 
                                   value="<?= htmlspecialchars($product['sku'] ?? '') ?>">
                            <small class="text-muted">Unique identifier</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Unit *</label>
                            <select name="unit" class="form-control" required>
                                <option value="tablet" <?= $product['unit'] == 'tablet' ? 'selected' : '' ?>>Tablet</option>
                                <option value="capsule" <?= $product['unit'] == 'capsule' ? 'selected' : '' ?>>Capsule</option>
                                <option value="bottle" <?= $product['unit'] == 'bottle' ? 'selected' : '' ?>>Bottle</option>
                                <option value="tube" <?= $product['unit'] == 'tube' ? 'selected' : '' ?>>Tube</option>
                                <option value="sachet" <?= $product['unit'] == 'sachet' ? 'selected' : '' ?>>Sachet</option>
                                <option value="pack" <?= $product['unit'] == 'pack' ? 'selected' : '' ?>>Pack</option>
                                <option value="box" <?= $product['unit'] == 'box' ? 'selected' : '' ?>>Box</option>
                                <option value="vial" <?= $product['unit'] == 'vial' ? 'selected' : '' ?>>Vial</option>
                                <option value="ampoule" <?= $product['unit'] == 'ampoule' ? 'selected' : '' ?>>Ampoule</option>
                                <option value="piece" <?= $product['unit'] == 'piece' ? 'selected' : '' ?>>Piece</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Category</label>
                            <input type="text" name="category" class="form-control" list="categories"
                                   value="<?= htmlspecialchars($product['category'] ?? '') ?>">
                            <datalist id="categories">
                                <?php foreach($categories as $category): ?>
                                <option value="<?= htmlspecialchars($category) ?>">
                                <?php endforeach; ?>
                            </datalist>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>VAT Percentage (%)</label>
                            <input type="number" name="vat_percent" class="form-control" step="0.01" min="0" max="100"
                                   value="<?= $product['vat_percent'] ?>">
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="mb-0">Pricing Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Buying Price *</label>
                                            <input type="number" name="buying_price" class="form-control" step="0.01" min="0.01" required
                                                   value="<?= $product['buying_price'] ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Selling Price *</label>
                                            <input type="number" name="selling_price" class="form-control" step="0.01" min="0.01" required
                                                   value="<?= $product['selling_price'] ?>">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Margin Calculation -->
                                <div class="alert alert-info mt-3" id="marginInfo">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <strong>Margin:</strong> <span id="marginAmount">0.00</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Margin %:</strong> <span id="marginPercent">0%</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Markup %:</strong> <span id="markupPercent">0%</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="mb-0">Status & Control</h5>
                            </div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label>Product Status</label>
                                    <div class="custom-control custom-switch">
                                        <input type="checkbox" class="custom-control-input" id="is_active" name="is_active" value="1"
                                               <?= $product['is_active'] ? 'checked' : '' ?>>
                                        <label class="custom-control-label" for="is_active">
                                            <?= $product['is_active'] ? 'Active' : 'Inactive' ?>
                                        </label>
                                    </div>
                                    <small class="text-muted">Inactive products won't appear in sales</small>
                                </div>
                                
                                <div class="form-group mt-3">
                                    <label>Product Information</label>
                                    <div class="border p-2 bg-light rounded">
                                        <small class="d-block">
                                            <strong>ID:</strong> <?= $product_id ?>
                                        </small>
                                        <small class="d-block">
                                            <strong>Created:</strong> <?= date('M d, Y', strtotime($product['created_at'])) ?>
                                        </small>
                                        <small class="d-block">
                                            <strong>Last Updated:</strong> 
                                            <?= !empty($product['updated_at']) ? date('M d, Y H:i', strtotime($product['updated_at'])) : 'Never' ?>
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Form Actions -->
                <div class="row mt-4">
                    <div class="col-md-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <button type="button" class="btn btn-secondary" onclick="Swal.close()">
                                    <i class="fas fa-times"></i> Cancel
                                </button>
                            </div>
                            <div>
                                <button type="button" class="btn btn-outline-info mr-2" onclick="viewProduct()">
                                    <i class="fas fa-eye"></i> View Product
                                </button>
                                <button type="submit" class="btn btn-warning">
                                    <i class="fas fa-save"></i> Update Product
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Calculate margin
    function calculateMargin() {
        const buying = parseFloat($('input[name="buying_price"]').val()) || 0;
        const selling = parseFloat($('input[name="selling_price"]').val()) || 0;
        
        if (buying > 0 && selling > 0) {
            const margin = selling - buying;
            const marginPercent = buying > 0 ? (margin / buying) * 100 : 0;
            const markupPercent = buying > 0 ? (margin / selling) * 100 : 0;
            
            $('#marginAmount').text(margin.toFixed(2));
            $('#marginPercent').text(marginPercent.toFixed(1) + '%');
            $('#markupPercent').text(markupPercent.toFixed(1) + '%');
        }
    }
    
    // Update margin when prices change
    $('input[name="buying_price"], input[name="selling_price"]').on('input', calculateMargin);
    
    // Trigger initial calculation
    calculateMargin();
    
    // Update switch label
    $('#is_active').change(function() {
        const label = $(this).next('.custom-control-label');
        label.text(this.checked ? 'Active' : 'Inactive');
    });
});

// Function to view product details
function viewProduct() {
    const productId = $('input[name="id"]').val();
    if (productId) {
        Swal.close(); // Close the edit modal
        // Redirect to view_product page
        window.location.href = 'view_product.php?id=' + productId;
    }
}
</script>