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

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

$stmt = $pdo->prepare("
    SELECT p.*, c.category_name, b.brand_name, s.supplier_name
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    LEFT JOIN brands b ON p.brand_id = b.id
    LEFT JOIN suppliers s ON p.supplier_id = s.id
    WHERE p.id = ?
");
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    $_SESSION['error'] = 'Product not found.';
    header('Refresh: 3; url=products.php');
    include __DIR__ . '/../includes/header.php';
    include __DIR__ . '/../includes/sidebar.php';
    echo '<div class="content-wrapper"><div class="container-fluid"><div class="alert alert-danger">Product not found. Redirecting to products list...</div></div></div>';
    include __DIR__ . '/../includes/footer.php';
    exit;
}

$is_phone = ($product['product_type'] === 'Phone');
$is_spare = ($product['product_type'] === 'Spare Part');

// Get IMEI records for phone products
$imei_records = [];
if ($is_phone) {
    $stmt = $pdo->prepare("SELECT * FROM product_imei WHERE product_id = ? ORDER BY id DESC");
    $stmt->execute([$id]);
    $imei_records = $stmt->fetchAll();
}

// Get recent stock movements
$stmt = $pdo->prepare("
    SELECT sm.*, u.name as created_by_name
    FROM stock_movements sm
    LEFT JOIN users u ON sm.created_by = u.id
    WHERE sm.product_id = ?
    ORDER BY sm.id DESC
    LIMIT 20
");
$stmt->execute([$id]);
$stock_movements = $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-box me-2"></i><?= htmlspecialchars($product['product_name']) ?></h4>
            <div>
                <a href="add_product.php?id=<?= $product['id'] ?>" class="btn btn-info"><i class="fas fa-edit me-1"></i>Edit Product</a>
                <a href="products.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i>Back to Products</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; ?>

        <div class="row">
            <div class="col-md-8">
                <!-- Basic Info -->
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-info-circle me-2"></i>Basic Information</div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 mb-2"><strong>Product Code:</strong><br><?= htmlspecialchars($product['product_code'] ?? '-') ?></div>
                            <div class="col-md-4 mb-2"><strong>SKU:</strong><br><?= htmlspecialchars($product['sku'] ?? '-') ?></div>
                            <div class="col-md-4 mb-2"><strong>Barcode:</strong><br><?= htmlspecialchars($product['barcode'] ?? '-') ?></div>
                            <div class="col-md-4 mb-2"><strong>Product Type:</strong><br>
                                <span class="badge bg-<?= $product['product_type'] == 'Phone' ? 'primary' : ($product['product_type'] == 'Accessory' ? 'success' : 'warning') ?>">
                                    <?= htmlspecialchars($product['product_type']) ?>
                                </span>
                            </div>
                            <div class="col-md-4 mb-2"><strong>Category:</strong><br><?= htmlspecialchars($product['category_name'] ?? '-') ?></div>
                            <div class="col-md-4 mb-2"><strong>Brand:</strong><br><?= htmlspecialchars($product['brand_name'] ?? '-') ?></div>
                            <div class="col-md-4 mb-2"><strong>Model:</strong><br><?= htmlspecialchars($product['model'] ?? '-') ?></div>
                            <div class="col-md-4 mb-2"><strong>Supplier:</strong><br><?= htmlspecialchars($product['supplier_name'] ?? '-') ?></div>
                            <div class="col-md-4 mb-2"><strong>Status:</strong><br><?= $product['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></div>
                        </div>
                    </div>
                </div>

                <!-- Pricing -->
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-dollar-sign me-2"></i>Pricing</div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 mb-2"><strong>Cost Price:</strong><br><?= formatCurrency($product['cost_price']) ?></div>
                            <div class="col-md-4 mb-2"><strong>Selling Price:</strong><br><?= formatCurrency($product['selling_price']) ?></div>
                            <div class="col-md-4 mb-2"><strong>Wholesale Price:</strong><br><?= formatCurrency($product['wholesale_price']) ?></div>
                        </div>
                    </div>
                </div>

                <!-- Stock Info -->
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-warehouse me-2"></i>Stock Information</div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 mb-2"><strong>Current Stock:</strong><br><?= getStockBadge($product['current_stock'], $product['low_stock_qty']) ?> (<?= (int)$product['current_stock'] ?>)</div>
                            <div class="col-md-4 mb-2"><strong>Low Stock Alert:</strong><br><?= (int)$product['low_stock_qty'] ?></div>
                            <div class="col-md-4 mb-2"><strong>Warranty Period:</strong><br><?= $product['warranty_period_days'] ? htmlspecialchars($product['warranty_period_days']) . ' days' : 'No warranty' ?></div>
                        </div>
                    </div>
                </div>

                <!-- Compatible Models (for spare parts) -->
                <?php if ($is_spare && !empty($product['compatible_models'])): ?>
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-mobile-alt me-2"></i>Compatible Models</div>
                    <div class="card-body">
                        <?php
                        $models = explode(',', $product['compatible_models']);
                        foreach ($models as $m):
                            $m = trim($m);
                            if (empty($m)) continue;
                        ?>
                        <span class="badge bg-info me-1 mb-1"><?= htmlspecialchars($m) ?></span>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Description -->
                <?php if (!empty($product['description'])): ?>
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-align-left me-2"></i>Description</div>
                    <div class="card-body">
                        <p class="mb-0"><?= nl2br(htmlspecialchars($product['description'])) ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <!-- IMEI Records (for phone products) -->
                <?php if ($is_phone): ?>
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-microchip me-2"></i>IMEI / Serial Numbers (<?= count($imei_records) ?>)</div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="imeiRecordsTable" class="table table-hover datatable">
                                <thead>
                                    <tr>
                                        <th>IMEI Number</th>
                                        <th>Serial Number</th>
                                        <th>Status</th>
                                        <th>Warranty Start</th>
                                        <th>Warranty End</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($imei_records as $imei): ?>
                                    <tr>
                                        <td><code><?= htmlspecialchars($imei['imei_number']) ?></code></td>
                                        <td><?= htmlspecialchars($imei['serial_number'] ?? '-') ?></td>
                                        <td><?= getStatusBadge($imei['status']) ?></td>
                                        <td><?= $imei['warranty_start_date'] ? formatDate($imei['warranty_start_date']) : '-' ?></td>
                                        <td><?= $imei['warranty_end_date'] ? formatDate($imei['warranty_end_date']) : '-' ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Recent Stock Movements -->
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-exchange-alt me-2"></i>Recent Stock Movements (Last 20)</div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="stockMovementsTable" class="table table-hover datatable">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Type</th>
                                        <th>In</th>
                                        <th>Out</th>
                                        <th>Balance</th>
                                        <th>Reference</th>
                                        <th>Note</th>
                                        <th>By</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($stock_movements)): ?>
                                    <?php foreach ($stock_movements as $sm): ?>
                                    <tr>
                                        <td><?= formatDateTime($sm['created_at']) ?></td>
                                        <td><span class="badge bg-<?= $sm['movement_type'] == 'purchase' ? 'success' : ($sm['movement_type'] == 'sale' ? 'primary' : ($sm['movement_type'] == 'return' ? 'info' : ($sm['movement_type'] == 'adjustment' ? 'warning' : 'danger'))) ?>"><?= htmlspecialchars(ucfirst($sm['movement_type'])) ?></span></td>
                                        <td><?= $sm['quantity_in'] ?: '-' ?></td>
                                        <td><?= $sm['quantity_out'] ?: '-' ?></td>
                                        <td><?= (int)$sm['balance_after'] ?></td>
                                        <td><?= htmlspecialchars(($sm['reference_type'] ?? '') . ($sm['reference_id'] ? '#' . $sm['reference_id'] : '')) ?: '-' ?></td>
                                        <td><?= htmlspecialchars($sm['note'] ?? '-') ?></td>
                                        <td><?= htmlspecialchars($sm['created_by_name'] ?? '-') ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <!-- Product Image -->
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-image me-2"></i>Product Image</div>
                    <div class="card-body text-center">
                        <?php if (!empty($product['product_image'])): ?>
                        <img src="<?= BASE_URL ?><?= htmlspecialchars($product['product_image']) ?>" alt="<?= htmlspecialchars($product['product_name']) ?>" class="img-fluid rounded" style="max-height:250px;">
                        <?php else: ?>
                        <div class="text-muted py-5"><i class="fas fa-camera fa-3x"></i><p class="mt-2">No image uploaded</p></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
