<?php
require_once __DIR__ . '/../../classes/ServiceModule.php';
require_once __DIR__ . '/../../classes/Branch.php';
include '../../includes/header.php';

$serviceModule = new ServiceModule($conn, new Logger($conn, $_SESSION['user_id'], $_SESSION['username'] ?? '', $_SESSION['role'] ?? ''));
$branchModel = new Branch($conn);
$currentRole = strtolower((string)($_SESSION['role'] ?? ''));
$canSeeAll = in_array($currentRole, ['admin', 'super_admin', 'controller'], true) || $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);
$selectedBranchId = $canSeeAll && isset($_GET['branch_id']) && $_GET['branch_id'] !== '' ? (int)$_GET['branch_id'] : ($canSeeAll ? null : (int)$userBranchId);
$catalogBranchId = $selectedBranchId ?: $userBranchId;
$catalog = $serviceModule->serviceCatalog($catalogBranchId ?: null);
$warehouseInventory = $serviceModule->warehouseInventoryCatalog();
$invoices = $serviceModule->listInvoices($selectedBranchId, 150);
$branches = [];
if ($canSeeAll) {
    $branchStmt = $branchModel->getAllBranches();
    $branches = $branchStmt ? $branchStmt->fetchAll(PDO::FETCH_ASSOC) : [];
}
$selectedInvoice = isset($_GET['invoice_id']) ? $serviceModule->getInvoice((int)$_GET['invoice_id']) : null;
$type = strtolower(trim((string)($_GET['type'] ?? 'repair')));
if (!in_array($type, ['repair', 'diagnostics', 'installation', 'maintenance', 'software', 'warranty', 'other'], true)) {
    $type = 'repair';
}
$typeLabels = [
    'repair' => 'Repair',
    'diagnostics' => 'Diagnostics',
    'installation' => 'Installation / Setup',
    'maintenance' => 'Maintenance',
    'software' => 'Software Service',
    'warranty' => 'Warranty Service',
    'other' => 'Other Service',
];
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h2 class="mb-1">Repairs & Other Services</h2>
        <p class="text-muted mb-0">Record job-card details, service charges, parts used from EIS warehouse inventory, and queue MRA EIS receipts.</p>
    </div>
    <a href="/IMS/views/admin/mra_eis_site_products.php" class="btn btn-outline-success"><i class="fas fa-cloud-download-alt"></i> EIS Warehouse Inventory</a>
</div>

<?php if (isset($_GET['success'])): ?><div class="alert alert-success"><?php echo htmlspecialchars($_GET['success']); ?></div><?php endif; ?>
<?php if (isset($_GET['error'])): ?><div class="alert alert-danger"><?php echo htmlspecialchars($_GET['error']); ?></div><?php endif; ?>

<div class="btn-group mb-3" role="group">
    <?php foreach ($typeLabels as $value => $label): ?>
        <a class="btn btn-sm <?php echo $type === $value ? 'btn-primary' : 'btn-outline-primary'; ?>" href="?type=<?php echo urlencode($value); ?><?php echo $selectedBranchId ? '&branch_id=' . (int)$selectedBranchId : ''; ?>"><?php echo htmlspecialchars($label); ?></a>
    <?php endforeach; ?>
</div>

