<?php
require_once '../../includes/header.php';
require_once '../../classes/ApiIntegrationService.php';
require_once '../../classes/DocumentImportService.php';
require_once '../../classes/Suppliers.php';
require_once '../../classes/Branch.php';

if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}

$documentImportService = new DocumentImportService($conn);
$integrations = array_values(array_filter(
    ApiIntegrationService::listAccounts($conn),
    function ($row) { return !empty($row['is_enabled']) && !empty($row['has_key']); }
));
$suppliers = (new Suppliers($conn))->getSuppliers('active');
$branchStmt = (new Branch($conn))->getAllBranches();
$branches = $branchStmt->fetchAll(PDO::FETCH_ASSOC);
$imports = $documentImportService->listImports();
?>

<style>
    .di-card { border: 1px solid #dfe6f0; border-radius: 14px; background: #fff; box-shadow: 0 8px 28px rgba(15,23,42,.05); margin-bottom: 24px; }
    .di-card-header { padding: 16px 22px; border-bottom: 1px solid #eef1f6; }
    .di-card-header h5 { margin: 0; font-size: 1rem; font-weight: 700; }
    .di-card-body { padding: 20px 22px; }
    .di-preview { max-width: 100%; max-height: 420px; border: 1px solid #e2e8f0; border-radius: 8px; }
    .di-status-badge { text-transform: capitalize; }
    .di-fieldset { display: none; }
    .di-fieldset.active { display: block; }
    .di-item-row td { vertical-align: middle; }
</style>

<div class="container-fluid py-4">
    <h4 class="mb-4"><i class="fas fa-file-import"></i> AI Document Import</h4>

    <?php if (empty($integrations)): ?>
        <div class="alert alert-warning">
            No enabled AI integration with a stored API key was found. Add or enable one under
            <a href="settings.php#api-settings">Settings &gt; API Integrations</a> before uploading documents.
        </div>
    <?php endif; ?>

    <div class="di-card">
        <div class="di-card-header"><h5><i class="fas fa-upload"></i> Upload a Document</h5></div>
        <div class="di-card-body">
            <form id="uploadForm">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">File (JPG, PNG, WEBP, or PDF)</label>
                        <input type="file" class="form-control" name="document" id="documentFile" accept=".jpg,.jpeg,.png,.webp,.pdf" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Document Type</label>
                        <select class="form-select" name="doc_type_hint" id="docTypeHint">
                            <?php foreach (DocumentImportService::DOC_TYPE_LABELS as $key => $label): ?>
                                <option value="<?php echo htmlspecialchars($key); ?>"><?php echo htmlspecialchars($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">AI Integration</label>
                        <select class="form-select" name="integration_id" id="integrationId" <?php echo empty($integrations) ? 'disabled' : ''; ?>>
                            <?php foreach ($integrations as $integration): ?>
                                <option value="<?php echo (int)$integration['integration_id']; ?>">
                                    <?php echo htmlspecialchars($integration['provider_label']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Branch</label>
                        <select class="form-select" name="branch_id" id="uploadBranchId">
                            <option value="">&mdash;</option>
                            <?php foreach ($branches as $branch): ?>
                                <option value="<?php echo (int)$branch['branch_id']; ?>"><?php echo htmlspecialchars($branch['branch_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary mt-3" id="uploadBtn" <?php echo empty($integrations) ? 'disabled' : ''; ?>>
                    <i class="fas fa-magic"></i> Upload &amp; Analyze
                </button>
                <span id="uploadStatus" class="ms-2 text-muted"></span>
            </form>
        </div>
    </div>

    <div class="di-card">
        <div class="di-card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-list"></i> Imports</h5>
            <button type="button" class="btn btn-sm btn-outline-secondary" id="refreshBtn"><i class="fas fa-sync"></i> Refresh</button>
        </div>
        <div class="di-card-body">
            <div class="table-responsive">
                <table class="table table-sm table-hover align-middle" id="importsTable">
                    <thead>
                        <tr>
                            <th>File</th>
                            <th>Doc Type</th>
                            <th>Status</th>
                            <th>Uploaded</th>
                            <th>By</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody id="importsTableBody"></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="reviewModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-search"></i> Review Extracted Document</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="reviewError" class="alert alert-danger d-none"></div>
                <div class="row">
                    <div class="col-md-5">
                        <div id="reviewPreviewContainer"></div>
                    </div>
                    <div class="col-md-7">
                        <form id="reviewForm">
                            <input type="hidden" name="import_id" id="reviewImportId">
                            <div class="mb-3">
                                <label class="form-label">Create record as</label>
                                <select class="form-select" id="targetModule" name="target_module">
                                    <option value="supplier_invoice">Supplier Invoice</option>
                                    <option value="quotation">Quotation</option>
                                    <option value="deposit">Bank Deposit</option>
                                    <option value="receipt">Receipt / Proof of Payment (reference only)</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Branch</label>
                                <select class="form-select" name="branch_id" id="reviewBranchId">
                                    <?php foreach ($branches as $branch): ?>
                                        <option value="<?php echo (int)$branch['branch_id']; ?>"><?php echo htmlspecialchars($branch['branch_name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <fieldset class="di-fieldset" data-module="supplier_invoice">
                                <p class="text-muted small">AI-detected supplier name: <span id="aiSupplierNameHint">&mdash;</span></p>
                                <div class="mb-3">
                                    <label class="form-label">Supplier</label>
                                    <select class="form-select" name="supplier_id">
                                        <option value="">Select supplier&hellip;</option>
                                        <?php foreach ($suppliers as $supplier): ?>
                                            <option value="<?php echo (int)$supplier['supplier_id']; ?>"><?php echo htmlspecialchars($supplier['supplier_name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </fieldset>

                            <fieldset class="di-fieldset" data-module="quotation">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Customer Name</label>
                                        <input type="text" class="form-control" name="customer_name">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Customer Contact</label>
                                        <input type="text" class="form-control" name="customer_contact">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Validity (days)</label>
                                        <input type="number" class="form-control" name="validity_days" value="30">
                                    </div>
                                </div>
                                <label class="form-label">Line Items</label>
                                <table class="table table-sm" id="lineItemsTable">
                                    <thead><tr><th>Item</th><th style="width:90px;">Qty</th><th style="width:130px;">Unit Price</th><th></th></tr></thead>
                                    <tbody id="lineItemsBody"></tbody>
                                </table>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="addLineItemBtn"><i class="fas fa-plus"></i> Add Item</button>
                            </fieldset>

                            <fieldset class="di-fieldset" data-module="deposit">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Bank Name</label>
                                        <input type="text" class="form-control" name="bank_name">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Account / Reference</label>
                                        <input type="text" class="form-control" name="account_reference">
                                    </div>
                                </div>
                            </fieldset>

                            <fieldset class="di-fieldset" data-module="receipt">
                                <div class="mb-3">
                                    <label class="form-label">Reference (e.g. Order #123, Laybuy LB-045)</label>
                                    <input type="text" class="form-control" name="receipt_reference" placeholder="What does this receipt prove payment for?">
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Payer</label>
                                        <input type="text" class="form-control" name="payer_name">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Payment Method</label>
                                        <input type="text" class="form-control" name="payment_method">
                                    </div>
                                </div>
                            </fieldset>

                            <div class="row mt-2">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Document Date</label>
                                    <input type="date" class="form-control" name="document_date">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Document Number</label>
                                    <input type="text" class="form-control" name="document_number">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Total Amount</label>
                                    <input type="number" step="0.01" class="form-control" name="total">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Subtotal</label>
                                    <input type="number" step="0.01" class="form-control" name="subtotal">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Tax</label>
                                    <input type="number" step="0.01" class="form-control" name="tax">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Notes</label>
                                <textarea class="form-control" name="notes" rows="2"></textarea>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-danger me-auto" id="rejectBtn"><i class="fas fa-times"></i> Reject</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="confirmBtn"><i class="fas fa-check"></i> Create Record</button>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const AI_TO_MODULE = { supplier_invoice: 'supplier_invoice', quotation: 'quotation', bank_deposit: 'deposit', receipt: 'receipt', unknown: 'quotation' };
    const reviewModalEl = document.getElementById('reviewModal');
    const reviewModal = new bootstrap.Modal(reviewModalEl);
    let currentImportId = null;

    function statusBadgeClass(status) {
        return {
            uploaded: 'bg-secondary', processing: 'bg-info', extracted: 'bg-primary',
            failed: 'bg-danger', confirmed: 'bg-success', rejected: 'bg-dark',
        }[status] || 'bg-secondary';
    }

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str == null ? '' : String(str);
        return div.innerHTML;
    }

    function renderTable(imports) {
        const body = document.getElementById('importsTableBody');
        if (!imports.length) {
            body.innerHTML = '<tr><td colspan="6" class="text-muted text-center">No documents uploaded yet.</td></tr>';
            return;
        }
        body.innerHTML = imports.map(function (row) {
            const canReview = row.status === 'extracted' || row.status === 'failed';
            const canDelete = row.status !== 'confirmed';
            return '<tr>' +
                '<td><a href="/IMS/uploads/document_imports/' + encodeURIComponent(row.stored_filename) + '" target="_blank">' + escapeHtml(row.original_filename) + '</a></td>' +
                '<td>' + escapeHtml(row.detected_doc_type || row.doc_type_hint) + '</td>' +
                '<td><span class="badge di-status-badge ' + statusBadgeClass(row.status) + '">' + escapeHtml(row.status) + '</span></td>' +
                '<td>' + escapeHtml(row.created_at) + '</td>' +
                '<td>' + escapeHtml(row.uploaded_by_name) + '</td>' +
                '<td>' +
                    (canReview ? '<button class="btn btn-sm btn-outline-primary me-1 review-btn" data-id="' + row.import_id + '"><i class="fas fa-search"></i> Review</button>' : '') +
                    (canDelete ? '<button class="btn btn-sm btn-outline-danger delete-btn" data-id="' + row.import_id + '"><i class="fas fa-trash"></i></button>' : '') +
                '</td>' +
            '</tr>';
        }).join('');

        body.querySelectorAll('.review-btn').forEach(function (btn) {
            btn.addEventListener('click', function () { openReview(btn.dataset.id); });
        });
        body.querySelectorAll('.delete-btn').forEach(function (btn) {
            btn.addEventListener('click', function () { deleteImport(btn.dataset.id); });
        });
    }

    function refreshList() {
        fetch('/IMS/ajax/admin/document_imports_list.php').then(function (r) { return r.json(); }).then(function (data) {
            if (data.success) renderTable(data.imports);
        });
    }

    function deleteImport(importId) {
        if (!confirm('Delete this upload?')) return;
        const form = new URLSearchParams({ action: 'delete', import_id: importId });
        fetch('/IMS/ajax/admin/document_import_action.php', { method: 'POST', body: form }).then(function (r) { return r.json(); }).then(function (data) {
            if (!data.success) { alert(data.message || 'Unable to delete.'); return; }
            refreshList();
        });
    }

    function setFieldsetVisibility(module) {
        document.querySelectorAll('.di-fieldset').forEach(function (fs) {
            fs.classList.toggle('active', fs.dataset.module === module);
        });
    }

    function addLineItemRow(item) {
        item = item || {};
        const tr = document.createElement('tr');
        tr.className = 'di-item-row';
        tr.innerHTML =
            '<td><input type="text" class="form-control form-control-sm" name="item_name[]" value="' + escapeHtml(item.item_name) + '"></td>' +
            '<td><input type="number" class="form-control form-control-sm" name="item_qty[]" value="' + escapeHtml(item.qty != null ? item.qty : 1) + '"></td>' +
            '<td><input type="number" step="0.01" class="form-control form-control-sm" name="item_unit_price[]" value="' + escapeHtml(item.unit_price != null ? item.unit_price : '') + '"></td>' +
            '<td><button type="button" class="btn btn-sm btn-outline-danger remove-row-btn"><i class="fas fa-times"></i></button></td>';
        tr.querySelector('.remove-row-btn').addEventListener('click', function () { tr.remove(); });
        document.getElementById('lineItemsBody').appendChild(tr);
    }

    function populateForm(data) {
        data = data || {};
        const form = document.getElementById('reviewForm');
        ['customer_name', 'customer_contact', 'document_number', 'document_date', 'due_date',
         'subtotal', 'tax', 'total', 'bank_name', 'account_reference', 'notes',
         'payer_name', 'payment_method'].forEach(function (name) {
            const el = form.querySelector('[name="' + name + '"]');
            if (el && data[name] != null) el.value = data[name];
        });
        document.getElementById('aiSupplierNameHint').textContent = data.supplier_name || '—';

        document.getElementById('lineItemsBody').innerHTML = '';
        (data.line_items || []).forEach(addLineItemRow);
        if (!(data.line_items || []).length) addLineItemRow({});
    }

    function openReview(importId) {
        currentImportId = importId;
        document.getElementById('reviewImportId').value = importId;
        document.getElementById('reviewError').classList.add('d-none');
        document.getElementById('reviewForm').reset();
        document.getElementById('lineItemsBody').innerHTML = '';
        document.getElementById('reviewPreviewContainer').innerHTML = '<div class="text-muted">Loading…</div>';

        fetch('/IMS/ajax/admin/document_imports_list.php?import_id=' + encodeURIComponent(importId))
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (!data.success) { alert(data.message || 'Unable to load import.'); return; }
                const row = data.import;
                const fileUrl = '/IMS/uploads/document_imports/' + encodeURIComponent(row.stored_filename);
                document.getElementById('reviewPreviewContainer').innerHTML = row.mime_type === 'application/pdf'
                    ? '<a href="' + fileUrl + '" target="_blank" class="btn btn-outline-secondary"><i class="fas fa-file-pdf"></i> Open PDF</a>'
                    : '<img src="' + fileUrl + '" class="di-preview">';

                const module = AI_TO_MODULE[row.detected_doc_type] || 'quotation';
                document.getElementById('targetModule').value = module;
                setFieldsetVisibility(module);
                if (row.branch_id) {
                    document.getElementById('reviewBranchId').value = row.branch_id;
                }

                if (row.status === 'failed') {
                    document.getElementById('reviewError').textContent = row.error_message || 'AI extraction failed. Fill in the fields manually below.';
                    document.getElementById('reviewError').classList.remove('d-none');
                }

                populateForm(row.extracted_data);
                reviewModal.show();
            });
    }

    document.getElementById('targetModule').addEventListener('change', function () {
        setFieldsetVisibility(this.value);
    });
    document.getElementById('addLineItemBtn').addEventListener('click', function () { addLineItemRow({}); });

    document.getElementById('uploadForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const status = document.getElementById('uploadStatus');
        const btn = document.getElementById('uploadBtn');
        const fileInput = document.getElementById('documentFile');
        if (!fileInput.files.length) return;

        btn.disabled = true;
        status.textContent = 'Uploading…';

        const formData = new FormData(this);
        fetch('/IMS/ajax/admin/document_import_upload.php', { method: 'POST', body: formData })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (!data.success) { status.textContent = ''; alert(data.message || 'Upload failed.'); btn.disabled = false; return; }
                status.textContent = 'Analyzing with AI…';
                refreshList();
                return fetch('/IMS/ajax/admin/document_import_process.php', {
                    method: 'POST', body: new URLSearchParams({ import_id: data.import_id })
                }).then(function (r) { return r.json(); }).then(function (result) {
                    status.textContent = '';
                    btn.disabled = false;
                    fileInput.value = '';
                    refreshList();
                    if (!result.success) {
                        alert('AI extraction failed: ' + (result.message || 'unknown error') + '\nYou can still review and fill the record manually.');
                    }
                    openReview(data.import_id);
                });
            })
            .catch(function () { status.textContent = ''; btn.disabled = false; alert('Unexpected error during upload.'); });
    });

    document.getElementById('rejectBtn').addEventListener('click', function () {
        if (!confirm('Reject this import? No record will be created.')) return;
        const form = new URLSearchParams({ action: 'reject', import_id: currentImportId });
        fetch('/IMS/ajax/admin/document_import_action.php', { method: 'POST', body: form }).then(function (r) { return r.json(); }).then(function (data) {
            if (!data.success) { alert(data.message || 'Unable to reject.'); return; }
            reviewModal.hide();
            refreshList();
        });
    });

    document.getElementById('confirmBtn').addEventListener('click', function () {
        const form = document.getElementById('reviewForm');
        const params = new URLSearchParams(new FormData(form));
        params.set('action', 'confirm');
        fetch('/IMS/ajax/admin/document_import_action.php', { method: 'POST', body: params })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (!data.success) { alert(data.message || 'Unable to create record.'); return; }
                reviewModal.hide();
                refreshList();
                alert('Record created successfully.');
            });
    });

    document.getElementById('refreshBtn').addEventListener('click', refreshList);

    renderTable(<?php echo json_encode(array_map(function ($row) {
        unset($row['extracted_data'], $row['ai_raw_response']);
        return $row;
    }, $imports)); ?>);
})();
</script>

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