<?php
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/Mailer.php';
requireLogin();

$id = (int)($_GET['id'] ?? 0);

$stmt = $pdo->prepare("SELECT i.*, c.customer_name, c.email, c.phone, c.billing_address, c.shipping_address, c.gst_number as customer_gst, c.city, c.state, c.pincode,
                        u.name as marked_by_name
                        FROM invoices i
                        JOIN sale_vendors c ON c.id=i.customer_id
                        LEFT JOIN users u ON u.id = i.payment_marked_by
                        WHERE i.id=?");
$stmt->execute([$id]);
$inv = $stmt->fetch();

if (!$inv) {
    setFlash('danger', 'Invoice not found.');
    header('Location: invoices.php'); exit;
}

$stmt = $pdo->prepare("SELECT * FROM invoice_items WHERE invoice_id=?");
$stmt->execute([$id]);
$lineItems = $stmt->fetchAll();

// Send email
if (isset($_GET['action']) && $_GET['action'] === 'send_email') {
    $result = Mailer::sendInvoice($id);
    if ($result['success']) {
        setFlash('success', 'Tax invoice emailed to customer successfully.');
    } else {
        setFlash('danger', 'Email failed: ' . $result['error']);
    }
    header("Location: invoice_view.php?id=$id"); exit;
}

// Mark payment received (full or partial) - uses shared payment function
// so this stays in sync with the dedicated Payments tab
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'mark_paid') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.');
        header("Location: invoice_view.php?id=$id"); exit;
    }

    $paymentDateTime = $_POST['payment_datetime'];
    $paymentMode = trim($_POST['payment_mode']);
    $paidAmount = (float)$_POST['paid_amount'];
    $tdsAmount = (float)($_POST['tds_amount'] ?? 0);
    $bankAccountId = (int)($_POST['bank_account_id'] ?? 0);

    $balanceDue = $inv['grand_total'] - $inv['paid_amount'] - $inv['tds_amount'];
    if (($paidAmount + $tdsAmount) > $balanceDue + 0.01) {
        setFlash('danger', 'Amount + TDS exceeds the balance due (' . formatMoney($balanceDue) . ').');
        header("Location: invoice_view.php?id=$id"); exit;
    }

    try {
        $pdo->beginTransaction();
        $result = recordInvoicePayment($id, $paidAmount, $tdsAmount, $paymentDateTime, $paymentMode, '', currentUserId(), $bankAccountId);
        $pdo->commit();

        if ($result['fully_paid']) {
            setFlash('success', "Payment recorded. Invoice marked as PAID. Stock moved from Freeze to Sold.");
        } else {
            setFlash('success', "Partial payment of " . formatMoney($paidAmount) . ($tdsAmount > 0 ? " + TDS " . formatMoney($tdsAmount) : "") . " recorded.");
        }
        header("Location: invoice_view.php?id=$id"); exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error: ' . $e->getMessage());
        header("Location: invoice_view.php?id=$id"); exit;
    }
}

$companyName = getSetting('company_name', 'Your Company');
$companyAddress = getSetting('company_address', '');
$companyGst = getSetting('company_gst', '');
$companyPhone = getSetting('company_phone', '');
$companyEmail = getSetting('company_email', '');