<?php if ($canSeeAll): ?>
<form method="get" class="card card-body mb-3">
    <input type="hidden" name="type" value="<?php echo htmlspecialchars($type); ?>">
    <div class="row align-items-end">
        <div class="col-md-4">
            <label class="form-label">Branch</label>
            <select name="branch_id" class="form-control">
                <option value="">All branches</option>
                <?php foreach ($branches as $branch): ?>
                    <option value="<?php echo (int)$branch['branch_id']; ?>" <?php echo (string)$selectedBranchId === (string)$branch['branch_id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($branch['branch_name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2"><button class="btn btn-primary btn-block">Filter</button></div>
    </div>
</form>
<?php endif; ?>

<div class="card mb-4">
    <div class="card-header"><strong>Record <?php echo htmlspecialchars($typeLabels[$type]); ?> Transaction</strong></div>
    <div class="card-body">
        <?php if (!$catalog): ?><div class="alert alert-warning">No MRA EIS service products were found for this branch. Download approved site services first, or enter an MRA service code manually.</div><?php endif; ?>
        <?php if (!$warehouseInventory): ?><div class="alert alert-info">No EIS warehouse product inventory was found. Parts can still be entered manually, but MRA product codes should be downloaded or mapped first.</div><?php endif; ?>
        <form method="post" action="action.php" id="serviceForm">
            <input type="hidden" name="action" value="create_invoice">
            <input type="hidden" name="service_type" value="<?php echo htmlspecialchars($type); ?>">
            <div class="row">
                <div class="col-md-3 mb-2">
                    <label class="form-label">Branch</label>
                    <?php if ($canSeeAll): ?>
                        <select name="branch_id" class="form-control" required>
                            <?php foreach ($branches as $branch): ?>
                                <option value="<?php echo (int)$branch['branch_id']; ?>" <?php echo (string)($selectedBranchId ?: $userBranchId) === (string)$branch['branch_id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($branch['branch_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php else: ?>
                        <input type="hidden" name="branch_id" value="<?php echo (int)$userBranchId; ?>">
                        <input class="form-control" value="<?php echo htmlspecialchars($branchName); ?>" disabled>
                    <?php endif; ?>
                </div>
                <div class="col-md-3 mb-2"><label class="form-label">Customer</label><input name="customer_name" class="form-control" required></div>
                <div class="col-md-2 mb-2"><label class="form-label">Phone</label><input name="customer_phone" class="form-control"></div>
                <div class="col-md-2 mb-2"><label class="form-label">Buyer TIN</label><input name="buyer_tin" class="form-control"></div>
                <div class="col-md-2 mb-2"><label class="form-label">Payment</label><select name="payment_method" class="form-control"><?php echo paymentMethodSelectOptions('cash'); ?></select></div>
            </div>
            <div class="row">
                <div class="col-md-2 mb-2"><label class="form-label">Device</label><input name="device_type" class="form-control" placeholder="Laptop, printer, desktop"></div>
                <div class="col-md-2 mb-2"><label class="form-label">Brand</label><input name="device_brand" class="form-control" placeholder="HP, Dell, Lenovo"></div>
                <div class="col-md-2 mb-2"><label class="form-label">Model</label><input name="device_model" class="form-control"></div>
                <div class="col-md-2 mb-2"><label class="form-label">Serial / Asset No.</label><input name="serial_number" class="form-control"></div>
                <div class="col-md-2 mb-2"><label class="form-label">Repair Status</label><select name="repair_status" class="form-control"><option value="received">Received</option><option value="diagnosing">Diagnosing</option><option value="waiting_parts">Waiting Parts</option><option value="repairing">Repairing</option><option value="ready">Ready</option><option value="collected">Collected</option><option value="cancelled">Cancelled</option></select></div>
                <div class="col-md-2 mb-2"><label class="form-label">Warranty</label><select name="warranty_status" class="form-control"><option value="out_of_warranty">Out of warranty</option><option value="under_warranty">Under warranty</option><option value="warranty_claim">Warranty claim</option><option value="internal">Internal</option></select></div>
            </div>
            <div class="row">
                <div class="col-md-4 mb-2"><label class="form-label">Reported Fault / Request</label><input name="reported_fault" class="form-control" placeholder="No display, OS install, keyboard replacement..."></div>
                <div class="col-md-4 mb-2"><label class="form-label">Diagnosis / Work Done</label><input name="diagnosis" class="form-control"></div>
                <div class="col-md-4 mb-2"><label class="form-label">Technician</label><input name="technician_name" class="form-control"></div>
            </div>
            <div class="table-responsive mt-3">
                <table class="table table-sm table-bordered" id="serviceLines">
                    <thead><tr><th>Type</th><th>Service / Warehouse Part</th><th>Code</th><th>Description</th><th>Qty</th><th>Unit Price</th><th>Discount</th><th></th></tr></thead>
                    <tbody>
                        <tr>
                            <td><select name="line_type[]" class="form-control form-control-sm line-type"><option value="service">Service</option><option value="part">Part</option><option value="consumable">Consumable</option></select></td>
                            <td>
                                <select name="site_product_id[]" class="form-control form-control-sm item-select">
                                    <option value="">Manual line</option>
                                    <optgroup label="EIS Services">
                                    <?php foreach ($catalog as $service): ?>
                                        <option value="<?php echo (int)$service['id']; ?>" data-kind="service" data-code="<?php echo htmlspecialchars($service['product_code']); ?>" data-name="<?php echo htmlspecialchars($service['product_name']); ?>" data-price="<?php echo htmlspecialchars($service['price']); ?>"><?php echo htmlspecialchars($service['product_name'] . ' (' . $service['product_code'] . ')'); ?></option>
                                    <?php endforeach; ?>
                                    </optgroup>
                                    <optgroup label="EIS Warehouse Parts">
                                    <?php foreach ($warehouseInventory as $part): ?>
                                        <option value="<?php echo (int)$part['id']; ?>" data-kind="part" data-code="<?php echo htmlspecialchars($part['product_code']); ?>" data-name="<?php echo htmlspecialchars($part['product_name']); ?>" data-price="<?php echo htmlspecialchars($part['price']); ?>"><?php echo htmlspecialchars($part['product_name'] . ' (' . $part['product_code'] . ')'); ?></option>
                                    <?php endforeach; ?>
                                    </optgroup>
                                </select>
                                <input name="service_name[]" class="form-control form-control-sm mt-1 service-name" placeholder="Service or part name">
                            </td>
                            <td><input name="product_code[]" class="form-control form-control-sm product-code" placeholder="MRA code"></td>
                            <td><input name="description[]" class="form-control form-control-sm" placeholder="Labour, parts, diagnosis, installation..."></td>
                            <td><input type="number" min="0.01" step="0.01" name="quantity[]" class="form-control form-control-sm" value="1"></td>
                            <td><input type="number" min="0" step="0.01" name="unit_price[]" class="form-control form-control-sm unit-price" required></td>
                            <td><input type="number" min="0" step="0.01" name="discount_amount[]" class="form-control form-control-sm" value="0"></td>
                            <td><button type="button" class="btn btn-sm btn-outline-danger remove-line">Remove</button></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="row">
                <div class="col-md-9 mb-2"><label class="form-label">Notes</label><input name="notes" class="form-control" placeholder="Job card notes, customer approval, collection terms"></div>
                <div class="col-md-3 mb-2 d-flex align-items-end"><button class="btn btn-success btn-block"><i class="fas fa-save"></i> Save & Queue EIS</button></div>
            </div>
            <button type="button" class="btn btn-sm btn-outline-primary" id="addLine"><i class="fas fa-plus"></i> Add line</button>
        </form>
    </div>
</div>

<?php if ($selectedInvoice): ?>
<div class="card mb-4"><div class="card-header"><strong><?php echo htmlspecialchars($selectedInvoice['invoice_number']); ?></strong></div><div class="card-body">
    <div class="row mb-2"><div class="col-md-3"><strong>Customer:</strong> <?php echo htmlspecialchars($selectedInvoice['customer_name']); ?></div><div class="col-md-3"><strong>Branch:</strong> <?php echo htmlspecialchars($selectedInvoice['branch_name'] ?? ''); ?></div><div class="col-md-3"><strong>Total:</strong> <?php echo number_format((float)$selectedInvoice['total_amount'], 2); ?></div><div class="col-md-3"><strong>EIS:</strong> <?php echo htmlspecialchars($selectedInvoice['eis_status'] ?? 'not queued'); ?></div></div>
    <div class="row mb-2"><div class="col-md-3"><strong>Type:</strong> <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $selectedInvoice['service_type'] ?? 'service'))); ?></div><div class="col-md-3"><strong>Device:</strong> <?php echo htmlspecialchars(trim(($selectedInvoice['device_brand'] ?? '') . ' ' . ($selectedInvoice['device_model'] ?? '')) ?: ($selectedInvoice['device_type'] ?? '')); ?></div><div class="col-md-3"><strong>Serial:</strong> <?php echo htmlspecialchars($selectedInvoice['serial_number'] ?? ''); ?></div><div class="col-md-3"><strong>Status:</strong> <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $selectedInvoice['repair_status'] ?? ''))); ?></div></div>
    <?php if (!empty($selectedInvoice['reported_fault'])): ?><p><strong>Reported fault:</strong> <?php echo htmlspecialchars($selectedInvoice['reported_fault']); ?></p><?php endif; ?>
    <?php if (!empty($selectedInvoice['diagnosis'])): ?><p><strong>Diagnosis / Work done:</strong> <?php echo htmlspecialchars($selectedInvoice['diagnosis']); ?></p><?php endif; ?>
    <?php if (!empty($selectedInvoice['last_error'])): ?><div class="alert alert-warning"><?php echo htmlspecialchars($selectedInvoice['last_error']); ?></div><?php endif; ?>
    <table class="table table-sm"><thead><tr><th>Type</th><th>Code</th><th>Description</th><th>Qty</th><th>Total</th><th>VAT</th></tr></thead><tbody><?php foreach ($selectedInvoice['lines'] as $line): ?><tr><td><?php echo htmlspecialchars(ucfirst($line['line_type'] ?? 'service')); ?></td><td><?php echo htmlspecialchars($line['product_code']); ?></td><td><?php echo htmlspecialchars($line['service_name']); ?></td><td><?php echo number_format((float)$line['quantity'], 2); ?></td><td><?php echo number_format((float)$line['line_total'], 2); ?></td><td><?php echo number_format((float)$line['vat_amount'], 2); ?></td></tr><?php endforeach; ?></tbody></table>
