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

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

$user = $_SESSION['user'];
$user_id = $user['id'] ?? 1;
$shop_id = $user['shop_id'] ?? null;

// Debug: Check user data
error_log("User ID: " . $user_id . ", Shop ID: " . $shop_id);

$message = '';

// Load products (only for this shop or all if you prefer)
try {
    $stmt = $pdo->prepare("SELECT id, name, buying_price, selling_price FROM products WHERE shop_id = ? AND is_active = 1 ORDER BY name ASC");
    $stmt->execute([$shop_id]);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $products = [];
    $message = "<div class='alert alert-danger'>Error loading products: " . htmlspecialchars($e->getMessage()) . "</div>";
}

// Load suppliers
try {
    $stmt = $pdo->query("SELECT id, name FROM suppliers ORDER BY name ASC");
    $suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $suppliers = [];
    $message = "<div class='alert alert-danger'>Error loading suppliers.</div>";
}

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id   = intval($_POST['product_id'] ?? 0);
    $batch_no     = trim($_POST['batch_no'] ?? '');
    $qty          = intval($_POST['quantity'] ?? 0);
    $cost_price   = floatval($_POST['buying_price'] ?? 0);
    $sell_price   = floatval($_POST['selling_price'] ?? 0);
    $expiry_date  = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;
    $supplier_id  = !empty($_POST['supplier_id']) ? intval($_POST['supplier_id']) : null;
    $created_by   = $user_id;
    
    // Generate a proper invoice number for tracking
    $invoice_prefix = 'DIRECT-BATCH';
    $date_part = date('Ymd');
    $random_part = str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    $invoice_no = $invoice_prefix . '-' . $date_part . '-' . $random_part;
    $purchase_date = date('Y-m-d');
    
    // Basic validation
    if ($product_id <= 0) {
        $message = "<div class='alert alert-danger'>Please select a product.</div>";
    } elseif ($qty <= 0) {
        $message = "<div class='alert alert-danger'>Quantity must be greater than zero.</div>";
    } elseif ($cost_price < 0 || $sell_price < 0) {
        $message = "<div class='alert alert-danger'>Prices cannot be negative.</div>";
    } elseif (empty($batch_no)) {
        $message = "<div class='alert alert-danger'>Batch number is required.</div>";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Debug log
            error_log("Creating purchase for batch: $batch_no, Invoice: $invoice_no, Qty: $qty");
            
            // 1. Create a purchase record for this batch
            $purchase_sql = "INSERT INTO purchases 
                (supplier_id, invoice_no, purchase_date, total, created_by, shop_id, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, NOW())";
            
            $purchase_total = $qty * $cost_price;
            
            error_log("Purchase total calculated: " . $purchase_total);
            
            $purchase_stmt = $pdo->prepare($purchase_sql);
            $purchase_stmt->execute([
                $supplier_id ?: null,
                $invoice_no,
                $purchase_date,
                $purchase_total,
                $created_by,
                $shop_id
            ]);
            
            $purchase_id = $pdo->lastInsertId();
            
            error_log("Purchase created with ID: " . $purchase_id);
            
            // 2. Create the product batch
            $batch_sql = "INSERT INTO product_batches
                (product_id, batch_no, qty, cost_price, sell_price, expiry_date, supplier_id, 
                 created_by, created_at, updated_by, updated_at, shop_id, is_active)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NOW(), ?, 1)";
            
            $batch_stmt = $pdo->prepare($batch_sql);
            $batch_stmt->execute([
                $product_id,
                $batch_no,
                $qty,
                number_format($cost_price, 2, '.', ''),
                number_format($sell_price, 2, '.', ''),
                $expiry_date,
                $supplier_id,
                $created_by,
                $created_by, // updated_by
                $shop_id
            ]);
            
            $batch_id = $pdo->lastInsertId();
            
            error_log("Batch created with ID: " . $batch_id);
            
            // 3. Create purchase line item
            $purchase_line_sql = "INSERT INTO purchase_lines
                (purchase_id, batch_id, qty, cost_price)
                VALUES (?, ?, ?, ?)";
            
            $purchase_line_stmt = $pdo->prepare($purchase_line_sql);
            $purchase_line_stmt->execute([
                $purchase_id,
                $batch_id,
                $qty,
                $cost_price
            ]);
            
            error_log("Purchase line created for purchase_id: " . $purchase_id . ", batch_id: " . $batch_id);
            
            // 4. Create inventory movement
            $movement_sql = "INSERT INTO inventory_movements 
                (product_id, batch_id, change_qty, movement_type, reference_id, 
                 note, created_by, shop_id, created_at)
                VALUES (?, ?, ?, 'PURCHASE', ?, ?, ?, ?, NOW())";
            
            $movement_note = "Direct batch addition via add_batch.php (Purchase #$purchase_id)";
            
            $movement_stmt = $pdo->prepare($movement_sql);
            $movement_stmt->execute([
                $product_id,
                $batch_id,
                $qty,
                $purchase_id,
                $movement_note,
                $created_by,
                $shop_id
            ]);
            
            error_log("Inventory movement created for batch_id: " . $batch_id);
            
            // 5. Update product default prices
            $update_product_sql = "UPDATE products SET 
                buying_price = ?, 
                selling_price = ? 
                WHERE id = ? AND shop_id = ?";
            
            $update_stmt = $pdo->prepare($update_product_sql);
            $update_stmt->execute([
                number_format($cost_price, 2, '.', ''),
                number_format($sell_price, 2, '.', ''),
                $product_id,
                $shop_id
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            // Get product name for success message
            $product_name = '';
            foreach ($products as $p) {
                if ($p['id'] == $product_id) {
                    $product_name = $p['name'];
                    break;
                }
            }
            
            $message = "<div class='alert alert-success'>
                          <i class='fas fa-check-circle'></i> <strong>Batch added successfully!</strong>
                          <div class='mt-2'>
                            <div><i class='fas fa-box'></i> <strong>Product:</strong> " . htmlspecialchars($product_name) . "</div>
                            <div><i class='fas fa-hashtag'></i> <strong>Batch No:</strong> " . htmlspecialchars($batch_no) . "</div>
                            <div><i class='fas fa-sort-amount-up'></i> <strong>Quantity:</strong> " . number_format($qty) . " units</div>
                            <div><i class='fas fa-file-invoice'></i> <strong>Purchase Record:</strong> #$purchase_id ($invoice_no)</div>
                            <div><i class='fas fa-money-bill-wave'></i> <strong>Total Cost:</strong> TSh " . number_format($purchase_total, 2) . "</div>
                          </div>
                          <div class='mt-3'>
                            <a href='list_purchases.php' class='btn btn-sm btn-outline-primary mr-2'>
                              <i class='fas fa-list'></i> View All Purchases
                            </a>
                            <a href='list_batches.php' class='btn btn-sm btn-outline-info'>
                              <i class='fas fa-boxes'></i> View All Batches
                            </a>
                          </div>
                        </div>";

            // Clear POST values to reset the form
            $_POST = [];
            
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            error_log("Database Error in add_batch.php: " . $e->getMessage());
            error_log("Error trace: " . $e->getTraceAsString());
            $message = "<div class='alert alert-danger'>
                          <i class='fas fa-exclamation-circle'></i> <strong>Error!</strong> " . htmlspecialchars($e->getMessage()) . "
                          <div class='mt-2 small'>
                            <strong>Details:</strong> product_id=$product_id, qty=$qty, shop_id=$shop_id, user_id=$user_id
                          </div>
                        </div>";
        }
    }
}
?>