$balance = $inv['grand_total'] - $inv['paid_amount'] - $inv['tds_amount'];
$paymentHistory = getInvoicePaymentHistory($id);
$csrf = generateCSRFToken();
$bankAccounts = $pdo->query("SELECT id, account_name, account_subtype, current_balance FROM accounts WHERE account_subtype IN ('bank','cash') AND is_active=1 ORDER BY account_code")->fetchAll();

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Tax Invoice';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header no-print">
    <div>
        <div class="eyebrow"><?= $inv['invoice_type']==='manual'?'Manual Bill':'Tax Invoice' ?></div>
        <h2 class="mb-0"><?= sanitize($inv['invoice_no']) ?></h2>
    </div>
    <div class="flex gap-8" style="flex-wrap:wrap;">
        <a href="<?= $inv['invoice_type']==='manual' ? '../billing/manual_billing.php' : 'invoices.php' ?>" class="btn"><?= icon('arrow-left') ?> Back</a>
        <a href="invoice_pdf.php?id=<?= $id ?>" class="btn" target="_blank"><?= icon('download') ?> Download PDF</a>
        <?php if (!empty($inv['email'])): ?>
        <a href="?id=<?= $id ?>&action=send_email" class="btn btn-primary" onclick="return confirm('Send this invoice to <?= sanitize($inv['email']) ?>?')">
            <?= icon('mail-forward') ?> <?= $inv['email_sent'] ? 'Re-send Email' : 'Send Email' ?>
        </a>
        <?php endif; ?>
        <?php if ($inv['payment_status'] !== 'paid'): ?>
        <button class="btn btn-success" onclick="document.getElementById('paymentModal').classList.add('show')"><?= icon('cash') ?> <?= $inv['payment_status'] === 'partial' ? 'Record Next Payment' : 'Mark Payment Received' ?></button>
        <?php endif; ?>
    </div>
</div>

<?php if ($inv['payment_status'] === 'paid'): ?>
<div class="alert alert-success no-print">
    <?= icon('circle-check') ?> <strong>FULLY PAID &amp; COMPLETED</strong> — Stock moved from Freeze to Sold.
    Paid on <?= formatDateTime($inv['payment_date']) ?> via <?= sanitize($inv['payment_mode']) ?>.
</div>
<?php elseif ($inv['payment_status'] === 'partial'): ?>
<div class="alert alert-warning no-print"><?= icon('clock') ?> Partially paid: <?= formatMoney($inv['paid_amount']) ?> received. Balance due: <strong><?= formatMoney($balance) ?></strong></div>
<?php else: ?>
<div class="alert alert-danger no-print"><?= icon('alert-circle') ?> Payment pending: <strong><?= formatMoney($inv['grand_total']) ?></strong></div>
<?php endif; ?>

<?php if (!empty($inv['email']) && $inv['email_sent']): ?>
<div class="alert alert-info no-print"><?= icon('mail') ?> Emailed to <?= sanitize($inv['email']) ?> on <?= formatDateTime($inv['email_sent_at']) ?></div>
<?php elseif (empty($inv['email'])): ?>
<div class="alert alert-warning no-print"><?= icon('alert-triangle') ?> No email on file. Use the Download button to share via WhatsApp.</div>
<?php endif; ?>