</div></div>
<?php endif; ?>

<div class="card"><div class="card-header"><strong>Recent Service / Repair Transactions</strong></div><div class="card-body table-responsive"><table class="table table-striped table-sm" id="servicesTable"><thead><tr><th>Invoice</th><th>Type</th><th>Branch</th><th>Customer</th><th>Device</th><th>Status</th><th>Total</th><th>EIS</th><th>Created</th><th></th></tr></thead><tbody>
<?php foreach ($invoices as $invoice): ?><tr><td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td><td><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $invoice['service_type'] ?? 'service'))); ?></td><td><?php echo htmlspecialchars($invoice['branch_name'] ?? $invoice['branch_id']); ?></td><td><?php echo htmlspecialchars($invoice['customer_name']); ?></td><td><?php echo htmlspecialchars(trim(($invoice['device_brand'] ?? '') . ' ' . ($invoice['device_model'] ?? '')) ?: ($invoice['device_type'] ?? '')); ?></td><td><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $invoice['repair_status'] ?? ''))); ?></td><td><?php echo number_format((float)$invoice['total_amount'], 2); ?></td><td><span class="badge bg-<?php echo ($invoice['eis_status'] ?? '') === 'ready' ? 'success' : (($invoice['eis_status'] ?? '') === 'blocked' ? 'warning' : 'secondary'); ?>"><?php echo htmlspecialchars($invoice['eis_status'] ?? 'not queued'); ?></span></td><td><?php echo htmlspecialchars($invoice['created_at']); ?></td><td><a class="btn btn-sm btn-outline-primary" href="?invoice_id=<?php echo (int)$invoice['service_invoice_id']; ?><?php echo $selectedBranchId ? '&branch_id=' . (int)$selectedBranchId : ''; ?><?php echo '&type=' . urlencode($type); ?>">View</a></td></tr><?php endforeach; ?>
</tbody></table></div></div>

