<?php
ob_start();
require_once __DIR__ . '/../../classes/CustomerService.php';
require_once __DIR__ . '/../../classes/Logger.php';
include '../../includes/header.php';

$logger  = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$service = null;
$error   = '';
try {
    $service = new CustomerService($conn, $logger);
} catch (Throwable $e) {
    $error = 'Service error: ' . htmlspecialchars($e->getMessage());
}

$isAdmin      = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);
$isController = $auth->isController($_SESSION['user_id']);

if ($isController) {
    ob_end_clean();
    header('Location: index.php?error=' . urlencode('Controllers cannot create claims. Use the claim list to update delivery dates.'));
    exit;
}

$branchId = $isAdmin ? null : $auth->getUserBranch($_SESSION['user_id']);

$receiptNumber = trim($_POST['receipt_number'] ?? $_GET['receipt_number'] ?? '');
$sale = null;
if ($service && $receiptNumber !== '') {
    try {
        $sale = $service->findSaleByReceipt($receiptNumber, $branchId);
    } catch (Throwable $e) {
        $error = 'Receipt lookup failed: ' . htmlspecialchars($e->getMessage());
    }
}

// Preserve form values across a failed POST so the user doesn't lose their input
$fv = [
    'request_type'   => $_POST['request_type']   ?? 'claim',
    'priority'       => $_POST['priority']        ?? 'normal',
    'sale_id'        => (int)($_POST['sale_id']   ?? 0),
    'item_id'        => (int)($_POST['item_id']   ?? 0),
    'subject'        => $_POST['subject']         ?? '',
    'customer_email' => $_POST['customer_email']  ?? '',
    'delivery_date'  => $_POST['delivery_date']   ?? '',
    'description'    => $_POST['description']     ?? '',
];

if ($receiptNumber !== '' && !$sale && $error === '') {
    $error = 'No sale receipt found for that number. Check the transaction ID and try again.';
}

if ($service && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['submit_claim'] ?? '') === '1') {
    $subject     = trim($_POST['subject'] ?? '');
    $description = trim($_POST['description'] ?? '');
    // sale_id is the select value (PK of sold_items — always non-null).
    // item_id comes from a hidden field populated by JS; may be 0 when sold_items.item_id is NULL.
    $saleId = (int)($_POST['sale_id'] ?? 0);
    $itemId = (int)($_POST['item_id'] ?? 0) ?: null;

    if (!$sale) {
        $error = 'A valid sale receipt is required before opening a claim.';
    } elseif ($subject === '' || $description === '' || !$saleId) {
        $error = 'Please select an item and fill in the subject and description.';
    } else {
        try {
            $data = [
                'request_type'   => in_array($_POST['request_type'] ?? '', ['claim','warranty','service'], true)
                                        ? $_POST['request_type'] : 'claim',
                'priority'       => in_array($_POST['priority'] ?? '', ['low','normal','high','urgent'], true)
                                        ? $_POST['priority'] : 'normal',
                'receipt_number' => $receiptNumber,
                'branch_id'      => $sale['branch_id'],
                'item_id'        => $itemId,
                'sale_id'        => $saleId,
                'customer_name'  => $sale['customer_name'] ?: 'Receipt Customer',
                'customer_phone' => $sale['customer_phone'] ?: '',
                'customer_email' => trim($_POST['customer_email'] ?? ''),
                'delivery_date'  => trim($_POST['delivery_date'] ?? ''),
                'subject'        => $subject,
                'description'    => $description,
                'assigned_to'    => null,
                'created_by'     => $_SESSION['user_id'],
            ];
            $id = $service->createRequest($data);
            ob_end_clean();
            header('Location: index.php?request_id=' . $id . '&success=' . urlencode('Customer claim opened successfully.'));
            exit;
        } catch (Throwable $e) {
            $error = 'Failed to open claim: ' . htmlspecialchars($e->getMessage());
        }
    }
}
?>

