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

// Ensure user and shop session
if (!isset($_SESSION['user']['id'], $_SESSION['user']['shop_id'])) {
    header("Location: ../../auth/login.php");
    exit();
}

$shop_id = $_SESSION['user']['shop_id'];
$user_id = $_SESSION['user']['id'];
$shop_name = $_SESSION['user']['shop_name'] ?? 'Your Shop';

// Validate purchase ID
$purchase_id = intval($_GET['id'] ?? 0);
if ($purchase_id <= 0) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>
                <i class='fas fa-exclamation-triangle'></i> Invalid purchase ID.
            </div>
            <a href='list_purchases.php' class='btn btn-secondary'>Back to Purchases</a>
          </div>";
    require_once '../includes/footer.php';
    exit();
}

// Fetch purchase with supplier info
$stmt = $pdo->prepare("
    SELECT p.*, s.name as supplier_name, s.contact as supplier_contact,
           u.username as created_by_name
    FROM purchases p
    LEFT JOIN suppliers s ON p.supplier_id = s.id
    LEFT JOIN users u ON p.created_by = u.id
    WHERE p.id = ? AND p.shop_id = ?
");
$stmt->execute([$purchase_id, $shop_id]);
$purchase = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$purchase) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>
                <i class='fas fa-exclamation-triangle'></i> Purchase not found or not authorized.
            </div>
            <a href='list_purchases.php' class='btn btn-secondary'>Back to Purchases</a>
          </div>";
    require_once '../includes/footer.php';
    exit();
}

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

