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

$pdo = getDB();

$warranties = $pdo->query("
    SELECT w.*, p.product_name as product_name, c.name as customer_name, c.phone as customer_phone, pi.imei_number
    FROM warranty_records w
    LEFT JOIN products p ON w.product_id = p.id
    LEFT JOIN customers c ON w.customer_id = c.id
    LEFT JOIN product_imei pi ON w.imei_id = pi.id
    ORDER BY w.id DESC
")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-shield-alt me-2"></i>Warranty Records</h4>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="warrantiesTable" class="table table-hover datatable">
                        <thead>
                            <tr><th>Type</th><th>Customer</th><th>Product</th><th>IMEI</th><th>Start Date</th><th>End Date</th><th>Period</th><th>Status</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($warranties as $w): ?>
                            <tr>
                                <td><span class="badge bg-<?= $w['warranty_type'] == 'product' ? 'primary' : 'info' ?>"><?= $w['warranty_type'] ?></span></td>
                                <td><?= htmlspecialchars($w['customer_name'] ?? '-') ?><br><small><?= htmlspecialchars($w['customer_phone'] ?? '') ?></small></td>
                                <td><?= htmlspecialchars($w['product_name'] ?? '-') ?></td>
                                <td><code><?= htmlspecialchars($w['imei_number'] ?? '-') ?></code></td>
                                <td><?= formatDate($w['warranty_start_date']) ?></td>
                                <td><?= formatDate($w['warranty_end_date']) ?></td>
                                <td><?= $w['warranty_start_date'] && $w['warranty_end_date'] ? floor((strtotime($w['warranty_end_date']) - strtotime($w['warranty_start_date'])) / 86400) . ' days' : '-' ?></td>
                                <td><?= getStatusBadge($w['warranty_status']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
