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

$pdo = getDB();
$user = currentUser();

$edit_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$grn = null;
$items = [];

if ($edit_id) {
    $stmt = $pdo->prepare("SELECT * FROM grns WHERE id = ? AND status = 'Draft'");
    $stmt->execute([$edit_id]);
    $grn = $stmt->fetch();
    if (!$grn) { $_SESSION['error'] = 'GRN not found or cannot be edited.'; header('Location: grn_list.php'); exit; }

    $stmt = $pdo->prepare("SELECT gi.*, p.product_name, p.product_type FROM grn_items gi JOIN products p ON gi.product_id = p.id WHERE gi.grn_id = ?");
    $stmt->execute([$edit_id]);
    $items = $stmt->fetchAll();

    // Get IMEIs for phone items
    foreach ($items as &$item) {
        if ($item['product_type'] === 'phone') {
            $stmt = $pdo->prepare("SELECT imei_number, serial_number FROM grn_item_imeis WHERE grn_item_id = ?");
            $stmt->execute([$item['id']]);
            $item['imeis'] = $stmt->fetchAll();
        }
    }
    unset($item);
}

$suppliers = $pdo->query("SELECT id, supplier_name, company_name FROM suppliers WHERE status = 1 ORDER BY supplier_name")->fetchAll();
$products = $pdo->query("SELECT id, product_name, product_code, product_type, cost_price, selling_price, current_stock FROM products WHERE status = 1 ORDER BY product_name")->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_grn'])) {
    $supplier_id = (int)$_POST['supplier_id'];
    $received_date = $_POST['received_date'] ?: date('Y-m-d');
    $supplier_invoice_no = trim($_POST['supplier_invoice_no'] ?? '');
    $purchase_order_no = trim($_POST['purchase_order_no'] ?? '');
    $status = $_POST['status'] ?? 'Draft';
    $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'] ?? [];

    if (!$supplier_id) { $_SESSION['error'] = 'Please select a supplier.'; }
    elseif (empty($product_ids) || !array_filter($product_ids)) { $_SESSION['error'] = 'Please add at least one item.'; }
    else {
        try {
            $pdo->beginTransaction();

            $subtotal = 0;
            $tax = 0;
            $discount = (float)($_POST['discount'] ?? 0);
            $items_data = [];

            foreach ($product_ids as $idx => $pid) {
                if (empty($pid)) continue;
                $qty = max(1, (int)($quantities[$idx] ?? 1));
                $cost = (float)($cost_prices[$idx] ?? 0);
                $sell = (float)($selling_prices[$idx] ?? 0);
                $total = $qty * $cost;
                $subtotal += $total;

                $items_data[] = [
                    'product_id' => (int)$pid,
                    'quantity' => $qty,
                    'cost_price' => $cost,
                    'selling_price' => $sell,
                    'total_price' => $total
                ];
            }

            // Tax calculation
            $tax_rate = 0;
            $tax = $subtotal * $tax_rate / 100;
            $total_amount = $subtotal + $tax - $discount;

            if ($edit_id) {
                // Update existing GRN
                $pdo->prepare("UPDATE grns SET supplier_id=?, received_date=?, supplier_invoice_no=?, purchase_order_no=?, subtotal=?, discount=?, tax=?, total_amount=?, status=?, note=?, updated_at=NOW() WHERE id=?")
                    ->execute([$supplier_id, $received_date, $supplier_invoice_no, $purchase_order_no, $subtotal, $discount, $tax, $total_amount, $status, $note, $edit_id]);

                // Delete old items (cascade deletes IMEI records too)
                $pdo->prepare("DELETE FROM grn_items WHERE grn_id = ?")->execute([$edit_id]);
                $grn_id = $edit_id;
            } else {
                $grn_no = generateCode('GRN-', 'grns');
                $stmt = $pdo->prepare("INSERT INTO grns (grn_no, supplier_id, received_date, supplier_invoice_no, purchase_order_no, subtotal, discount, tax, total_amount, status, note, received_by, created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
                $stmt->execute([$grn_no, $supplier_id, $received_date, $supplier_invoice_no, $purchase_order_no, $subtotal, $discount, $tax, $total_amount, $status, $note, $user['id'], $user['id']]);
                $grn_id = $pdo->lastInsertId();
            }

            // Insert GRN items
            foreach ($items_data as $item) {
                $stmt = $pdo->prepare("INSERT INTO grn_items (grn_id, product_id, quantity, cost_price, selling_price, total_price) VALUES (?,?,?,?,?,?)");
                $stmt->execute([$grn_id, $item['product_id'], $item['quantity'], $item['cost_price'], $item['selling_price'], $item['total_price']]);
                $grn_item_id = $pdo->lastInsertId();

                // Handle IMEI for phone products
                $stmt2 = $pdo->prepare("SELECT product_type FROM products WHERE id = ?");
                $stmt2->execute([$item['product_id']]);
                $ptype = $stmt2->fetchColumn();

                if ($ptype === 'phone' && $status === 'Received') {
                    $imeis_for_item = $imei_data[$idx] ?? [];
                    // Split by newline or comma
                    $imei_list = [];
                    if (is_array($imeis_for_item)) {
                        $imei_list = $imeis_for_item;
                    } elseif (is_string($imeis_for_item)) {
                        $imei_list = array_filter(array_map('trim', preg_split('/[\r\n,]+/', $imeis_for_item)));
                    }

                    if (count($imei_list) !== $item['quantity']) {
                        throw new Exception("Item '{$item['product_id']}' requires exactly {$item['quantity']} IMEI number(s), but " . count($imei_list) . " provided.");
                    }

                    foreach ($imei_list as $imei) {
                        $imei = trim($imei);
                        if (empty($imei)) continue;

                        // Check duplicate IMEI
                        $chk = $pdo->prepare("SELECT COUNT(*) FROM product_imei WHERE imei_number = ?");
                        $chk->execute([$imei]);
                        if ($chk->fetchColumn() > 0) {
                            throw new Exception("Duplicate IMEI: $imei already exists in system.");
                        }

                        $stmt = $pdo->prepare("INSERT INTO grn_item_imeis (grn_item_id, product_id, imei_number) VALUES (?,?,?)");
                        $stmt->execute([$grn_item_id, $item['product_id'], $imei]);
                    }
                }
            }

            // If status is Received, update stock
            if ($status === 'Received') {
                foreach ($items_data as $item) {
                    $stmt = $pdo->prepare("SELECT current_stock FROM products WHERE id = ? FOR UPDATE");
                    $stmt->execute([$item['product_id']]);
                    $current = (int)$stmt->fetchColumn();

                    $pdo->prepare("UPDATE products SET current_stock = current_stock + ?, cost_price = ? WHERE id = ?")
                        ->execute([$item['quantity'], $item['cost_price'], $item['product_id']]);

                    $new_balance = $current + $item['quantity'];
                    $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, reference_type, reference_id, quantity_in, quantity_out, balance_after, note, created_by) VALUES (?, 'grn_receive', 'grn', ?, ?, 0, ?, ?, ?)")
                        ->execute([$item['product_id'], $grn_id, $item['quantity'], $new_balance, 'GRN received', $user['id']]);

                    // Create IMEI records for phone products received
                    $stmt2 = $pdo->prepare("SELECT product_type FROM products WHERE id = ?");
                    $stmt2->execute([$item['product_id']]);
                    $ptype = $stmt2->fetchColumn();

                    if ($ptype === 'phone') {
                        // Get IMEIs from grn_item_imeis
                        $stmt = $pdo->prepare("SELECT id, imei_number FROM grn_item_imeis WHERE grn_item_id = ?");
                        $stmt->execute([$grn_item_id]);
                        $imei_records = $stmt->fetchAll();

                        foreach ($imei_records as $ir) {
                            // Check if already added to product_imei (for draft->received transition)
                            $chk = $pdo->prepare("SELECT COUNT(*) FROM product_imei WHERE imei_number = ?");
                            $chk->execute([$ir['imei_number']]);
                            if ($chk->fetchColumn() == 0) {
                                $pdo->prepare("INSERT INTO product_imei (product_id, imei_number, purchase_item_id, status) VALUES (?,?,?, 'Available')")
                                    ->execute([$item['product_id'], $ir['imei_number'], $grn_item_id]);
                            }
                        }
                    }
                }
            }

            $pdo->commit();

            if ($status === 'Received') {
                $_SESSION['success'] = 'GRN received and stock updated successfully.';
            } else {
                $_SESSION['success'] = 'GRN saved as draft.';
            }

            header('Location: view_grn.php?id=' . $grn_id); exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = 'Error: ' . $e->getMessage();
        }
    }
}

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-<?= $edit_id ? 'edit' : 'plus' ?> me-2"></i><?= $edit_id ? 'Edit' : 'Create' ?> GRN</h4>

        <?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="grnForm">
            <input type="hidden" name="save_grn" value="1">

            <div class="card">
                <div class="card-header">GRN Information</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Supplier <span class="text-danger">*</span></label>
                            <select name="supplier_id" class="form-select select2" required>
                                <option value="">Select Supplier</option>
                                <?php foreach ($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>" <?= ($grn['supplier_id'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['supplier_name']) ?> <?= $s['company_name'] ? '(' . htmlspecialchars($s['company_name']) . ')' : '' ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Received Date <span class="text-danger">*</span></label>
                            <input type="date" name="received_date" class="form-control" value="<?= $grn['received_date'] ?? date('Y-m-d') ?>" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select" id="grnStatus">
                                <option value="Draft">Draft (No stock update)</option>
                                <option value="Received" <?= ($grn['status'] ?? '') == 'Received' ? 'selected' : '' ?>>Received (Update stock)</option>
                            </select>
                            <div class="form-text">Select "Received" to update stock immediately.</div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Supplier Invoice No</label>
                            <input type="text" name="supplier_invoice_no" class="form-control" value="<?= htmlspecialchars($grn['supplier_invoice_no'] ?? '') ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Purchase Order No</label>
                            <input type="text" name="purchase_order_no" class="form-control" value="<?= htmlspecialchars($grn['purchase_order_no'] ?? '') ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Discount</label>
                            <input type="number" step="0.01" name="discount" class="form-control" value="<?= $grn['discount'] ?? 0 ?>" min="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"><?= htmlspecialchars($grn['note'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header d-flex justify-content-between">
                    <span><i class="fas fa-boxes me-1"></i>GRN Items</span>
                    <button type="button" class="btn btn-sm btn-success" onclick="addItemRow()"><i class="fas fa-plus me-1"></i>Add Item</button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table no-datatable" id="itemsTable">
                            <thead>
                                <tr>
                                    <th style="width:30%;">Product <span class="text-danger">*</span></th>
                                    <th style="width:80px;">Qty <span class="text-danger">*</span></th>
                                    <th style="width:120px;">Cost Price</th>
                                    <th style="width:120px;">Selling Price</th>
                                    <th style="width:100px;">Total</th>
                                    <th>IMEI Numbers</th>
                                    <th style="width:40px;"></th>
                                </tr>
                            </thead>
                            <tbody id="itemsBody">
                                <?php if (!empty($items)): ?>
                                <?php foreach ($items as $idx => $item): ?>
                                <tr class="item-row">
                                    <td>
                                        <select name="product_id[]" class="form-select product-select" required>
                                            <option value="">Select Product</option>
                                            <?php foreach ($products as $p): ?>
                                            <option value="<?= $p['id'] ?>" data-type="<?= $p['product_type'] ?>" data-cost="<?= $p['cost_price'] ?>" data-sell="<?= $p['selling_price'] ?>" <?= $item['product_id'] == $p['id'] ? 'selected' : '' ?>><?= htmlspecialchars($p['product_name']) ?> (<?= $p['product_type'] ?>)</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="number" name="quantity[]" class="form-control item-qty" value="<?= $item['quantity'] ?>" min="1" required></td>
                                    <td><input type="number" step="0.01" name="cost_price[]" class="form-control item-cost" value="<?= $item['cost_price'] ?>"></td>
                                    <td><input type="number" step="0.01" name="selling_price[]" class="form-control item-sell" value="<?= $item['selling_price'] ?>"></td>
                                    <td class="item-total fw-bold"><?= formatCurrency($item['total_price']) ?></td>
                                    <td>
                                        <textarea name="imei[<?= $idx ?>][]" class="form-control imei-input" rows="1" placeholder="One IMEI per line" style="display:none;"><?= isset($item['imeis']) ? implode("\n", array_column($item['imeis'], 'imei_number')) : '' ?></textarea>
                                    </td>
                                    <td><button type="button" class="btn btn-sm btn-danger remove-item"><i class="fas fa-times"></i></button></td>
                                </tr>
                                <?php endforeach; ?>
                                <?php else: ?>
                                <tr class="item-row">
                                    <td>
                                        <select name="product_id[]" class="form-select product-select" required>
                                            <option value="">Select Product</option>
                                            <?php foreach ($products as $p): ?>
                                            <option value="<?= $p['id'] ?>" data-type="<?= $p['product_type'] ?>" data-cost="<?= $p['cost_price'] ?>" data-sell="<?= $p['selling_price'] ?>"><?= htmlspecialchars($p['product_name']) ?> (<?= $p['product_type'] ?>)</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="number" name="quantity[]" class="form-control item-qty" value="1" min="1" required></td>
                                    <td><input type="number" step="0.01" name="cost_price[]" class="form-control item-cost" value="0"></td>
                                    <td><input type="number" step="0.01" name="selling_price[]" class="form-control item-sell" value="0"></td>
                                    <td class="item-total fw-bold">0.00</td>
                                    <td>
                                        <textarea name="imei[0][]" class="form-control imei-input" rows="1" placeholder="One IMEI per line" style="display:none;"></textarea>
                                    </td>
                                    <td><button type="button" class="btn btn-sm btn-danger remove-item"><i class="fas fa-times"></i></button></td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="d-flex gap-2 mb-4">
                <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save me-1"></i> Save GRN</button>
                <a href="grn_list.php" class="btn btn-secondary btn-lg">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
var rowIndex = <?= count($items) > 0 ? count($items) : 1 ?>;

function addItemRow() {
    var row = $('#itemsBody .item-row').first().clone();
    row.find('select').val('');
    row.find('input').val('');
    row.find('input.item-qty').val('1');
    row.find('.item-total').text('0.00');
    row.find('.imei-input').val('').hide();
    row.find('textarea').attr('name', 'imei[' + rowIndex + '][]');
    $('#itemsBody').append(row);
    row.find('.select2').select2({ theme: 'bootstrap-5', width: '100%' });
    rowIndex++;
}

$(document).on('click', '.remove-item', function() {
    if ($('#itemsBody .item-row').length > 1) {
        $(this).closest('tr').remove();
    }
});

$(document).on('change', '.product-select', function() {
    var row = $(this).closest('tr');
    var opt = $(this).find('option:selected');
    var type = opt.data('type');
    var cost = opt.data('cost');
    var sell = opt.data('sell');

    row.find('.item-cost').val(cost || 0);
    row.find('.item-sell').val(sell || 0);

    if (type === 'phone') {
        row.find('.imei-input').show().attr('required', true);
    } else {
        row.find('.imei-input').hide().removeAttr('required');
    }
    calcRow(row);
});

$(document).on('input', '.item-qty, .item-cost', function() {
    calcRow($(this).closest('tr'));
});

function calcRow(row) {
    var qty = parseInt(row.find('.item-qty').val()) || 0;
    var cost = parseFloat(row.find('.item-cost').val()) || 0;
    row.find('.item-total').text((qty * cost).toFixed(2));
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