// Fetch purchase lines with product and batch info
$lines_stmt = $pdo->prepare("
    SELECT pl.id AS line_id, pl.batch_id, pl.qty, pl.cost_price,
           pb.product_id, pb.batch_no, pb.sell_price, pb.expiry_date,
           p.name AS product_name, p.unit
    FROM purchase_lines pl
    LEFT JOIN product_batches pb ON pl.batch_id = pb.id
    LEFT JOIN products p ON pb.product_id = p.id
    WHERE pl.purchase_id = ?
");
$lines_stmt->execute([$purchase_id]);
$purchase_lines = $lines_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all active products for adding new rows
$products = $pdo->query("SELECT id, name, unit FROM products WHERE is_active = 1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Check if purchase can be edited (not if items have been sold)
$canEdit = true;
foreach ($purchase_lines as $line) {
    $checkStmt = $pdo->prepare("
        SELECT COUNT(*) as sale_count 
        FROM sale_lines 
        WHERE batch_id = ?
    ");
    $checkStmt->execute([$line['batch_id']]);
    $saleData = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($saleData && $saleData['sale_count'] > 0) {
        $canEdit = false;
        break;
    }
}
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-primary">
            <i class="fas fa-edit"></i> Edit Purchase
        </h3>
        <div>
            <span class="badge badge-info">ID: <?= $purchase_id ?></span>
            <span class="badge badge-secondary ml-2">Shop: <?= htmlspecialchars($shop_name) ?></span>
            <?php if (!$canEdit): ?>
                <span class="badge badge-warning ml-2" title="Some items have been sold">
                    <i class="fas fa-exclamation-triangle"></i> Limited Edit
                </span>
            <?php endif; ?>
        </div>
    </div>

    <?php if (!$canEdit): ?>
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle"></i> 
            <strong>Limited Edit Mode:</strong> Some items in this purchase have been sold. 
            You can only edit quantities and prices for unsold items.
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    <?php endif; ?>

    <!-- Toast container -->
    <div id="toastContainer" style="position: fixed; top: 20px; right: 20px; z-index: 1050;"></div>

    <div class="card">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-info-circle"></i> Purchase Information</h5>
        </div>
        <div class="card-body">
            <form id="editPurchaseForm">
                <input type="hidden" name="purchase_id" value="<?= $purchase_id ?>">
                <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
                <input type="hidden" name="updated_by" value="<?= $user_id ?>">

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold">Supplier <span class="text-danger">*</span></label>
                        <select name="supplier_id" class="form-control" required <?= !$canEdit ? 'disabled' : '' ?>>
                            <option value="">-- Select Supplier --</option>
                            <?php foreach ($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>" <?= $s['id'] == $purchase['supplier_id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($s['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (!$canEdit): ?>
                            <input type="hidden" name="supplier_id" value="<?= $purchase['supplier_id'] ?>">
                        <?php endif; ?>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold">Invoice Number <span class="text-danger">*</span></label>
                        <input type="text" name="invoice_no" class="form-control" required 
                               value="<?= htmlspecialchars($purchase['invoice_no']) ?>" 
                               <?= !$canEdit ? 'readonly' : '' ?>>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold">Purchase Date <span class="text-danger">*</span></label>
                        <input type="date" name="purchase_date" class="form-control" required
                               value="<?= $purchase['purchase_date'] ?>" 
                               <?= !$canEdit ? 'readonly' : '' ?>>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Created By</label>
                            <input type="text" class="form-control" value="<?= htmlspecialchars($purchase['created_by_name'] ?? 'Unknown') ?>" readonly>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Created On</label>
                            <input type="text" class="form-control" value="<?= date('d/m/Y H:i', strtotime($purchase['created_at'])) ?>" readonly>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Original Total</label>
                            <input type="text" class="form-control" value="TSh <?= number_format($purchase['total'], 2) ?>" readonly>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-boxes"></i> Purchase Items</h5>
            <?php if ($canEdit): ?>
                <button type="button" class="btn btn-primary btn-sm" onclick="addNewRow()">
                    <i class="fas fa-plus"></i> Add New Item
                </button>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="linesTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>Product</th>
                            <th>Batch No</th>
                            <th>Qty</th>
                            <th>Cost Price</th>
                            <th>Sell Price</th>
                            <th>Expiry Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $totalQty = 0;
                        $totalCost = 0;
                        foreach ($purchase_lines as $line): 
                            // Check if item has been sold
                            $soldStmt = $pdo->prepare("
                                SELECT COUNT(*) as sale_count, COALESCE(SUM(qty), 0) as sold_qty 
                                FROM sale_lines 
                                WHERE batch_id = ?
                            ");
                            $soldStmt->execute([$line['batch_id']]);
                            $soldData = $soldStmt->fetch(PDO::FETCH_ASSOC);
                            $hasSales = $soldData && $soldData['sale_count'] > 0;
                            $soldQty = $soldData['sold_qty'] ?? 0;
                            $availableQty = $line['qty'] - $soldQty;
                            
                            $totalQty += $line['qty'];
                            $totalCost += $line['qty'] * $line['cost_price'];
                        ?>
                        <tr data-line-id="<?= $line['line_id'] ?>" data-batch-id="<?= $line['batch_id'] ?>">
                            <td>
                                <?= htmlspecialchars($line['product_name']) ?>
                                <small class="text-muted d-block"><?= $line['unit'] ?? 'unit' ?></small>
                                <input type="hidden" name="line_id[]" value="<?= $line['line_id'] ?>">
                                <input type="hidden" name="batch_id[]" value="<?= $line['batch_id'] ?>">
                                <input type="hidden" name="product_id[]" value="<?= $line['product_id'] ?>">
                            </td>
                            <td>
                                <?= htmlspecialchars($line['batch_no']) ?>
                            </td>
                            <td>
                                <input type="number" class="form-control qty" name="qty[]" 
                                       value="<?= $line['qty'] ?>" min="<?= $hasSales ? max(1, $soldQty) : 1 ?>" 
                                       required onchange="calculateTotal()" onkeyup="calculateTotal()"
                                       <?= !$canEdit ? 'readonly' : '' ?>
                                       title="<?= $hasSales ? "Already sold: $soldQty units" : '' ?>">
                                <?php if ($hasSales): ?>
                                    <small class="text-warning">
                                        <i class="fas fa-shopping-cart"></i> Sold: <?= $soldQty ?>
                                    </small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">TSh</span>
                                    </div>
                                    <input type="number" class="form-control cost" name="cost_price[]" 
                                           value="<?= $line['cost_price'] ?>" step="0.01" required 
                                           onchange="calculateTotal()" onkeyup="calculateTotal()"
                                           <?= !$canEdit ? 'readonly' : '' ?>>
                                </div>
                            </td>
                            <td>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">TSh</span>
                                    </div>
                                    <input type="number" class="form-control sell" name="sell_price[]" 
                                           value="<?= $line['sell_price'] ?>" step="0.01" required
                                           <?= !$canEdit ? 'readonly' : '' ?>>
                                </div>
                            </td>
                            <td>
                                <input type="date" class="form-control expiry" name="expiry_date[]" 
                                       value="<?= $line['expiry_date'] ?>"
                                       <?= !$canEdit ? 'readonly' : '' ?>>
                            </td>
                            <td class="text-center">
                                <?php if ($hasSales): ?>
                                    <span class="badge badge-warning" title="This item has been sold">
                                        <i class="fas fa-shopping-cart"></i> Sold
                                    </span>
                                <?php else: ?>
                                    <span class="badge badge-success">Unsold</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <?php if ($canEdit && !$hasSales): ?>
                                    <button type="button" class="btn btn-danger btn-sm" 
                                            onclick="removeRow(this, <?= $line['line_id'] ?>)"
                                            title="Remove item">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-calculator"></i> Purchase Summary</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label class="font-weight-bold">Total Items</label>
                        <input type="text" id="itemCount" class="form-control" readonly value="<?= count($purchase_lines) ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label class="font-weight-bold">Total Quantity</label>
                        <input type="text" id="totalQty" class="form-control" readonly value="<?= $totalQty ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label class="font-weight-bold">New Total Amount</label>
                        <input type="text" id="total" class="form-control" readonly value="<?= number_format($totalCost, 2) ?>">
                    </div>
                </div>
            </div>
            
            <div class="form-group mt-3">
                <label>Update Notes (Optional)</label>
                <textarea name="update_notes" class="form-control" rows="2" 
                          placeholder="Reason for update..."></textarea>
            </div>
            
            <div class="form-group mt-4">
                <button type="submit" form="editPurchaseForm" class="btn btn-success btn-lg" id="saveBtn">
                    <i class="fas fa-save"></i> Save Changes
                </button>
                <a href="list_purchases.php" class="btn btn-secondary btn-lg">
                    <i class="fas fa-times"></i> Cancel
                </a>
                <a href="view_purchase.php?id=<?= $purchase_id ?>" class="btn btn-info btn-lg">
                    <i class="fas fa-eye"></i> View Details
                </a>
            </div>
        </div>
    </div>
</div>

<script>
const allProducts = <?= json_encode($products) ?>;
let newRowCounter = 0;

function showToast(message, type='success', icon='') {
    const icons = {
        'success': 'fa-check-circle',
        'danger': 'fa-exclamation-circle',
        'warning': 'fa-exclamation-triangle',
        'info': 'fa-info-circle'
    };
    
    let toastId = 'toast-' + Date.now();
    let toastHTML = `
        <div id="${toastId}" class="alert alert-${type} alert-dismissible fade show shadow" 
             style="min-width: 300px; margin-bottom: 10px; border-left: 4px solid var(--${type});">
            <div class="d-flex align-items-center">
                <i class="fas ${icon || icons[type] || 'fa-info-circle'} fa-lg mr-2"></i>
                <div class="flex-grow-1">${message}</div>
                <button type="button" class="close ml-2" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </div>`;
    
    $('#toastContainer').append(toastHTML);
    
    // Auto remove after 4 seconds
    setTimeout(() => {
        $(`#${toastId}`).alert('close');
    }, 4000);
}

function addNewRow() {
    newRowCounter++;
    let row = `
    <tr id="new-row-${newRowCounter}" class="table-info">
        <td>
            <select name="new_product_id[]" class="form-control" required>
                <option value="">-- Select Product --</option>
                ${allProducts.map(p => `<option value="${p.id}">${p.name} (${p.unit || 'unit'})</option>`).join('')}
            </select>
        </td>
        <td>
            <input type="text" name="new_batch_no[]" class="form-control" required 
                   placeholder="New batch number">
        </td>
        <td>
            <input type="number" name="new_qty[]" class="form-control new-qty" min="1" required 
                   onchange="calculateTotal()" onkeyup="calculateTotal()">
        </td>
        <td>
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text">TSh</span>
                </div>
                <input type="number" name="new_cost_price[]" class="form-control new-cost" step="0.01" required 
                       onchange="calculateTotal()" onkeyup="calculateTotal()">
            </div>
        </td>
        <td>
            <div class="input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text">TSh</span>
                </div>
                <input type="number" name="new_sell_price[]" class="form-control" step="0.01" required>
            </div>
        </td>
        <td>
            <input type="date" name="new_expiry_date[]" class="form-control">
        </td>
        <td>
            <span class="badge badge-info">New</span>
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-danger btn-sm" 
                    onclick="removeNewRow(${newRowCounter})"
                    title="Remove new item">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    </tr>`;
    
    $('#linesTable tbody').append(row);
    updateItemCount();
}

function removeRow(btn, lineId) {
    if (confirm('Are you sure you want to remove this item?')) {
        // Mark for deletion
        $('#linesTable tbody').append(`<input type="hidden" name="delete_line_id[]" value="${lineId}">`);
        $(btn).closest('tr').remove();
        calculateTotal();
        updateItemCount();
    }
}

function removeNewRow(rowId) {
    $(`#new-row-${rowId}`).remove();
    calculateTotal();
    updateItemCount();
}

function calculateTotal() {
    let total = 0;
    let totalQty = 0;
    
    // Calculate from existing items
    $('#linesTable tbody tr[data-line-id]').each(function() {
        let qty = parseFloat($(this).find('.qty').val()) || 0;
        let cost = parseFloat($(this).find('.cost').val()) || 0;
        total += qty * cost;
        totalQty += qty;
    });
    
    // Calculate from new items
    $('#linesTable tbody tr[id^="new-row-"]').each(function() {
        let qty = parseFloat($(this).find('.new-qty').val()) || 0;
        let cost = parseFloat($(this).find('.new-cost').val()) || 0;
        total += qty * cost;
        totalQty += qty;
    });
    
    $('#total').val(total.toFixed(2));
    $('#totalQty').val(totalQty);
}

function updateItemCount() {
    let count = $('#linesTable tbody tr').length;
    $('#itemCount').val(count);
}

// Form submission
$('#editPurchaseForm').on('submit', function(e) {
    e.preventDefault();
    
    // Validate at least one item remains
    if ($('#linesTable tbody tr').length === 0) {
        showToast('Purchase must have at least one item.', 'warning', 'fa-exclamation-triangle');
        return;
    }
    
    // Show loading
    let submitBtn = $('#saveBtn');
    let originalText = submitBtn.html();
    submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
    
    let formData = new FormData(this);
    
    $.ajax({
        url: 'save_edit_purchase.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                showToast(response.message, 'success', 'fa-check-circle');
                
                // Store success message in session for redirect
                sessionStorage.setItem('purchase_success', response.message);
                
                // Redirect after 2 seconds
                setTimeout(function() {
                    window.location.href = 'list_purchases.php?updated=1&id=' + response.purchase_id;
                }, 2000);
            } else {
                showToast(response.message, 'danger');
                submitBtn.prop('disabled', false).html(originalText);
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', error);
            showToast('An error occurred while saving changes. Please try again.', 'danger');
            submitBtn.prop('disabled', false).html(originalText);
        }
    });
});

// Auto-calculate selling price for new items
$(document).on('change', '.new-cost', function() {
    let cost = parseFloat($(this).val()) || 0;
    let sellPriceField = $(this).closest('tr').find('input[name="new_sell_price[]"]');
    
    // Only auto-calculate if sell price is empty or zero
    if (!sellPriceField.val() || parseFloat(sellPriceField.val()) === 0) {
        // Add 30% markup by default
        let sellPrice = cost * 1.3;
        sellPriceField.val(sellPrice.toFixed(2));
    }
});

// Initialize calculations
$(document).ready(function() {
    calculateTotal();
});
</script>

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