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

$pdo = getDB();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$stmt = $pdo->prepare("
    SELECT pi.*, p.product_name, p.model, p.product_code, p.sku, p.selling_price, p.product_type
    FROM product_imei pi
    JOIN products p ON pi.product_id = p.id
    WHERE pi.id = ?
");
$stmt->execute([$id]);
$imei = $stmt->fetch();

if (!$imei) {
    $_SESSION['error'] = 'IMEI record not found.';
    header('Location: imei_stock.php');
    exit;
}

// Purchase info
$purchase_info = null;
if ($imei['purchase_item_id']) {
    $stmt = $pdo->prepare("
        SELECT pi.*, pu.purchase_no, pu.purchase_date, pu.supplier_id, s.supplier_name
        FROM purchase_items pi
        JOIN purchases pu ON pi.purchase_id = pu.id
        LEFT JOIN suppliers s ON pu.supplier_id = s.id
        WHERE pi.id = ?
    ");
    $stmt->execute([$imei['purchase_item_id']]);
    $purchase_info = $stmt->fetch();
}

// Sale info
$sale_info = null;
if ($imei['sales_invoice_item_id']) {
    $stmt = $pdo->prepare("
        SELECT sii.*, si.invoice_no, si.invoice_date, si.customer_id, c.name as customer_name
        FROM sales_invoice_items sii
        JOIN sales_invoices si ON sii.sales_invoice_id = si.id
        LEFT JOIN customers c ON si.customer_id = c.id
        WHERE sii.id = ?
    ");
    $stmt->execute([$imei['sales_invoice_item_id']]);
    $sale_info = $stmt->fetch();
}

// Warranty claims
$stmt = $pdo->prepare("
    SELECT wc.*, wr.warranty_start_date, wr.warranty_end_date, wr.warranty_status as record_status
    FROM warranty_claims wc
    JOIN warranty_records wr ON wc.warranty_record_id = wr.id
    WHERE wr.imei_id = ?
    ORDER BY wc.created_at DESC
");
$stmt->execute([$id]);
$warranty_claims = $stmt->fetchAll();

// Warranty records
$stmt = $pdo->prepare("
    SELECT * FROM warranty_records
    WHERE imei_id = ?
    ORDER BY created_at DESC
");
$stmt->execute([$id]);
$warranty_records = $stmt->fetchAll();

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-history me-2"></i>IMEI History</h4>
            <a href="imei_stock.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i>Back to IMEI Stock</a>
        </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; ?>

        <!-- IMEI Details -->
        <div class="card mb-3">
            <div class="card-header"><i class="fas fa-microchip me-2"></i>IMEI Details</div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-2"><strong>IMEI Number:</strong><br><code><?= htmlspecialchars($imei['imei_number']) ?></code></div>
                    <div class="col-md-4 mb-2"><strong>Serial Number:</strong><br><?= htmlspecialchars($imei['serial_number'] ?? '-') ?></div>
                    <div class="col-md-4 mb-2"><strong>Status:</strong><br>
                        <?php
                        $status_class = 'bg-secondary';
                        if ($imei['status'] == 'Available') $status_class = 'bg-success';
                        elseif ($imei['status'] == 'Sold') $status_class = 'bg-primary';
                        elseif ($imei['status'] == 'Returned') $status_class = 'bg-warning text-dark';
                        elseif ($imei['status'] == 'Damaged') $status_class = 'bg-danger';
                        elseif ($imei['status'] == 'Warranty Claim') $status_class = 'bg-purple';
                        ?>
                        <span class="badge <?= $status_class ?>"><?= htmlspecialchars($imei['status']) ?></span>
                    </div>
                    <div class="col-md-4 mb-2"><strong>Product:</strong><br><?= htmlspecialchars($imei['product_name']) ?></div>
                    <div class="col-md-4 mb-2"><strong>Model:</strong><br><?= htmlspecialchars($imei['model'] ?? '-') ?></div>
                    <div class="col-md-4 mb-2"><strong>Product Code:</strong><br><?= htmlspecialchars($imei['product_code'] ?? '-') ?></div>
                    <div class="col-md-4 mb-2"><strong>Warranty Start:</strong><br><?= $imei['warranty_start_date'] ? formatDate($imei['warranty_start_date']) : '-' ?></div>
                    <div class="col-md-4 mb-2"><strong>Warranty End:</strong><br><?= $imei['warranty_end_date'] ? formatDate($imei['warranty_end_date']) : '-' ?></div>
                    <div class="col-md-4 mb-2"><strong>Created At:</strong><br><?= formatDateTime($imei['created_at']) ?></div>
                    <div class="col-md-4 mb-2"><strong>Updated At:</strong><br><?= formatDateTime($imei['updated_at']) ?></div>
                </div>
            </div>
        </div>

        <!-- Purchase Info -->
        <?php if ($purchase_info): ?>
        <div class="card mb-3">
            <div class="card-header"><i class="fas fa-truck me-2"></i>Purchase Information</div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-2"><strong>Purchase No:</strong><br><?= htmlspecialchars($purchase_info['purchase_no'] ?? '-') ?></div>
                    <div class="col-md-4 mb-2"><strong>Purchase Date:</strong><br><?= formatDate($purchase_info['purchase_date']) ?></div>
                    <div class="col-md-4 mb-2"><strong>Supplier:</strong><br><?= htmlspecialchars($purchase_info['supplier_name'] ?? '-') ?></div>
                    <div class="col-md-4 mb-2"><strong>Cost Price:</strong><br><?= formatCurrency($purchase_info['cost_price'] ?? 0) ?></div>
                    <div class="col-md-4 mb-2"><strong>Quantity:</strong><br><?= (int)($purchase_info['quantity'] ?? 0) ?></div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Sale Info -->
        <?php if ($sale_info): ?>
        <div class="card mb-3">
            <div class="card-header"><i class="fas fa-shopping-cart me-2"></i>Sale Information</div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-2"><strong>Invoice No:</strong><br><?= htmlspecialchars($sale_info['invoice_no'] ?? '-') ?></div>
                    <div class="col-md-4 mb-2"><strong>Invoice Date:</strong><br><?= formatDate($sale_info['invoice_date'] ?? $sale_info['created_at']) ?></div>
                    <div class="col-md-4 mb-2"><strong>Customer:</strong><br><?= htmlspecialchars($sale_info['customer_name'] ?? '-') ?></div>
                    <div class="col-md-4 mb-2"><strong>Selling Price:</strong><br><?= formatCurrency($sale_info['selling_price'] ?? 0) ?></div>
                    <div class="col-md-4 mb-2"><strong>Warranty End:</strong><br><?= ($sale_info['warranty_end_date'] ?? '') ? formatDate($sale_info['warranty_end_date']) : '-' ?></div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Warranty Records -->
        <?php if (!empty($warranty_records)): ?>
        <div class="card mb-3">
            <div class="card-header"><i class="fas fa-shield-alt me-2"></i>Warranty Records</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover no-datatable">
                        <thead>
                            <tr>
                                <th>Type</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($warranty_records as $wr): ?>
                            <tr>
                                <td><?= htmlspecialchars($wr['warranty_type'] ?? '-') ?></td>
                                <td><?= formatDate($wr['warranty_start_date']) ?></td>
                                <td><?= formatDate($wr['warranty_end_date']) ?></td>
                                <td><?= getStatusBadge($wr['warranty_status']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Warranty Claims -->
        <?php if (!empty($warranty_claims)): ?>
        <div class="card mb-3">
            <div class="card-header"><i class="fas fa-exclamation-triangle me-2"></i>Warranty Claims History</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover no-datatable">
                        <thead>
                            <tr>
                                <th>Claim No</th>
                                <th>Claim Date</th>
                                <th>Issue</th>
                                <th>Status</th>
                                <th>Decision</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($warranty_claims as $wc): ?>
                            <tr>
                                <td><?= htmlspecialchars($wc['claim_no'] ?? '-') ?></td>
                                <td><?= formatDate($wc['claim_date']) ?></td>
                                <td><?= htmlspecialchars(substr($wc['issue_description'] ?? '', 0, 100)) ?></td>
                                <td><?= getStatusBadge($wc['claim_status']) ?></td>
                                <td><?= htmlspecialchars(substr($wc['decision_note'] ?? '', 0, 100)) ?: '-' ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!$purchase_info && !$sale_info && empty($warranty_records) && empty($warranty_claims)): ?>
        <div class="alert alert-info">No additional history records found for this IMEI.</div>
        <?php endif; ?>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