<div class="card" style="max-width:850px; margin:0 auto;">

    <div class="flex-between" style="align-items:flex-start; margin-bottom: 24px;">
        <div>
            <h1 style="margin-bottom:4px;"><?= sanitize($companyName) ?></h1>
            <div class="text-sm text-muted"><?= nl2br(sanitize($companyAddress)) ?></div>
            <?php if ($companyGst): ?><div class="text-sm text-muted">GSTIN: <?= sanitize($companyGst) ?></div><?php endif; ?>
            <?php if ($companyPhone): ?><div class="text-sm text-muted">Phone: <?= sanitize($companyPhone) ?> | Email: <?= sanitize($companyEmail) ?></div><?php endif; ?>
        </div>
        <div class="text-right">
            <h2 style="margin-bottom:4px;"><?= $inv['invoice_type']==='manual' ? 'INVOICE (SERVICE)' : 'TAX INVOICE' ?></h2>
            <div class="mono"><?= sanitize($inv['invoice_no']) ?></div>
            <div class="text-sm text-muted">Date: <?= formatDate($inv['invoice_date']) ?></div>
            <div class="badge badge-<?= $inv['payment_status']=='paid'?'success':($inv['payment_status']=='partial'?'warning':'danger') ?>" style="margin-top:6px;"><?= strtoupper($inv['payment_status']) ?></div>
        </div>
    </div>

    <div class="divider"></div>

    <div style="margin-bottom:16px;">
        <div class="text-sm text-muted" style="font-weight:700; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:4px;">Bill To</div>
        <div style="font-weight:600;"><?= sanitize($inv['customer_name']) ?></div>
        <div class="text-sm"><?= nl2br(sanitize($inv['billing_address'])) ?></div>
        <div class="text-sm"><?= sanitize($inv['city']) ?><?= $inv['city']&&$inv['state']?', ':'' ?><?= sanitize($inv['state']) ?> <?= sanitize($inv['pincode']) ?></div>
        <?php if ($inv['customer_gst']): ?><div class="text-sm">GSTIN: <?= sanitize($inv['customer_gst']) ?></div><?php endif; ?>
        <div class="text-sm">Phone: <?= sanitize($inv['phone']) ?> | Email: <?= sanitize($inv['email']) ?></div>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th style="width:40px">#</th>
                    <th>Description</th>
                    <th class="text-right">Qty</th>
                    <th class="text-right">Rate</th>
                    <th class="text-right">CGST</th>
                    <th class="text-right">SGST</th>
                    <th class="text-right">Amount</th>
                </tr>
            </thead>
            <tbody>
            <?php $sno=1; foreach ($lineItems as $li): ?>
                <tr>
                    <td><?= $sno++ ?></td>
                    <td><?= sanitize($li['description']) ?></td>
                    <td class="num"><?= rtrim(rtrim(number_format($li['qty'],2),'0'),'.') ?></td>
                    <td class="num mono"><?= formatMoney($li['unit_price']) ?></td>
                    <td class="num mono"><?= formatMoney($li['line_cgst']) ?> <span class="text-faint">(<?= number_format($li['cgst_percent'],1) ?>%)</span></td>
                    <td class="num mono"><?= formatMoney($li['line_sgst']) ?> <span class="text-faint">(<?= number_format($li['sgst_percent'],1) ?>%)</span></td>
                    <td class="num mono"><strong><?= formatMoney($li['line_total']) ?></strong></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="flex-end mt-16">
        <div style="width:280px;">
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">Subtotal</span>
                <strong class="mono"><?= formatMoney($inv['subtotal']) ?></strong>
            </div>
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">CGST</span>
                <strong class="mono"><?= formatMoney($inv['cgst_amount']) ?></strong>
            </div>
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">SGST</span>
                <strong class="mono"><?= formatMoney($inv['sgst_amount']) ?></strong>
            </div>
            <div class="divider" style="margin:8px 0;"></div>
            <div class="flex-between" style="padding:4px 0;">
                <span style="font-weight:700; font-size:15px;">Grand Total</span>
                <strong class="mono" style="font-size:18px; color:var(--color-primary);"><?= formatMoney($inv['grand_total']) ?></strong>
            </div>
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">Paid</span>
                <strong class="mono text-success"><?= formatMoney($inv['paid_amount']) ?></strong>
            </div>
            <?php if ($inv['tds_amount'] > 0): ?>
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">TDS Deducted</span>
                <strong class="mono"><?= formatMoney($inv['tds_amount']) ?></strong>
            </div>
            <?php endif; ?>
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">Balance Due</span>
                <strong class="mono <?= $balance>0?'text-danger':'' ?>"><?= formatMoney($balance) ?></strong>
            </div>
        </div>
    </div>

    <?php if ($inv['notes']): ?>
    <div class="divider"></div>
    <div>
        <strong class="text-sm">Notes:</strong>
        <div class="text-sm text-muted"><?= nl2br(sanitize($inv['notes'])) ?></div>
    </div>
    <?php endif; ?>

    <div class="divider"></div>
    <div class="text-sm text-faint">Thank you for your business. This is a computer-generated invoice.</div>
</div>

