<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('repair_management');

$pdo = getDB();
$user = currentUser();
$user_id = $user['id'];
$is_admin = in_array($user['role_name'], ['Super Admin', 'Admin']);

$job_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$job_id) { $_SESSION['error'] = 'Invalid job ID.'; header('Location: repair_jobs.php'); exit; }

$stmt = $pdo->prepare("
    SELECT rj.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address,
           u.name as technician_name, cr.name as created_by_name
    FROM repair_jobs rj
    LEFT JOIN customers c ON rj.customer_id = c.id
    LEFT JOIN users u ON rj.assigned_technician_id = u.id
    LEFT JOIN users cr ON rj.created_by = cr.id
    WHERE rj.id = ?
");
$stmt->execute([$job_id]);
$job = $stmt->fetch();
if (!$job) { $_SESSION['error'] = 'Job not found.'; header('Location: repair_jobs.php'); exit; }

// Load parts
$parts = $pdo->prepare("SELECT rjp.*, p.product_name, p.current_stock FROM repair_job_parts rjp JOIN products p ON rjp.product_id = p.id WHERE rjp.repair_job_id = ? ORDER BY rjp.created_at");
$parts->execute([$job_id]);
$parts = $parts->fetchAll();

// Load payments
$payments = $pdo->prepare("SELECT p.*, u.name as received_by_name FROM payments p LEFT JOIN users u ON p.received_by = u.id WHERE p.payment_type = 'repair' AND p.reference_id = ? ORDER BY p.created_at");
$payments->execute([$job_id]);
$payments = $payments->fetchAll();

// Load status history
$history = $pdo->prepare("SELECT h.*, u.name as changed_by_name FROM repair_job_status_history h LEFT JOIN users u ON h.changed_by = u.id WHERE h.repair_job_id = ? ORDER BY h.created_at DESC");
$history->execute([$job_id]);
$history = $history->fetchAll();

$has_edit_perm = $is_admin || hasPermission('repair_management');
$has_parts_perm = $is_admin || hasPermission('repair_parts_manage');
$has_payment_perm = $is_admin || hasPermission('repair_payment');
$has_invoice_perm = $is_admin || hasPermission('repair_invoice_view');
$is_delivered = $job['repair_status'] === 'Delivered';
$is_completed = $job['repair_status'] === 'Completed';
$is_cancelled = in_array($job['repair_status'], ['Cancelled', 'Cannot Repair']);

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-eye me-2"></i>Repair Job Details - <?= htmlspecialchars($job['job_no']) ?></h4>
            <div class="no-print">
                <?php if ($has_invoice_perm): ?>
                <a href="repair_invoice.php?id=<?= $job_id ?>" class="btn btn-sm btn-success"><i class="fas fa-file-invoice"></i> Invoice</a>
                <a href="print_repair_invoice.php?id=<?= $job_id ?>" class="btn btn-sm btn-secondary" target="_blank"><i class="fas fa-print"></i> Print</a>
                <?php endif; ?>
                <a href="repair_jobs.php" class="btn btn-sm btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <!-- Action Buttons -->
        <?php if (!$is_delivered && !$is_cancelled): ?>
        <div class="card no-print">
            <div class="card-body py-2">
                <div class="d-flex gap-2 flex-wrap">
                    <?php if ($has_edit_perm): ?>
                    <a href="edit_repair_job.php?id=<?= $job_id ?>" class="btn btn-sm btn-info"><i class="fas fa-edit"></i> Edit Job</a>
                    <?php endif; ?>
                    <?php if ($has_parts_perm && !$is_delivered): ?>
                    <button class="btn btn-sm btn-primary" onclick="showAddPartModal()"><i class="fas fa-plus-circle"></i> Add Spare Part</button>
                    <?php endif; ?>
                    <?php if ($has_edit_perm): ?>
                    <button class="btn btn-sm btn-warning" onclick="showLabourModal()"><i class="fas fa-wrench"></i> Labour Charge</button>
                    <?php endif; ?>
                    <?php if ($has_payment_perm && !$is_delivered): ?>
                    <a href="repair_payment.php?job_id=<?= $job_id ?>" class="btn btn-sm btn-success"><i class="fas fa-money-bill"></i> Collect Payment</a>
                    <?php endif; ?>
                    <?php if ($has_edit_perm && !$is_completed && !$is_delivered): ?>
                    <form method="POST" action="complete_repair.php" style="display:inline" onsubmit="return confirm('Mark this job as Completed?')">
                        <input type="hidden" name="job_id" value="<?= $job_id ?>">
                        <input type="hidden" name="action" value="mark_completed">
                        <button type="submit" class="btn btn-sm btn-success"><i class="fas fa-check"></i> Mark Completed</button>
                    </form>
                    <?php endif; ?>
                    <?php if ($has_edit_perm && $is_completed && !$is_delivered): ?>
                    <form method="POST" action="complete_repair.php" style="display:inline" onsubmit="return confirm('Deliver device to customer? This will start warranty if applicable.')">
                        <input type="hidden" name="job_id" value="<?= $job_id ?>">
                        <input type="hidden" name="action" value="mark_delivered">
                        <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-handshake"></i> Mark Delivered</button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-user me-2"></i>Customer Information</div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td width="120">Name:</td><td><strong><?= htmlspecialchars($job['customer_name'] ?? '-') ?></strong></td></tr>
                            <tr><td>Phone:</td><td><?= htmlspecialchars($job['customer_phone'] ?? '-') ?></td></tr>
                            <tr><td>Address:</td><td><?= nl2br(htmlspecialchars($job['customer_address'] ?? '-')) ?></td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-info-circle me-2"></i>Job Information</div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td width="140">Job No:</td><td><strong><?= htmlspecialchars($job['job_no']) ?></strong></td></tr>
                            <tr><td>Status:</td><td><?= getStatusBadge($job['repair_status']) ?> <?= $job['priority'] == 'Urgent' ? '<span class="badge bg-danger">Urgent</span>' : '' ?></td></tr>
                            <tr><td>Technician:</td><td><?= htmlspecialchars($job['technician_name'] ?? 'Unassigned') ?></td></tr>
                            <tr><td>Created By:</td><td><?= htmlspecialchars($job['created_by_name'] ?? 'System') ?></td></tr>
                            <tr><td>Created:</td><td><?= formatDateTime($job['created_at']) ?></td></tr>
                            <tr><td>Expected Delivery:</td><td><?= formatDate($job['expected_delivery_date']) ?></td></tr>
                            <?php if ($job['delivered_date']): ?><tr><td>Delivered:</td><td><?= formatDateTime($job['delivered_date']) ?></td></tr><?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><i class="fas fa-mobile-alt me-2"></i>Device Information</div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3"><strong>Brand:</strong> <?= htmlspecialchars($job['device_brand'] ?? '-') ?></div>
                    <div class="col-md-3"><strong>Model:</strong> <?= htmlspecialchars($job['device_model'] ?? '-') ?></div>
                    <div class="col-md-3"><strong>IMEI:</strong> <code><?= htmlspecialchars($job['device_imei'] ?? '-') ?></code></div>
                    <div class="col-md-3"><strong>Color:</strong> <?= htmlspecialchars($job['device_color'] ?? '-') ?></div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <strong>Problem Description:</strong>
                        <p class="mb-0"><?= nl2br(htmlspecialchars($job['problem_description'])) ?></p>
                    </div>
                    <div class="col-md-6">
                        <strong>Device Condition:</strong>
                        <p class="mb-0"><?= nl2br(htmlspecialchars($job['device_condition'] ?? 'Not specified')) ?></p>
                    </div>
                </div>
                <?php if (!empty($job['device_password_note'])): ?>
                <hr><p><strong>Password Note:</strong> <?= htmlspecialchars($job['device_password_note']) ?></p>
                <?php endif; ?>
                <?php if (!empty($job['accessories_received'])): ?>
                <hr><p><strong>Accessories Received:</strong> <?= htmlspecialchars($job['accessories_received']) ?></p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Spare Parts Used -->
        <div class="card">
            <div class="card-header d-flex justify-content-between">
                <span><i class="fas fa-cogs me-2"></i>Spare Parts Used</span>
                <?php if ($has_parts_perm && !$is_delivered): ?>
                <button class="btn btn-sm btn-primary" onclick="showAddPartModal()"><i class="fas fa-plus"></i> Add Part</button>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <?php if (count($parts) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-sm no-datatable">
                        <thead><tr><th>Part Name</th><th>Qty</th><th>Cost Price</th><th>Selling Price</th><th>Total</th><?php if ($has_parts_perm && !$is_delivered): ?><th>Action</th><?php endif; ?></tr></thead>
                        <tbody>
                            <?php foreach ($parts as $p): ?>
                            <tr>
                                <td><?= htmlspecialchars($p['product_name']) ?></td>
                                <td><?= $p['quantity'] ?></td>
                                <td><?= formatCurrency($p['cost_price']) ?></td>
                                <td><?= formatCurrency($p['selling_price']) ?></td>
                                <td><?= formatCurrency($p['total_price']) ?></td>
                                <?php if ($has_parts_perm && !$is_delivered): ?>
                                <td>
                                    <form method="POST" action="remove_repair_part.php" onsubmit="return confirm('Remove this part and restore stock?')">
                                        <input type="hidden" name="part_id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="job_id" value="<?= $job_id ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                                <?php endif; ?>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <p class="text-muted mb-0">No spare parts used yet.</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Pricing Summary -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-dollar-sign me-2"></i>Pricing Summary</div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td>Estimated Cost (Reference):</td><td class="text-end"><?= formatCurrency($job['estimated_cost']) ?></td></tr>
                            <tr><td>Parts Total:</td><td class="text-end"><?= formatCurrency($job['parts_total']) ?></td></tr>
                            <tr><td>Labour Charge:</td><td class="text-end"><?= formatCurrency($job['labour_charge']) ?></td></tr>
                            <tr><td>Discount:</td><td class="text-end">-<?= formatCurrency($job['discount_amount']) ?></td></tr>
                            <tr class="fw-bold"><td>Final Amount:</td><td class="text-end"><?= formatCurrency($job['final_amount']) ?></td></tr>
                            <tr><td>Advance Paid:</td><td class="text-end"><?= formatCurrency($job['advance_payment']) ?></td></tr>
                            <tr><td>Total Paid:</td><td class="text-end" class="text-success"><?= formatCurrency($job['paid_amount']) ?></td></tr>
                            <tr class="text-danger fw-bold"><td>Due Amount:</td><td class="text-end"><?= formatCurrency($job['due_amount']) ?></td></tr>
                        </table>
                        <?php if ($has_edit_perm && !$is_delivered): ?>
                        <button class="btn btn-sm btn-warning" onclick="showLabourModal()"><i class="fas fa-wrench"></i> Update Labour</button>
                        <button class="btn btn-sm btn-info" onclick="showDiscountModal()"><i class="fas fa-percentage"></i> Discount</button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-credit-card me-2"></i>Payment History</div>
                    <div class="card-body">
                        <?php if (count($payments) > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-sm no-datatable">
                                <thead><tr><th>Date</th><th>Amount</th><th>Method</th><th>Received By</th><th>Note</th></tr></thead>
                                <tbody>
                                    <?php foreach ($payments as $pmt): ?>
                                    <tr>
                                        <td><?= formatDate($pmt['payment_date'], 'Y-m-d') ?></td>
                                        <td><?= formatCurrency($pmt['amount']) ?></td>
                                        <td><?= $pmt['payment_method'] ?></td>
                                        <td><?= htmlspecialchars($pmt['received_by_name'] ?? 'System') ?></td>
                                        <td><small><?= htmlspecialchars($pmt['note'] ?? '') ?></small></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <p class="text-muted mb-0">No payments recorded yet.</p>
                        <?php endif; ?>
                        <?php if ($has_payment_perm && !$is_delivered): ?>
                        <a href="repair_payment.php?job_id=<?= $job_id ?>" class="btn btn-sm btn-success mt-2"><i class="fas fa-money-bill"></i> Collect Payment</a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($job['repair_warranty_days'] > 0): ?>
        <div class="card">
            <div class="card-header"><i class="fas fa-shield-alt me-2"></i>Repair Warranty</div>
            <div class="card-body">
                <p>Warranty Period: <strong><?= $job['repair_warranty_days'] ?> days</strong></p>
                <?php if ($job['repair_warranty_start_date']): ?>
                <p>Start: <?= formatDate($job['repair_warranty_start_date']) ?> | End: <?= formatDate($job['repair_warranty_end_date']) ?></p>
                <?php else: ?>
                <p class="text-muted">Warranty starts on delivery.</p>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Status History -->
        <div class="card">
            <div class="card-header"><i class="fas fa-history me-2"></i>Status History</div>
            <div class="card-body">
                <?php if (count($history) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-sm no-datatable">
                        <thead><tr><th>Date</th><th>Status</th><th>Notes</th><th>Changed By</th></tr></thead>
                        <tbody>
                            <?php foreach ($history as $h): ?>
                            <tr>
                                <td><?= formatDateTime($h['created_at']) ?></td>
                                <td><?= getStatusBadge($h['new_status']) ?></td>
                                <td><?= htmlspecialchars($h['note'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($h['changed_by_name'] ?? 'System') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <p class="text-muted mb-0">No status history.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Add Part Modal -->
<div class="modal fade" id="addPartModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="add_repair_parts.php" class="modal-content">
            <input type="hidden" name="job_id" value="<?= $job_id ?>">
            <div class="modal-header"><h5 class="modal-title">Add Spare Part</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Spare Part</label>
                    <select name="product_id" id="partProduct" class="form-select" required>
                        <option value="">Select Part</option>
                        <?php
                        $spare_parts = $pdo->query("SELECT id, product_name, current_stock, selling_price, cost_price FROM products WHERE product_type='spare_part' AND status=1 AND current_stock > 0 ORDER BY product_name")->fetchAll();
                        foreach ($spare_parts as $sp): ?>
                        <option value="<?= $sp['id'] ?>" data-stock="<?= $sp['current_stock'] ?>" data-price="<?= $sp['selling_price'] ?>"><?= htmlspecialchars($sp['product_name']) ?> (Stock: <?= $sp['current_stock'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="row">
                    <div class="col-6 mb-3">
                        <label class="form-label">Current Stock</label>
                        <div id="stockDisplay" class="form-control-plaintext fw-bold">-</div>
                    </div>
                    <div class="col-6 mb-3">
                        <label class="form-label">Unit Price</label>
                        <div id="priceDisplay" class="form-control-plaintext fw-bold">-</div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-6 mb-3">
                        <label class="form-label">Quantity <span class="text-danger">*</span></label>
                        <input type="number" name="quantity" id="partQty" class="form-control" value="1" min="1" required>
                    </div>
                    <div class="col-6 mb-3">
                        <label class="form-label">Selling Price <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" name="selling_price" id="partPrice" class="form-control" required>
                    </div>
                </div>
                <div class="mb-3 p-3 bg-light rounded">
                    <strong>Total: </strong><span id="totalDisplay">0.00</span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Add Part</button>
            </div>
        </form>
    </div>
</div>

<!-- Labour Modal -->
<div class="modal fade" id="labourModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="complete_repair.php" class="modal-content">
            <input type="hidden" name="action" value="update_labour">
            <input type="hidden" name="job_id" value="<?= $job_id ?>">
            <div class="modal-header"><h5 class="modal-title">Update Labour Charge</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Labour Charge</label>
                    <input type="number" step="0.01" name="labour_charge" class="form-control" value="<?= $job['labour_charge'] ?>" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-warning">Update Labour</button>
            </div>
        </form>
    </div>
</div>

<!-- Discount Modal -->
<div class="modal fade" id="discountModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="complete_repair.php" class="modal-content">
            <input type="hidden" name="action" value="update_discount">
            <input type="hidden" name="job_id" value="<?= $job_id ?>">
            <div class="modal-header"><h5 class="modal-title">Update Discount</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Discount Amount</label>
                    <input type="number" step="0.01" name="discount_amount" class="form-control" value="<?= $job['discount_amount'] ?>">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-info">Update Discount</button>
            </div>
        </form>
    </div>
</div>

<script>
function showAddPartModal() { $('#addPartModal').modal('show'); }
function showLabourModal() { $('#labourModal').modal('show'); }
function showDiscountModal() { $('#discountModal').modal('show'); }

$('#partProduct').on('change', function() {
    var opt = $(this).find('option:selected');
    var stock = opt.data('stock');
    var price = opt.data('price');
    $('#stockDisplay').text(stock != null ? stock : '-');
    $('#priceDisplay').text(price != null ? '<?= getSetting('currency_symbol', 'Rs.') ?> ' + parseFloat(price).toFixed(2) : '-');
    $('#partPrice').val(price || 0);
    calcTotal();
});

$('#partQty, #partPrice').on('input', calcTotal);
function calcTotal() {
    var qty = parseInt($('#partQty').val()) || 0;
    var price = parseFloat($('#partPrice').val()) || 0;
    $('#totalDisplay').text((qty * price).toFixed(2));
}
</script>

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