<div class="container mt-4 mb-5">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h2 class="mb-1">New Customer Claim</h2>
            <p class="text-muted mb-0">Every claim must be linked to a sale receipt / transaction ID.</p>
        </div>
        <a href="index.php" class="btn btn-secondary">Back</a>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <!-- ── Step 1: Find receipt ── -->
    <div class="card mb-4">
        <div class="card-header"><strong><i class="fas fa-search me-1"></i> Step 1 — Find Sale Receipt</strong></div>
        <div class="card-body">

            <!-- Search mode toggle -->
            <ul class="nav nav-pills mb-3" id="searchModePills">
                <li class="nav-item me-1">
                    <button type="button" class="nav-link active" id="pillByReceipt">
                        <i class="fas fa-receipt me-1"></i> By Transaction ID
                    </button>
                </li>
                <li class="nav-item">
                    <button type="button" class="nav-link" id="pillByCustomer">
                        <i class="fas fa-user me-1"></i> By Customer Name
                    </button>
                </li>
            </ul>

            <!-- Panel 1: By transaction ID -->
            <div id="panelByReceipt">
                <div class="row g-2 align-items-end">
                    <div class="col-md-9">
                        <label class="form-label">Transaction ID / Receipt Number</label>
                        <input type="text" id="receiptSearchInput" class="form-control"
                               placeholder="e.g. TXN-69b1110d2ec50"
                               value="<?php echo htmlspecialchars($receiptNumber); ?>">
                    </div>
                    <div class="col-md-3">
                        <button type="button" id="findReceiptBtn" class="btn btn-primary w-100">
                            <i class="fas fa-search me-1"></i> Find Receipt
                        </button>
                    </div>
                </div>
            </div>

            <!-- Panel 2: By customer name / phone -->
            <div id="panelByCustomer" style="display:none">
                <div class="row g-2 align-items-end">
                    <div class="col-md-9">
                        <label class="form-label">Customer Name or Phone Number</label>
                        <input type="text" id="customerSearchInput" class="form-control"
                               placeholder="e.g. John Banda  or  +265 999...">
                    </div>
                    <div class="col-md-3">
                        <button type="button" id="customerSearchBtn" class="btn btn-primary w-100">
                            <i class="fas fa-user-check me-1"></i> Search
                        </button>
                    </div>
                </div>
                <div id="customerSearchResults" class="mt-3" style="display:none"></div>
            </div>

        </div>
    </div>

    <?php if ($sale): ?>

    <!-- ── Step 2: Receipt details ── -->
    <div class="card mb-4 border-success">
        <div class="card-header bg-success text-white"><strong><i class="fas fa-check-circle me-1"></i> Step 2 — Receipt Found</strong></div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Transaction</div>
                    <div class="fw-bold"><?php echo htmlspecialchars($sale['stored_transaction_id']); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Date</div>
                    <div><?php echo htmlspecialchars(date('d M Y H:i', strtotime($sale['sold_at']))); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Customer</div>
                    <div class="fw-bold"><?php echo htmlspecialchars($sale['customer_name'] ?: 'N/A'); ?></div>
                    <div class="text-muted small"><?php echo htmlspecialchars($sale['customer_phone'] ?: ''); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Branch</div>
                    <div><?php echo htmlspecialchars($sale['branch_name'] ?: 'N/A'); ?></div>
                    <div class="text-muted small"><?php echo count($sale['items']); ?> item(s) on this receipt</div>
                </div>
            </div>
        </div>
    </div>

    <!-- ── Step 3: Open claim ── -->
    <div class="card">
        <div class="card-header"><strong><i class="fas fa-clipboard-list me-1"></i> Step 3 — Open Claim</strong></div>
        <div class="card-body">
            <form method="POST" id="claimForm">
                <input type="hidden" name="submit_claim" value="1">
                <input type="hidden" name="receipt_number" value="<?php echo htmlspecialchars($receiptNumber); ?>">
                <!-- sale_id: submitted as the select's value (sold_items PK, always non-null) -->
                <!-- item_id: submitted from this hidden field, set by JS from data-item-id     -->
                <input type="hidden" name="item_id" id="claimItemId">

                <div class="row g-3">
                    <!-- Type, Priority, Delivery Date, Email -->
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Claim Type</label>
                        <select name="request_type" class="form-select">
                            <?php foreach (['claim' => 'Claim', 'warranty' => 'Warranty', 'service' => 'Service Request'] as $v => $l): ?>
                            <option value="<?php echo $v; ?>" <?php echo $fv['request_type'] === $v ? 'selected' : ''; ?>><?php echo $l; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Priority</label>
                        <select name="priority" class="form-select">
                            <?php foreach (['low' => 'Low', 'normal' => 'Normal', 'high' => 'High', 'urgent' => 'Urgent'] as $v => $l): ?>
                            <option value="<?php echo $v; ?>" <?php echo $fv['priority'] === $v ? 'selected' : ''; ?>><?php echo $l; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Expected Finish / Delivery Date <span class="text-muted fw-normal">(optional)</span></label>
                        <input type="date" name="delivery_date" class="form-control"
                               value="<?php echo htmlspecialchars($fv['delivery_date']); ?>"
                               min="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold">Customer Email <span class="text-muted fw-normal">(optional)</span></label>
                        <input type="email" name="customer_email" class="form-control"
                               value="<?php echo htmlspecialchars($fv['customer_email']); ?>"
                               placeholder="customer@email.com">
                    </div>

                    <!-- Item selector -->
                    <div class="col-12">
                        <label class="form-label fw-bold">Item Being Claimed <span class="text-danger">*</span></label>
                        <?php if (empty($sale['items'])): ?>
                            <div class="alert alert-warning mb-0">No items found on this receipt.</div>
                        <?php else: ?>
                        <select name="sale_id" id="claimSaleRowSelect" class="form-select" required>
                            <option value="">— Select item —</option>
                            <?php foreach ($sale['items'] as $item):
                                $optSaleId = (int)$item['sale_id'];
                                $optItemId = (int)($item['item_id'] ?? 0);
                                $label = trim(($item['unique_code'] ?? '') . ' — ' . ($item['item_name'] ?? 'Unknown item') . ' — ' . ($item['item_details'] ?? 'N/A'));
                                $label .= ' — MWK ' . number_format((float)$item['total_price'], 2);
                                if (!empty($item['warranty_months'])) {
                                    $label .= ' (warranty: ' . (int)$item['warranty_months'] . ' mo)';
                                }
                            ?>
                            <option value="<?php echo $optSaleId; ?>"
                                    data-item-id="<?php echo $optItemId; ?>"
                                    <?php echo $fv['sale_id'] === $optSaleId ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($label); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted">Select the specific item from this receipt that the claim is about.</small>
                        <?php endif; ?>
                    </div>

                    <!-- Subject -->
                    <div class="col-12">
                        <label class="form-label fw-bold">Claim Subject <span class="text-danger">*</span></label>
                        <input type="text" name="subject" class="form-control" required
                               maxlength="180"
                               placeholder="Brief summary of the claim"
                               value="<?php echo htmlspecialchars($fv['subject']); ?>">
                    </div>

                    <!-- Description -->
                    <div class="col-12">
                        <label class="form-label fw-bold">Claim Description <span class="text-danger">*</span></label>
                        <textarea name="description" rows="5" class="form-control" required
                                  placeholder="Describe the issue in detail — what happened, when, and what the customer expects."><?php echo htmlspecialchars($fv['description']); ?></textarea>
                    </div>

                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-1"></i> Open Claim
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php endif; ?>
</div>

