<?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['product_id'] ?? 0;
$product_id = intval($product_id);
$shop_id = $_SESSION['user']['shop_id'];

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

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

// Get suppliers
$suppliers = $pdo->query("SELECT id, name FROM suppliers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Generate invoice number
$invoice_no = 'PUR-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
?>

<div class="container-fluid p-0">
    <div class="card border-0">
        <div class="card-header bg-success text-white">
            <h4 class="mb-0"><i class="fas fa-plus-circle"></i> Add Stock Purchase</h4>
        </div>
        <div class="card-body">
            <!-- Product Info -->
            <div class="alert alert-info">
                <h5><i class="fas fa-capsules"></i> <?= htmlspecialchars($product['name']) ?></h5>
                <div class="row">
                    <div class="col-md-3">
                        <strong>SKU:</strong> <?= htmlspecialchars($product['sku'] ?? 'N/A') ?>
                    </div>
                    <div class="col-md-3">
                        <strong>Current Stock:</strong> 
                        <?php 
                        $stock_sql = "SELECT COALESCE(total_qty, 0) as stock FROM product_stock_view WHERE product_id = ?";
                        $stock_stmt = $pdo->prepare($stock_sql);
                        $stock_stmt->execute([$product_id]);
                        $stock = $stock_stmt->fetch(PDO::FETCH_ASSOC);
                        echo $stock['stock'] ?? 0;
                        ?>
                    </div>
                    <div class="col-md-3">
                        <strong>Buying Price:</strong> <?= number_format($product['buying_price'], 2) ?>
                    </div>
                    <div class="col-md-3">
                        <strong>Selling Price:</strong> <?= number_format($product['selling_price'], 2) ?>
                    </div>
                </div>
            </div>
            
            <!-- Purchase Form -->
            <form id="purchaseForm">
                <input type="hidden" name="product_id" value="<?= $product_id ?>">
                <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
                <input type="hidden" name="created_by" value="<?= $_SESSION['user']['id'] ?>">
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Invoice Number *</label>
                            <input type="text" name="invoice_no" class="form-control" value="<?= $invoice_no ?>" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Purchase Date *</label>
                            <input type="date" name="purchase_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Supplier *</label>
                            <select name="supplier_id" class="form-control" 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>
                
                <!-- Batch Information -->
                <div class="card mt-3">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-box"></i> Batch Details</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Batch Number *</label>
                                    <input type="text" name="batch_no" class="form-control" required 
                                           placeholder="e.g., BATCH-2024-001">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Quantity *</label>
                                    <input type="number" name="qty" class="form-control" min="1" required 
                                           placeholder="Enter quantity">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Cost Price per Unit *</label>
                                    <input type="number" name="cost_price" class="form-control" step="0.01" min="0.01" required 
                                           value="<?= $product['buying_price'] ?>" placeholder="0.00">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Selling Price per Unit *</label>
                                    <input type="number" name="sell_price" class="form-control" step="0.01" min="0.01" required 
                                           value="<?= $product['selling_price'] ?>" placeholder="0.00">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Expiry Date</label>
                                    <input type="date" name="expiry_date" class="form-control" 
                                           min="<?= date('Y-m-d') ?>">
                                </div>
                            </div>
                            <div class="col-md-8">
                                <div class="form-group">
                                    <label>Notes (Optional)</label>
                                    <textarea name="notes" class="form-control" rows="2" 
                                              placeholder="Any additional notes about this purchase..."></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Calculated Total -->
                        <div class="row mt-3">
                            <div class="col-md-12">
                                <div class="alert alert-warning">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <strong>Quantity:</strong> <span id="displayQty">0</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Cost Price:</strong> <span id="displayPrice">0.00</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Total Amount:</strong> TZS <span id="totalAmount">0.00</span>
                                        </div>
                                    </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">
                            <button type="button" class="btn btn-secondary" onclick="Swal.close()">
                                <i class="fas fa-times"></i> Cancel
                            </button>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-save"></i> Save Purchase
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Update display values
$(document).ready(function() {
    $('input[name="qty"], input[name="cost_price"]').on('input', function() {
        const qty = parseInt($('input[name="qty"]').val()) || 0;
        const price = parseFloat($('input[name="cost_price"]').val()) || 0;
        const total = qty * price;
        
        $('#displayQty').text(qty);
        $('#displayPrice').text(price.toFixed(2));
        $('#totalAmount').text(total.toFixed(2));
    });
    
    // Trigger initial calculation
    $('input[name="qty"]').trigger('input');
});
</script>