<script>
(function() {
    var table = document.getElementById('serviceLines');
    document.getElementById('addLine').addEventListener('click', function() {
        var clone = table.querySelector('tbody tr').cloneNode(true);
        clone.querySelectorAll('input').forEach(function(input) { input.value = input.name.indexOf('quantity') === 0 ? '1' : (input.name.indexOf('discount') === 0 ? '0' : ''); });
        clone.querySelectorAll('select').forEach(function(select) { select.selectedIndex = 0; });
        table.querySelector('tbody').appendChild(clone);
    });
    table.addEventListener('click', function(e) { if (e.target.classList.contains('remove-line') && table.querySelectorAll('tbody tr').length > 1) e.target.closest('tr').remove(); });
    table.addEventListener('change', function(e) {
        if (!e.target.classList.contains('item-select')) return;
        var option = e.target.options[e.target.selectedIndex];
        var row = e.target.closest('tr');
        if (option && option.value) {
            row.querySelector('.product-code').value = option.dataset.code || '';
            row.querySelector('.service-name').value = option.dataset.name || '';
            row.querySelector('.unit-price').value = option.dataset.price || '';
            row.querySelector('.line-type').value = option.dataset.kind === 'part' ? 'part' : 'service';
        }
    });
    if (window.DataTable) new DataTable('#servicesTable');
})();
</script>

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