<script>
(function () {

    // ── Tab / panel toggle ───────────────────────────────────────────────────
    var pillReceipt  = document.getElementById('pillByReceipt');
    var pillCustomer = document.getElementById('pillByCustomer');
    var panelReceipt = document.getElementById('panelByReceipt');
    var panelCustomer = document.getElementById('panelByCustomer');

    function showPanel(which) {
        if (which === 'receipt') {
            pillReceipt.classList.add('active');
            pillCustomer.classList.remove('active');
            panelReceipt.style.display  = '';
            panelCustomer.style.display = 'none';
        } else {
            pillCustomer.classList.add('active');
            pillReceipt.classList.remove('active');
            panelCustomer.style.display = '';
            panelReceipt.style.display  = 'none';
            document.getElementById('customerSearchInput').focus();
        }
    }

    pillReceipt.addEventListener('click',  function () { showPanel('receipt'); });
    pillCustomer.addEventListener('click', function () { showPanel('customer'); });

    // ── By-Transaction-ID search ─────────────────────────────────────────────
    var findBtn   = document.getElementById('findReceiptBtn');
    var searchInp = document.getElementById('receiptSearchInput');

    function doReceiptSearch() {
        var val = searchInp ? searchInp.value.trim() : '';
        if (!val) { if (searchInp) searchInp.focus(); return; }
        window.location.href = 'create.php?receipt_number=' + encodeURIComponent(val);
    }

    if (findBtn)   findBtn.addEventListener('click', doReceiptSearch);
    if (searchInp) {
        searchInp.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') { e.preventDefault(); doReceiptSearch(); }
        });
    }

    // ── By-Customer-Name search (AJAX) ───────────────────────────────────────
    var custBtn    = document.getElementById('customerSearchBtn');
    var custInp    = document.getElementById('customerSearchInput');
    var custResult = document.getElementById('customerSearchResults');

    function fmtDate(s) {
        if (!s) return '—';
        var d = new Date(s.replace(' ', 'T'));
        return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
    }

    function fmtMoney(v) {
        var n = parseFloat(v) || 0;
        return 'MWK ' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function selectReceipt(txnId) {
        // Switch to transaction-ID panel and load the receipt
        showPanel('receipt');
        if (searchInp) searchInp.value = txnId;
        window.location.href = 'create.php?receipt_number=' + encodeURIComponent(txnId);
    }

    function renderCustomerResults(results) {
        custResult.style.display = '';
        if (!results || results.length === 0) {
            custResult.innerHTML = '<div class="alert alert-warning mb-0">No sales found for that customer.</div>';
            return;
        }

        var rows = results.map(function (r) {
            return '<tr>' +
                '<td class="fw-bold">' + escHtml(r.customer_name || '—') + '</td>' +
                '<td>' + escHtml(r.customer_phone || '—') + '</td>' +
                '<td><span class="font-monospace small">' + escHtml(r.transaction_id) + '</span></td>' +
                '<td>' + fmtDate(r.sold_at) + '</td>' +
                '<td class="text-end">' + fmtMoney(r.total_amount) + '</td>' +
                '<td>' + escHtml(r.item_count) + '</td>' +
                '<td>' + escHtml(r.branch_name || '—') + '</td>' +
                '<td><button type="button" class="btn btn-sm btn-outline-primary cr-select-btn" ' +
                    'data-txn="' + escAttr(r.transaction_id) + '">' +
                    '<i class="fas fa-arrow-right me-1"></i>Select</button></td>' +
                '</tr>';
        }).join('');

        custResult.innerHTML =
            '<p class="text-muted small mb-2">' + results.length + ' receipt(s) found. Click <strong>Select</strong> to load the claim form.</p>' +
            '<div class="table-responsive">' +
            '<table class="table table-sm table-hover table-bordered align-middle mb-0">' +
            '<thead class="table-light"><tr>' +
            '<th>Customer</th><th>Phone</th><th>Transaction ID</th><th>Date</th>' +
            '<th class="text-end">Total</th><th>Items</th><th>Branch</th><th></th>' +
            '</tr></thead>' +
            '<tbody>' + rows + '</tbody>' +
            '</table></div>';

        // Attach click handlers to select buttons
        custResult.querySelectorAll('.cr-select-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                selectReceipt(this.dataset.txn);
            });
        });
    }

    function escHtml(s) {
        return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    }
    function escAttr(s) {
        return String(s).replace(/"/g,'&quot;').replace(/'/g,'&#39;');
    }

    function doCustomerSearch() {
        var q = custInp ? custInp.value.trim() : '';
        if (q.length < 2) {
            custResult.style.display = '';
            custResult.innerHTML = '<div class="alert alert-warning mb-0">Enter at least 2 characters.</div>';
            return;
        }

        custBtn.disabled = true;
        custBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Searching…';
        custResult.style.display = 'none';

        fetch('ajax_search.php?action=customer_search&q=' + encodeURIComponent(q))
            .then(function (r) { return r.json(); })
            .then(function (data) {
                custBtn.disabled = false;
                custBtn.innerHTML = '<i class="fas fa-user-check me-1"></i> Search';
                if (data.ok) {
                    renderCustomerResults(data.results);
                } else {
                    custResult.style.display = '';
                    custResult.innerHTML = '<div class="alert alert-danger mb-0">' + escHtml(data.error || 'Search failed.') + '</div>';
                }
            })
            .catch(function () {
                custBtn.disabled = false;
                custBtn.innerHTML = '<i class="fas fa-user-check me-1"></i> Search';
                custResult.style.display = '';
                custResult.innerHTML = '<div class="alert alert-danger mb-0">Request failed. Check your connection and try again.</div>';
            });
    }

    if (custBtn) custBtn.addEventListener('click', doCustomerSearch);
    if (custInp) {
        custInp.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') { e.preventDefault(); doCustomerSearch(); }
        });
    }

    // ── Claim item selector ──────────────────────────────────────────────────
    var sel       = document.getElementById('claimSaleRowSelect');
    var itemIdInp = document.getElementById('claimItemId');
    if (!sel || !itemIdInp) return;

    function syncFields() {
        var opt = sel.options[sel.selectedIndex];
        itemIdInp.value = (opt && opt.dataset.itemId) ? opt.dataset.itemId : '';
    }

    sel.addEventListener('change', syncFields);

    var realOpts = Array.from(sel.options).filter(function (o) { return o.value !== ''; });
    if (realOpts.length === 1) { sel.value = realOpts[0].value; }

    syncFields();

})();
</script>

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