<?php
include 'auth_check.php';

requireAdminAccess('credit_sale.php');

$message = '';
$messageClass = 'success-box';
$date = date('Y-m-d');
$time = date('H:i:s');
$user = $_SESSION['name'];

function round2($value) {
    return round((float)$value, 2);
}

function allocateInvoicePayment(array $records, float $invoicePaidTarget): array {
    $allocated = [];
    $remainingPaid = round2($invoicePaidTarget);

    foreach ($records as $index => $record) {
        $rowTotal = round2($record['total_amount']);

        if ($index === count($records) - 1) {
            $rowPaid = min($rowTotal, max(0, $remainingPaid));
        } else {
            $rowPaid = min($rowTotal, max(0, $remainingPaid));
            $rowPaid = round2($rowPaid);
        }

        $rowPending = round2($rowTotal - $rowPaid);
        if ($rowPending < 0) {
            $rowPending = 0;
        }

        $allocated[] = [
            'id' => (int)$record['id'],
            'paid_amount' => $rowPaid,
            'pending_amount' => $rowPending,
            'payment_status' => $rowPending <= 0 ? 'Paid' : 'Pending'
        ];

        $remainingPaid = round2($remainingPaid - $rowPaid);
        if ($remainingPaid < 0) {
            $remainingPaid = 0;
        }
    }

    return $allocated;
}

