<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('purchase_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $supplier_id = (int)($_POST['supplier_id'] ?? 0);
    $purchase_date = $_POST['purchase_date'] ?? date('Y-m-d');
    $purchase_status = $_POST['purchase_status'] ?? 'Pending';
    $discount = (float)($_POST['discount'] ?? 0);
    $tax = (float)($_POST['tax'] ?? 0);
    $paid_amount = (float)($_POST['paid_amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'Cash';
    $note = trim($_POST['note'] ?? '');

    $product_ids = $_POST['product_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $cost_prices = $_POST['cost_price'] ?? [];
    $selling_prices = $_POST['selling_price'] ?? [];
    $imei_data = $_POST['imei_numbers'] ?? [];

    if ($supplier_id <= 0 || empty($product_ids)) {
        $_SESSION['error'] = 'Please select a supplier and add at least one product.';
        header('Location: add_purchase.php'); exit;
    }

    try {
        $pdo->beginTransaction();

        $purchase_no = generatePurchaseNo();

        $subtotal = 0;
        $items = [];
        foreach ($product_ids as $idx => $pid) {
            $pid = (int)$pid;
            if ($pid <= 0) continue;
            $qty = max(1, (int)($quantities[$idx] ?? 1));
            $cost = max(0, (float)($cost_prices[$idx] ?? 0));
            $sell = max(0, (float)($selling_prices[$idx] ?? 0));
            $total = $qty * $cost;
            $subtotal += $total;
            $items[] = [
                'product_id' => $pid,
                'quantity' => $qty,
                'cost_price' => $cost,
                'selling_price' => $sell,
                'total_price' => $total,
                'imei' => $imei_data[$idx] ?? '',
            ];
        }

        $total_amount = $subtotal - $discount + $tax;
        if ($total_amount < 0) $total_amount = 0;
        $due_amount = $total_amount - $paid_amount;
        if ($due_amount < 0) $due_amount = 0;

        $stmt = $pdo->prepare("INSERT INTO purchases (purchase_no, supplier_id, purchase_date, subtotal, discount, tax, total_amount, paid_amount, due_amount, payment_method, purchase_status, note, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$purchase_no, $supplier_id, $purchase_date, $subtotal, $discount, $tax, $total_amount, $paid_amount, $due_amount, $payment_method, $purchase_status, $note, $_SESSION['user_id']]);
        $purchase_id = $pdo->lastInsertId();

        $item_stmt = $pdo->prepare("INSERT INTO purchase_items (purchase_id, product_id, quantity, cost_price, selling_price, total_price) VALUES (?, ?, ?, ?, ?, ?)");

        foreach ($items as $item) {
            $item_stmt->execute([$purchase_id, $item['product_id'], $item['quantity'], $item['cost_price'], $item['selling_price'], $item['total_price']]);
            $purchase_item_id = $pdo->lastInsertId();

            if ($purchase_status === 'Received') {
                $movement_ok = createStockMovement($item['product_id'], 'purchase', 'purchases', $purchase_id, $item['quantity'], 0, 'Purchase GRN', $_SESSION['user_id']);
                if (!$movement_ok) { throw new Exception("Stock movement failed for product ID {$item['product_id']}."); }
            }

            if ($purchase_status === 'Received' && !empty(trim($item['imei']))) {
                $stmt_prod = $pdo->prepare("SELECT product_type FROM products WHERE id = ?");
                $stmt_prod->execute([$item['product_id']]);
                $prod_type = $stmt_prod->fetchColumn();
                if (strtolower($prod_type) === 'phone') {
                    $imei_list = array_filter(array_map('trim', explode("\n", str_replace("\r", "", $item['imei']))));
                    if (count($imei_list) !== $item['quantity']) { throw new Exception("IMEI count (" . count($imei_list) . ") does not match quantity (" . $item['quantity'] . ") for product ID {$item['product_id']}."); }
                    $imei_stmt = $pdo->prepare("INSERT INTO product_imei (product_id, imei_number, serial_number, purchase_item_id, status) VALUES (?, ?, '', ?, 'Available')");
                    foreach ($imei_list as $imei) {
                        if (!empty($imei)) {
                            $imei_stmt->execute([$item['product_id'], $imei, $purchase_item_id]);
                        }
                    }
                }
            }
        }

        if ($purchase_status === 'Received') {
            $stmt = $pdo->prepare("UPDATE suppliers SET current_balance = current_balance + ? WHERE id = ?");
            $stmt->execute([$due_amount, $supplier_id]);
        }

        if ($paid_amount > 0) {
            $payment_no = generatePaymentNo();
            $stmt = $pdo->prepare("INSERT INTO payments (payment_no, payment_type, reference_id, supplier_id, amount, payment_method, payment_date, note, received_by) VALUES (?, 'supplier', ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$payment_no, $purchase_id, $supplier_id, $paid_amount, $payment_method, $purchase_date, 'Purchase payment for ' . $purchase_no, $_SESSION['user_id']]);
        }

        $pdo->commit();
        logActivity('Created Purchase', 'Purchases', $purchase_id, "Purchase #$purchase_no created with status $purchase_status");
        $_SESSION['success'] = "Purchase #$purchase_no created successfully.";
        header('Location: purchases.php'); exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = 'Error: ' . $e->getMessage();
        header('Location: add_purchase.php'); exit;
    }
}

$suppliers = $pdo->query("SELECT id, supplier_name, company_name FROM suppliers WHERE status = 1 ORDER BY supplier_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-plus-circle me-2"></i>Add Purchase Order</h4>
            <a href="purchases.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back to Purchases</a>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <form method="POST" id="purchaseForm">
            <div class="card mb-3">
                <div class="card-header"><i class="fas fa-user me-2"></i>Supplier Information</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Supplier *</label>
                            <select name="supplier_id" id="supplierSelect" class="form-select select2" required>
                                <option value="">Select Supplier</option>
                                <?php foreach ($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['supplier_name'] . ($s['company_name'] ? ' (' . $s['company_name'] . ')' : '')) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Purchase Date *</label>
                            <input type="date" name="purchase_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Note</label>
                            <input type="text" name="note" class="form-control" placeholder="Optional note about this purchase">
                        </div>
                    </div>
                </div>
            </div>

            <div class="card mb-3">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-boxes me-2"></i>Product Items</span>
                    <button type="button" class="btn btn-sm btn-success" id="addItemBtn"><i class="fas fa-plus me-1"></i>Add Row</button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered no-datatable" id="itemsTable">
                            <thead>
                                <tr>
                                    <th style="width:30%;">Product</th>
                                    <th style="width:80px;">Quantity</th>
                                    <th style="width:120px;">Cost Price</th>
                                    <th style="width:120px;">Selling Price</th>
                                    <th style="width:120px;">Line Total</th>
                                    <th style="width:150px;">IMEI Numbers</th>
                                    <th style="width:40px;"></th>
                                </tr>
                            </thead>
                            <tbody id="itemsBody">
                                <tr class="item-row">
                                    <td>
                                        <select name="product_id[]" class="form-select product-select select2" required>
                                            <option value="">Search Product</option>
                                        </select>
                                    </td>
                                    <td><input type="number" name="quantity[]" class="form-control quantity" value="1" min="1"></td>
                                    <td><input type="number" step="0.01" name="cost_price[]" class="form-control cost-price" value="0.00" min="0"></td>
                                    <td><input type="number" step="0.01" name="selling_price[]" class="form-control selling-price" value="0.00" min="0"></td>
                                    <td><input type="text" class="form-control line-total" value="0.00" readonly></td>
                                    <td><textarea name="imei_numbers[]" class="form-control imei-input" rows="1" placeholder="IMEI (one per line)" style="display:none;font-size:0.8rem;"></textarea></td>
                                    <td><button type="button" class="btn btn-danger btn-sm remove-item-btn"><i class="fas fa-times"></i></button></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="card mb-3">
                <div class="card-header"><i class="fas fa-calculator me-2"></i>Summary</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Subtotal</label>
                            <input type="text" id="subtotalDisplay" class="form-control" value="0.00" readonly>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Discount</label>
                            <input type="number" step="0.01" name="discount" id="discountInput" class="form-control" value="0.00" min="0">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Tax</label>
                            <input type="number" step="0.01" name="tax" id="taxInput" class="form-control" value="0.00" min="0">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label fw-bold">Total Amount</label>
                            <input type="text" id="totalDisplay" class="form-control fw-bold" value="0.00" readonly>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card mb-3">
                <div class="card-header"><i class="fas fa-money-bill me-2"></i>Payment</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Paid Amount</label>
                            <input type="number" step="0.01" name="paid_amount" id="paidAmount" class="form-control" value="0.00" min="0">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Payment Method</label>
                            <select name="payment_method" class="form-select">
                                <option value="Cash">Cash</option>
                                <option value="Card">Card</option>
                                <option value="Bank Transfer">Bank Transfer</option>
                                <option value="Online Payment">Online Payment</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold text-danger">Due Amount</label>
                            <input type="text" id="dueDisplay" class="form-control fw-bold text-danger" value="0.00" readonly>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mb-4 text-center">
                <button type="submit" name="purchase_status" value="Pending" class="btn btn-secondary btn-lg me-2"><i class="fas fa-save me-1"></i>Save as Draft</button>
                <button type="submit" name="purchase_status" value="Received" class="btn btn-success btn-lg"><i class="fas fa-check-circle me-1"></i>Save & Receive</button>
            </div>
        </form>
    </div>
</div>

<script>
$(document).ready(function() {
    function initSelect2($el) {
        $el.select2({
            theme: 'bootstrap-5',
            width: '100%',
            dropdownParent: $el.closest('.modal') || 'body',
            ajax: {
                url: '<?= BASE_URL ?>ajax/search_product_purchase.php',
                dataType: 'json',
                delay: 300,
                data: function(params) {
                    return { q: params.term || '' };
                },
                processResults: function(data) {
                    return { results: data.map(function(p) { return { id: p.id, text: p.product_code + ' - ' + p.product_name + ' (' + p.product_type + ')', product: p }; }) };
                },
                cache: true
            },
            minimumInputLength: 1,
            placeholder: 'Search product...',
            allowClear: true
        });
    }

    initSelect2($('.product-select'));

    function calcRowTotal($row) {
        var qty = parseFloat($row.find('.quantity').val()) || 0;
        var cost = parseFloat($row.find('.cost-price').val()) || 0;
        var total = qty * cost;
        $row.find('.line-total').val(total.toFixed(2));
        calcSummary();
    }

    function calcSummary() {
        var subtotal = 0;
        $('.line-total').each(function() { subtotal += parseFloat($(this).val()) || 0; });
        var discount = parseFloat($('#discountInput').val()) || 0;
        var tax = parseFloat($('#taxInput').val()) || 0;
        var total = subtotal - discount + tax;
        if (total < 0) total = 0;
        var paid = parseFloat($('#paidAmount').val()) || 0;
        var due = total - paid;
        if (due < 0) due = 0;
        $('#subtotalDisplay').val(subtotal.toFixed(2));
        $('#totalDisplay').val(total.toFixed(2));
        $('#dueDisplay').val(due.toFixed(2));
    }

    $(document).on('change', '.quantity, .cost-price, .selling-price', function() {
        calcRowTotal($(this).closest('.item-row'));
    });

    $(document).on('change', '#discountInput, #taxInput, #paidAmount', function() {
        calcSummary();
    });

    $(document).on('select2:select', '.product-select', function(e) {
        var data = e.params.data;
        if (data && data.product) {
            var $row = $(this).closest('.item-row');
            $row.find('.cost-price').val(data.product.cost_price || 0);
            $row.find('.selling-price').val(data.product.selling_price || 0);
            if (data.product.product_type && data.product.product_type.toLowerCase() === 'phone') {
                $row.find('.imei-input').show().attr('placeholder', 'Enter IMEI (one per line)');
            } else {
                $row.find('.imei-input').hide().val('');
            }
            calcRowTotal($row);
        }
    });

    $(document).on('select2:clear', '.product-select', function() {
        var $row = $(this).closest('.item-row');
        $row.find('.cost-price').val('0.00');
        $row.find('.selling-price').val('0.00');
        $row.find('.imei-input').hide().val('');
        calcRowTotal($row);
    });

    $('#addItemBtn').click(function() {
        var $clone = $('.item-row').first().clone(true, true);
        $clone.find('input, textarea').val('');
        $clone.find('.quantity').val('1');
        $clone.find('.cost-price, .selling-price, .line-total').val('0.00');
        $clone.find('.imei-input').hide().val('');
        $clone.find('select').val(null).trigger('change');
        var $sel = $clone.find('.product-select');
        $sel.select2('destroy');
        $('#itemsBody').append($clone);
        initSelect2($clone.find('.product-select'));
        calcSummary();
    });

    $(document).on('click', '.remove-item-btn', function() {
        if ($('.item-row').length > 1) {
            var $row = $(this).closest('.item-row');
            var $sel = $row.find('.product-select');
            if ($sel.hasClass('select2-hidden-accessible')) {
                $sel.select2('destroy');
            }
            $row.remove();
            calcSummary();
        } else {
            alert('At least one item is required.');
        }
    });

    $('#purchaseForm').on('submit', function(e) {
        var hasProduct = false;
        $('.product-select').each(function() {
            if ($(this).val()) hasProduct = true;
        });
        if (!hasProduct) { e.preventDefault(); alert('Please add at least one product.'); return; }
        if ($('#supplierSelect').val() === '') { e.preventDefault(); alert('Please select a supplier.'); return; }
        // Validate IMEI for phone products when status=Received
        var status = $('button[type=submit]:focus').val();
        if (status === 'Received') {
            var ok = true;
            $('.item-row').each(function() {
                var $sel = $(this).find('.product-select');
                var selected = $sel.select2('data');
                if (selected.length && selected[0] && selected[0].product && selected[0].product.product_type && selected[0].product.product_type.toLowerCase() === 'phone') {
                    var imei = $(this).find('.imei-input').val().trim();
                    var qty = parseInt($(this).find('.quantity').val()) || 0;
                    var lines = imei ? imei.split('\n').filter(function(l) { return l.trim() !== ''; }) : [];
                    if (lines.length !== qty) {
                        ok = false;
                        alert('Product "' + selected[0].text + '": IMEI count (' + lines.length + ') must equal quantity (' + qty + ').');
                        return false;
                    }
                }
            });
            if (!ok) { e.preventDefault(); return; }
        }
    });
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