<style>
    .form-control:focus {
        border-color: #28a745;
        box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
    }
    
    .alert {
        border-radius: 8px;
        border-left: 4px solid;
    }
    
    .alert-success {
        border-left-color: #28a745;
    }
    
    .alert-danger {
        border-left-color: #dc3545;
    }
    
    .alert-warning {
        border-left-color: #ffc107;
    }
    
    .card {
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    
    .btn-success {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        border: none;
        transition: all 0.3s ease;
    }
    
    .btn-success:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
    }
    
    .input-group-text {
        background-color: #f8f9fa;
        border-color: #dee2e6;
    }
    
    .purchase-info {
        background-color: #e8f5e8;
        border-left: 4px solid #28a745;
        padding: 10px;
        border-radius: 4px;
        margin-bottom: 15px;
    }
    
    .purchase-info h6 {
        color: #28a745;
        margin-bottom: 5px;
    }
    
    .success-details {
        background-color: #f8f9fa;
        border-radius: 6px;
        padding: 10px;
        margin-top: 10px;
    }
    
    .success-details div {
        margin-bottom: 5px;
    }
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="text-success font-weight-bold">
                <i class="fas fa-box mr-2"></i> Add New Product Batch
            </h3>
            <p class="text-muted mb-0">Add stock batches with automatic purchase tracking</p>
        </div>
        <div>
            <a href="add_purchase.php" class="btn btn-outline-info mr-2">
                <i class="fas fa-cart-plus mr-2"></i> Add Multi-Item Purchase
            </a>
            <a href="list_batches.php" class="btn btn-outline-primary">
                <i class="fas fa-list mr-2"></i> View All Batches
            </a>
        </div>
    </div>

    <?= $message ?>

    <div class="card">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="fas fa-plus-circle mr-2"></i> Batch Information</h5>
        </div>
        <div class="card-body">
            <div class="purchase-info">
                <h6><i class="fas fa-info-circle mr-2"></i> Automatic Purchase Tracking</h6>
                <p class="mb-0 small">Every batch you add here will automatically create a purchase record. This ensures:</p>
                <ul class="small mb-0">
                    <li>All stock additions are tracked in financial reports</li>
                    <li>Purchase totals are accurate in dashboard statistics</li>
                    <li>Complete audit trail for all inventory movements</li>
                </ul>
            </div>
            
            <form method="POST" action="" id="batchForm">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label class="font-weight-bold">Product <span class="text-danger">*</span></label>
                        <select name="product_id" class="form-control" id="productSelect" required>
                            <option value="">-- Select Product --</option>
                            <?php foreach ($products as $p): ?>
                                <option value="<?= $p['id'] ?>" 
                                    <?= (isset($_POST['product_id']) && $_POST['product_id']==$p['id']) ? 'selected' : '' ?>
                                    data-buying-price="<?= $p['buying_price'] ?>"
                                    data-selling-price="<?= $p['selling_price'] ?? 0 ?>">
                                    <?= htmlspecialchars($p['name']) ?> 
                                    (Cost: <?= number_format($p['buying_price'],2) ?>, 
                                    Sell: <?= number_format($p['selling_price'] ?? 0,2) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="form-text text-muted">Select the product for this batch</small>
                    </div>

                    <div class="form-group col-md-6">
                        <label class="font-weight-bold">Supplier</label>
                        <select name="supplier_id" class="form-control">
                            <option value="">-- Select Supplier (optional) --</option>
                            <?php foreach ($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>" 
                                    <?= (isset($_POST['supplier_id']) && $_POST['supplier_id']==$s['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($s['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="form-text text-muted">Optional: Select the supplier for this batch</small>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label class="font-weight-bold">Batch Number <span class="text-danger">*</span></label>
                        <input type="text" name="batch_no" class="form-control" id="batchNoInput" 
                               value="<?= htmlspecialchars($_POST['batch_no'] ?? '') ?>" 
                               placeholder="e.g., BATCH-2025-001" required>
                        <small class="form-text text-muted">Unique batch identifier</small>
                    </div>

                    <div class="form-group col-md-2">
                        <label class="font-weight-bold">Quantity <span class="text-danger">*</span></label>
                        <input type="number" name="quantity" class="form-control" id="quantityInput" min="1" 
                               value="<?= htmlspecialchars($_POST['quantity'] ?? 1) ?>" required>
                        <small class="form-text text-muted">Number of units</small>
                    </div>

                    <div class="form-group col-md-3">
                        <label class="font-weight-bold">Cost Price <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text">TSh</span>
                            </div>
                            <input type="number" step="0.01" name="buying_price" class="form-control" id="costPriceInput" 
                                   value="<?= htmlspecialchars($_POST['buying_price'] ?? '0.00') ?>" required>
                        </div>
                        <small class="form-text text-muted">Cost price per unit</small>
                    </div>

                    <div class="form-group col-md-3">
                        <label class="font-weight-bold">Selling Price <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text">TSh</span>
                            </div>
                            <input type="number" step="0.01" name="selling_price" class="form-control" id="sellPriceInput" 
                                   value="<?= htmlspecialchars($_POST['selling_price'] ?? '0.00') ?>" required>
                        </div>
                        <small class="form-text text-muted">Selling price per unit</small>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-4">
                        <label class="font-weight-bold">Expiry Date</label>
                        <input type="date" name="expiry_date" class="form-control" id="expiryDateInput"
                               value="<?= htmlspecialchars($_POST['expiry_date'] ?? '') ?>"
                               min="<?= date('Y-m-d') ?>">
                        <small class="form-text text-muted">Optional expiry date</small>
                    </div>

                    <div class="form-group col-md-4 d-flex align-items-end">
                        <div class="w-100">
                            <label class="font-weight-bold">Total Purchase Value</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">TSh</span>
                                </div>
                                <input type="text" class="form-control bg-light" id="totalValue" readonly>
                            </div>
                            <small class="form-text text-muted">Auto-calculated: Quantity × Cost Price</small>
                        </div>
                    </div>

                    <div class="form-group col-md-4 d-flex align-items-end justify-content-end">
                        <button type="reset" class="btn btn-outline-secondary mr-2" id="resetBtn">
                            <i class="fas fa-redo mr-2"></i> Clear Form
                        </button>
                        <button type="submit" class="btn btn-success btn-lg" id="submitBtn">
                            <i class="fas fa-save mr-2"></i> Add Batch & Purchase
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Help Information -->
    <div class="card mt-4">
        <div class="card-header bg-light">
            <h6 class="mb-0"><i class="fas fa-info-circle mr-2"></i> About Purchase Tracking</h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h6><i class="fas fa-database text-primary mr-2"></i> What gets created:</h6>
                    <ul class="small text-muted">
                        <li><strong>Purchase Record:</strong> In <code>purchases</code> table</li>
                        <li><strong>Batch Record:</strong> In <code>product_batches</code> table</li>
                        <li><strong>Purchase Line:</strong> In <code>purchase_lines</code> table</li>
                        <li><strong>Inventory Movement:</strong> In <code>inventory_movements</code> table</li>
                    </ul>
                </div>
                <div class="col-md-6">
                    <h6><i class="fas fa-chart-line text-success mr-2"></i> Impact on Reports:</h6>
                    <ul class="small text-muted">
                        <li>Dashboard purchase statistics updated</li>
                        <li>Financial reports include this purchase</li>
                        <li>Stock levels correctly tracked</li>
                        <li>Profit calculations are accurate</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const productSelect = document.getElementById('productSelect');
    const batchNoInput = document.getElementById('batchNoInput');
    const costPriceInput = document.getElementById('costPriceInput');
    const sellPriceInput = document.getElementById('sellPriceInput');
    const quantityInput = document.getElementById('quantityInput');
    const expiryDateInput = document.getElementById('expiryDateInput');
    const totalValueInput = document.getElementById('totalValue');
    const resetBtn = document.getElementById('resetBtn');
    const submitBtn = document.getElementById('submitBtn');
    const batchForm = document.getElementById('batchForm');

    // Function to calculate total value
    function calculateTotalValue() {
        const qty = parseFloat(quantityInput.value) || 0;
        const cost = parseFloat(costPriceInput.value) || 0;
        const total = qty * cost;
        totalValueInput.value = total.toFixed(2);
    }

    // Auto-fill prices when product is selected
    productSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        if (selectedOption.value) {
            const buyingPrice = selectedOption.getAttribute('data-buying-price') || '0.00';
            const sellingPrice = selectedOption.getAttribute('data-selling-price') || '0.00';
            
            costPriceInput.value = parseFloat(buyingPrice).toFixed(2);
            sellPriceInput.value = parseFloat(sellingPrice).toFixed(2);
            calculateTotalValue();
        }
    });

    // Auto-generate batch number if empty
    batchNoInput.addEventListener('focus', function() {
        if (!this.value.trim()) {
            const today = new Date();
            const dateStr = today.getFullYear() + '-' + 
                           String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                           String(today.getDate()).padStart(2, '0');
            this.value = 'BATCH-' + dateStr + '-001';
        }
    });

    // Set minimum date for expiry date (today)
    expiryDateInput.min = new Date().toISOString().split('T')[0];

    // Calculate total value when quantity or cost changes
    quantityInput.addEventListener('input', calculateTotalValue);
    costPriceInput.addEventListener('input', calculateTotalValue);

    // Auto-calculate selling price based on cost (30% markup)
    costPriceInput.addEventListener('change', function() {
        const cost = parseFloat(this.value) || 0;
        const currentSell = parseFloat(sellPriceInput.value) || 0;
        
        // Only auto-calculate if sell price is empty or zero
        if (!currentSell || currentSell === 0) {
            const markupPrice = cost * 1.3;
            sellPriceInput.value = markupPrice.toFixed(2);
        }
    });

    // Form validation before submit
    batchForm.addEventListener('submit', function(e) {
        let isValid = true;
        let errorMessage = '';

        // Check required fields
        if (!productSelect.value) {
            isValid = false;
            errorMessage += '• Please select a product\n';
            productSelect.classList.add('is-invalid');
        } else {
            productSelect.classList.remove('is-invalid');
        }

        if (!batchNoInput.value.trim()) {
            isValid = false;
            errorMessage += '• Batch number is required\n';
            batchNoInput.classList.add('is-invalid');
        } else {
            batchNoInput.classList.remove('is-invalid');
        }

        if (!quantityInput.value || parseInt(quantityInput.value) <= 0) {
            isValid = false;
            errorMessage += '• Quantity must be greater than zero\n';
            quantityInput.classList.add('is-invalid');
        } else {
            quantityInput.classList.remove('is-invalid');
        }

        if (!costPriceInput.value || parseFloat(costPriceInput.value) < 0) {
            isValid = false;
            errorMessage += '• Cost price cannot be negative\n';
            costPriceInput.classList.add('is-invalid');
        } else {
            costPriceInput.classList.remove('is-invalid');
        }

        if (!sellPriceInput.value || parseFloat(sellPriceInput.value) < 0) {
            isValid = false;
            errorMessage += '• Selling price cannot be negative\n';
            sellPriceInput.classList.add('is-invalid');
        } else {
            sellPriceInput.classList.remove('is-invalid');
        }

        if (!isValid) {
            e.preventDefault();
            alert('Please fix the following errors:\n\n' + errorMessage);
            return false;
        }

        // Show loading state
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Processing...';
    });

    // Reset form
    resetBtn.addEventListener('click', function() {
        productSelect.selectedIndex = 0;
        batchNoInput.value = '';
        quantityInput.value = '1';
        costPriceInput.value = '0.00';
        sellPriceInput.value = '0.00';
        expiryDateInput.value = '';
        totalValueInput.value = '';
        
        // Remove validation styles
        [productSelect, batchNoInput, quantityInput, costPriceInput, sellPriceInput].forEach(el => {
            el.classList.remove('is-invalid');
        });
        
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i> Add Batch & Purchase';
    });

    // Remove invalid class on input
    [productSelect, batchNoInput, quantityInput, costPriceInput, sellPriceInput].forEach(el => {
        el.addEventListener('input', function() {
            this.classList.remove('is-invalid');
        });
    });

    // Initial calculation
    calculateTotalValue();
});
</script>

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