$invoiceGroups = [];
$pageLoadError = '';

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = trim($_POST['action'] ?? '');
        $invoiceNumber = trim($_POST['invoice_number'] ?? '');
        $payment_method = trim($_POST['payment_method'] ?? '');
        $payment_reference = trim($_POST['payment_reference'] ?? '');
        $paymentAmountInput = round2($_POST['payment_amount'] ?? 0);

        if ($invoiceNumber !== '') {
            $stmt = $conn->prepare("SELECT * FROM credit_puraching WHERE invoice_number = ? ORDER BY id ASC");
            $stmt->bind_param("s", $invoiceNumber);
            $stmt->execute();
            $invoiceResult = $stmt->get_result();

            $invoiceRows = [];
            while ($row = $invoiceResult->fetch_assoc()) {
                $invoiceRows[] = $row;
            }

            if (!empty($invoiceRows)) {
                $invoiceTotal = 0;
                $invoicePaid = 0;

                foreach ($invoiceRows as $row) {
                    $invoiceTotal += (float)$row['total_amount'];
                    $invoicePaid += (float)$row['paid_amount'];
                }

                $invoiceTotal = round2($invoiceTotal);
                $invoicePaid = round2($invoicePaid);
                $invoicePending = round2($invoiceTotal - $invoicePaid);
                if ($invoicePending < 0) {
                    $invoicePending = 0;
                }

                if ($action === 'mark_paid') {
                    $paymentAmount = $invoicePending;
                    $newInvoicePaid = $invoiceTotal;
                    $newInvoicePending = 0;
                    $invoiceStatus = 'Paid';
                } elseif ($action === 'partial_pay') {
                    $paymentAmount = $paymentAmountInput;
                    $newInvoicePaid = round2($invoicePaid + $paymentAmount);
                    if ($newInvoicePaid > $invoiceTotal) {
                        $newInvoicePaid = $invoiceTotal;
                    }
                    $newInvoicePending = round2($invoiceTotal - $newInvoicePaid);
                    if ($newInvoicePending < 0) {
                        $newInvoicePending = 0;
                    }
                    $invoiceStatus = $newInvoicePending <= 0 ? 'Paid' : 'Pending';
                } else {
                    $paymentAmount = 0;
                    $newInvoicePaid = $invoicePaid;
                    $newInvoicePending = $invoicePending;
                    $invoiceStatus = $newInvoicePending <= 0 ? 'Paid' : 'Pending';
                }

                if (($action === 'mark_paid') || ($action === 'partial_pay' && $paymentAmount > 0)) {
                    $conn->begin_transaction();

                    $allocatedRows = allocateInvoicePayment($invoiceRows, $newInvoicePaid);

                    foreach ($allocatedRows as $allocated) {
                        $up = $conn->prepare("UPDATE credit_puraching SET paid_amount=?, pending_amount=?, payment_status=?, payment_method=?, payment_reference=?, last_payment_date=?, last_payment_time=?, last_payment_user=? WHERE id=?");
                        $up->bind_param(
                            "ddssssssi",
                            $allocated['paid_amount'],
                            $allocated['pending_amount'],
                            $allocated['payment_status'],
                            $payment_method,
                            $payment_reference,
                            $date,
                            $time,
                            $user,
                            $allocated['id']
                        );
                        $up->execute();
                    }

                    $productNames = implode(', ', array_map(function ($item) {
                        return $item['product_name'];
                    }, $invoiceRows));

                    $firstId = (int)$invoiceRows[0]['id'];
                    $supplierName = $invoiceRows[0]['supplier'];

                    $log = $conn->prepare("INSERT INTO credit_purchaing_update (credit_purchase_id, product_name, supplier, invoice_number, total_amount, paid_amount, pending_amount, payment_amount, payment_status, payment_method, payment_reference, entered_date, entered_time, entered_user) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                    $log->bind_param(
                        "isssddddssssss",
                        $firstId,
                        $productNames,
                        $supplierName,
                        $invoiceNumber,
                        $invoiceTotal,
                        $newInvoicePaid,
                        $newInvoicePending,
                        $paymentAmount,
                        $invoiceStatus,
                        $payment_method,
                        $payment_reference,
                        $date,
                        $time,
                        $user
                    );
                    $log->execute();

                    $conn->commit();

                    $message = 'Credit purchasing payment updated successfully.';
                } else {
                    $message = 'Please enter a valid payment amount.';
                    $messageClass = 'error-box';
                }
            } else {
                $message = 'Selected invoice details not found.';
                $messageClass = 'error-box';
            }
        } else {
            $message = 'Invoice number is missing.';
            $messageClass = 'error-box';
        }
    }

    $search_date = trim($_GET['search_date'] ?? '');
    $search_company = trim($_GET['search_company'] ?? '');
    $search_invoice = trim($_GET['search_invoice'] ?? '');

    $query = "
        SELECT *
        FROM credit_puraching
        WHERE 1=1
    ";
    $params = [];
    $types = '';

    if ($search_date !== '') {
        $query .= " AND purchase_date = ?";
        $params[] = $search_date;
        $types .= 's';
    }
    if ($search_company !== '') {
        $query .= " AND supplier LIKE CONCAT('%', ?, '%')";
        $params[] = $search_company;
        $types .= 's';
    }
    if ($search_invoice !== '') {
        $query .= " AND invoice_number LIKE CONCAT('%', ?, '%')";
        $params[] = $search_invoice;
        $types .= 's';
    }

    $query .= " ORDER BY purchase_date ASC, id DESC";

    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $records = $stmt->get_result();

    while ($row = $records->fetch_assoc()) {
        $invoiceKey = trim((string)$row['invoice_number']);
        if ($invoiceKey === '') {
            $invoiceKey = 'NO-INVOICE-' . $row['id'];
        }

        if (!isset($invoiceGroups[$invoiceKey])) {
            $invoiceGroups[$invoiceKey] = [
                'invoice_number' => $row['invoice_number'],
                'supplier' => $row['supplier'],
                'purchase_date' => $row['purchase_date'],
                'total_amount' => 0,
                'paid_amount' => 0,
                'pending_amount' => 0,
                'payment_method' => $row['payment_method'],
                'payment_reference' => $row['payment_reference'],
                'items' => []
            ];
        }

        $invoiceGroups[$invoiceKey]['total_amount'] += (float)$row['total_amount'];
        $invoiceGroups[$invoiceKey]['paid_amount'] += (float)$row['paid_amount'];
        $invoiceGroups[$invoiceKey]['pending_amount'] += (float)$row['pending_amount'];

        if (!empty($row['payment_method'])) {
            $invoiceGroups[$invoiceKey]['payment_method'] = $row['payment_method'];
        }
        if (!empty($row['payment_reference'])) {
            $invoiceGroups[$invoiceKey]['payment_reference'] = $row['payment_reference'];
        }
        if (!empty($row['purchase_date']) && ($invoiceGroups[$invoiceKey]['purchase_date'] === '' || $row['purchase_date'] < $invoiceGroups[$invoiceKey]['purchase_date'])) {
            $invoiceGroups[$invoiceKey]['purchase_date'] = $row['purchase_date'];
        }

        $invoiceGroups[$invoiceKey]['items'][] = $row;
    }
} catch (Throwable $e) {
    try {
        $conn->rollback();
    } catch (Throwable $rollbackError) {
    }

    app_log_error('credit_purchases.php error: ' . $e->getMessage());
    $message = 'Connection or server issue detected. Please try again.';
    $messageClass = 'error-box';
    $pageLoadError = 'Credit purchase data could not be loaded at the moment.';
    $invoiceGroups = [];
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Credit Purchases</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <?php renderSidebar('credit_purchases'); ?>
    <main class="main-content">
        <div class="topbar"><span class="topbar-left-status"></span>Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <?php if ($message !== '') { ?>
            <div class="message-box <?php echo $messageClass; ?>"><?php echo htmlspecialchars($message); ?></div>
        <?php } ?>

        <?php if ($pageLoadError !== '') { ?>
            <div class="message-box error-box"><?php echo htmlspecialchars($pageLoadError); ?></div>
        <?php } ?>

        <div class="credit-card">
            <h2>Credit-Purchases</h2>

            <form method="GET" class="search-bar">
                <input type="date" name="search_date" value="<?php echo htmlspecialchars($_GET['search_date'] ?? ''); ?>">
                <input type="text" name="search_company" placeholder="Company Name" value="<?php echo htmlspecialchars($_GET['search_company'] ?? ''); ?>">
                <input type="text" name="search_invoice" placeholder="Invoice Number" value="<?php echo htmlspecialchars($_GET['search_invoice'] ?? ''); ?>">
                <button type="submit">Search</button>
            </form>

            <div class="table-scroll">
                <table>
                    <tr>
                        <th>Supplier</th>
                        <th>Total</th>
                        <th>Paid</th>
                        <th>Pending</th>
                        <th>Status</th>
                        <th>Payment Method</th>
                        <th>Reference</th>
                        <th>Purchase Date</th>
                        <th>Action</th>
                    </tr>
                    <?php foreach ($invoiceGroups as $invoiceKey => $group) {
                        $group['total_amount'] = round2($group['total_amount']);
                        $group['paid_amount'] = round2($group['paid_amount']);
                        $group['pending_amount'] = round2($group['pending_amount']);
                        $statusLabel = $group['pending_amount'] <= 0 ? 'Paid' : 'Pending';
                        $pendingLong = ($group['pending_amount'] > 0) && ((strtotime(date('Y-m-d')) - strtotime($group['purchase_date'])) > 7 * 24 * 60 * 60);

                        $modalPayload = [
                            'invoice_number' => $group['invoice_number'],
                            'supplier' => $group['supplier'],
                            'total_amount' => $group['total_amount'],
                            'paid_amount' => $group['paid_amount'],
                            'pending_amount' => $group['pending_amount'],
                            'payment_method' => $group['payment_method'],
                            'payment_reference' => $group['payment_reference'],
                            'purchase_date' => $group['purchase_date'],
                            'items' => array_map(function ($item) {
                                $qty = (float)$item['purchased_qty'];
                                $lineTotal = round2($item['total_amount']);
                                $itemPrice = $qty > 0 ? round2($lineTotal / $qty) : 0;

                                return [
                                    'product_name' => $item['product_name'],
                                    'purchased_qty' => round2($item['purchased_qty']),
                                    'unit' => $item['unit'],
                                    'total_amount' => $lineTotal,
                                    'item_price' => $itemPrice
                                ];
                            }, $group['items'])
                        ];
                    ?>
                    <tr class="<?php echo $pendingLong ? 'pending-credit' : ''; ?>">
                        <td><?php echo htmlspecialchars($group['supplier']); ?></td>
                        <td><?php echo number_format($group['total_amount'], 2); ?></td>
                        <td><?php echo number_format($group['paid_amount'], 2); ?></td>
                        <td><?php echo number_format($group['pending_amount'], 2); ?></td>
                        <td><?php echo htmlspecialchars($statusLabel); ?></td>
                        <td><?php echo htmlspecialchars($group['payment_method']); ?></td>
                        <td><?php echo htmlspecialchars($group['payment_reference']); ?></td>
                        <td><?php echo htmlspecialchars($group['purchase_date']); ?></td>
                        <td>
                            <button type="button"
                                    class="invoice-action-btn"
                                    onclick='openCreditPurchaseModal(<?php echo json_encode($modalPayload, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>)'>
                                Action
                            </button>
                        </td>
                    </tr>
                    <?php } ?>
                </table>
            </div>
        </div>
    </main>
</div>

<div class="credit-modal-backdrop" id="creditPurchaseModal">
    <div class="credit-modal-card">
        <div class="credit-modal-header">
            <div>
                <h3>Invoice Details</h3>
                <div class="credit-modal-meta" id="creditModalMeta"></div>
            </div>
            <button type="button" class="credit-modal-close" onclick="closeCreditPurchaseModal()">×</button>
        </div>

        <div class="credit-modal-items-wrap">
            <div class="credit-modal-items" id="creditModalItems"></div>
        </div>

        <div class="credit-modal-divider"></div>

        <form method="POST" class="credit-modal-footer">
            <input type="hidden" name="invoice_number" id="credit_modal_invoice_number">

            <div class="credit-modal-summary-row">
                <div class="credit-summary-pill">Total: <span id="creditModalTotal">0.00</span></div>
                <div class="credit-summary-pill">Paid: <span id="creditModalPaid">0.00</span></div>
                <div class="credit-summary-pill">Pending: <span id="creditModalPending">0.00</span></div>
            </div>

            <div class="credit-modal-action-grid">
                <input type="number" step="0.01" min="0" name="payment_amount" id="credit_modal_payment_amount" placeholder="Partial Amount">
                <select name="payment_method" id="credit_modal_payment_method" required>
                    <option value="">Method</option>
                    <option value="Cash">Cash</option>
                    <option value="Cheque Number">Cheque Number</option>
                    <option value="Bank Transfer Number">Bank Transfer Number</option>
                </select>
                <input type="text" name="payment_reference" id="credit_modal_payment_reference" placeholder="Cheque / Transfer No">
            </div>

            <div class="credit-modal-button-row">
                <button type="submit" name="action" value="partial_pay">Partial Pay</button>
                <button type="submit" name="action" value="mark_paid">Paid</button>
            </div>
        </form>
    </div>
</div>

<script>
function openCreditPurchaseModal(data) {
    const modal = document.getElementById('creditPurchaseModal');
    const meta = document.getElementById('creditModalMeta');
    const itemsWrap = document.getElementById('creditModalItems');

    document.getElementById('credit_modal_invoice_number').value = data.invoice_number || '';
    document.getElementById('credit_modal_payment_method').value = data.payment_method || '';
    document.getElementById('credit_modal_payment_reference').value = data.payment_reference || '';
    document.getElementById('credit_modal_payment_amount').value = '';

    document.getElementById('creditModalTotal').textContent = Number(data.total_amount || 0).toFixed(2);
    document.getElementById('creditModalPaid').textContent = Number(data.paid_amount || 0).toFixed(2);
    document.getElementById('creditModalPending').textContent = Number(data.pending_amount || 0).toFixed(2);

    meta.innerHTML = `
        <strong>Supplier:</strong> ${escapeHtml(data.supplier || '')}
        &nbsp; | &nbsp;
        <strong>Invoice:</strong> ${escapeHtml(data.invoice_number || '')}
        &nbsp; | &nbsp;
        <strong>Date:</strong> ${escapeHtml(data.purchase_date || '')}
    `;

    let html = '';
    (data.items || []).forEach((item, index) => {
        html += `
            <div class="credit-modal-item-row">
                <div class="credit-item-main">
                    <div class="credit-item-name">${escapeHtml(item.product_name || '')}</div>
                    <div class="credit-item-sub">
                        Qty: ${escapeHtml(String(item.purchased_qty || '0'))} ${escapeHtml(item.unit || '')}
                    </div>
                </div>
                <div class="credit-item-values">
                    <div><span>Item Price</span><strong>Rs. ${Number(item.item_price || 0).toFixed(2)}</strong></div>
                    <div><span>Line Total</span><strong>Rs. ${Number(item.total_amount || 0).toFixed(2)}</strong></div>
                </div>
            </div>
        `;
        if (index !== (data.items || []).length - 1) {
            html += `<div class="credit-modal-item-separator"></div>`;
        }
    });

    itemsWrap.innerHTML = html || '<div class="credit-modal-empty">No items found for this invoice.</div>';
    modal.classList.add('show');
}

function closeCreditPurchaseModal() {
    document.getElementById('creditPurchaseModal').classList.remove('show');
}

document.getElementById('creditPurchaseModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeCreditPurchaseModal();
    }
});

function escapeHtml(value) {
    return String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}
</script>
</body>
</html>