<!-- Payment Modal -->
<div class="modal-backdrop" id="paymentModal">
    <div class="modal">
        <div class="modal-header">
            <h2>Mark Payment Received</h2>
            <button class="btn btn-icon" onclick="document.getElementById('paymentModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="mark_paid">

            <div class="form-group">
                <label>Amount Received <span class="req">*</span></label>
                <input type="number" step="0.01" name="paid_amount" id="quickPayAmount" value="<?= number_format($balance,2,'.','') ?>" oninput="recalcQuickPay()" required>
                <div class="text-sm text-faint">Balance due: <?= formatMoney($balance) ?>. Enter full amount to mark as PAID and release stock as sold.</div>
            </div>
            <div class="form-group">
                <label>TDS Deducted (if any)</label>
                <input type="number" step="0.01" name="tds_amount" id="quickPayTds" value="0" oninput="recalcQuickPay()">
                <div class="text-sm text-faint">Tax Deducted at Source by the customer - counts toward settlement.</div>
            </div>
            <div class="form-group">
                <label>Payment Date & Time <span class="req">*</span></label>
                <input type="datetime-local" name="payment_datetime" value="<?= date('Y-m-d\TH:i') ?>" required>
                <div class="text-sm text-faint">Choose the date/time payment was actually received (for cash flow records).</div>
            </div>
            <div class="form-group">
                <label>Payment Mode <span class="req">*</span></label>
                <select name="payment_mode" required>
                    <option value="Cash">Cash</option>
                    <option value="Bank Transfer">Bank Transfer</option>
                    <option value="UPI">UPI</option>
                    <option value="Cheque">Cheque</option>
                    <option value="Card">Card</option>
                </select>
            </div>
            <?php if ($bankAccounts): ?>
            <div class="form-group">
                <label>Received Into Account <span class="req">*</span></label>
                <select name="bank_account_id" required>
                    <option value="">-- Select Account --</option>
                    <?php foreach ($bankAccounts as $ba): ?>
                    <option value="<?= $ba['id'] ?>"><?= sanitize($ba['account_name']) ?> (<?= formatMoney($ba['current_balance']) ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <div style="background:var(--color-surface-2);border-radius:var(--radius-md);padding:10px 12px;margin-bottom:12px;">
                <div class="flex-between"><span class="text-sm text-muted">Remaining balance after this</span><strong class="mono" id="quickRemain"><?= formatMoney(0) ?></strong></div>
            </div>
            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="document.getElementById('paymentModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-success"><?= icon('check') ?> Confirm Payment</button>
            </div>
        </form>
    </div>
</div>
<script>
function recalcQuickPay() {
    const balance = <?= $balance ?>;
    const amt = parseFloat(document.getElementById('quickPayAmount').value) || 0;
    const tds = parseFloat(document.getElementById('quickPayTds').value) || 0;
    const remain = Math.max(0, balance - amt - tds);
    document.getElementById('quickRemain').textContent = '₹' + remain.toFixed(2);
}
recalcQuickPay();
</script>

<div class="card" style="max-width:850px; margin:20px auto 0;">
    <div class="card-title flex-between">
        <span>Payment History</span>
        <a href="../payments/payments.php?customer_id=<?= $inv['customer_id'] ?>&invoice_id=<?= $id ?>" class="btn btn-sm"><?= icon('cash') ?> Open in Payments Tab</a>
    </div>
    <?php if ($paymentHistory): ?>
    <div class="table-wrap">
        <table>
            <thead><tr><th>Date/Time</th><th class="text-right">Amount</th><th class="text-right">TDS</th><th>Mode</th><th>Marked By</th></tr></thead>
            <tbody>
            <?php foreach ($paymentHistory as $p): ?>
            <tr>
                <td><?= formatDateTime($p['payment_date']) ?></td>
                <td class="num text-success"><?= formatMoney($p['amount']) ?></td>
                <td class="num"><?= formatMoney($p['tds_amount']) ?></td>
                <td><?= sanitize($p['payment_mode']) ?></td>
                <td><?= sanitize($p['marked_by_name']) ?: '-' ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('history') ?> No payments recorded yet.</div>
    <?php endif; ?>
</div>

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