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

$pdo = getDB();

$stmt = $pdo->query("SELECT id, product_name, model, product_type FROM products WHERE status = 1 ORDER BY product_name");
$all_products = $stmt->fetchAll();

$where = [];
$params = [];

if (!empty($_GET['product_id'])) {
    $where[] = 'pi.product_id = ?';
    $params[] = (int)$_GET['product_id'];
}

if (!empty($_GET['status'])) {
    $where[] = 'pi.status = ?';
    $params[] = $_GET['status'];
}

if (!empty($_GET['search'])) {
    $where[] = '(pi.imei_number LIKE ? OR pi.serial_number LIKE ?)';
    $search = '%' . $_GET['search'] . '%';
    $params[] = $search;
    $params[] = $search;
}

$where_clause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$stmt = $pdo->prepare("
    SELECT pi.*, p.product_name, p.model, p.product_type, p.brand_id,
           COALESCE(b.brand_name, 'N/A') AS brand_name
    FROM product_imei pi
    JOIN products p ON pi.product_id = p.id
    LEFT JOIN brands b ON p.brand_id = b.id
    $where_clause
    ORDER BY pi.id DESC
");
$stmt->execute($params);
$imei_list = $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-microchip me-2"></i>IMEI / Serial Number Stock</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addImeiModal"><i class="fas fa-plus me-1"></i>Add IMEI</button>
        </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; ?>

        <!-- Filter Card -->
        <div class="card mb-3">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Product</label>
                        <select name="product_id" class="form-select">
                            <option value="">All Products</option>
                            <?php foreach ($all_products as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= (isset($_GET['product_id']) && $_GET['product_id'] == $p['id']) ? 'selected' : '' ?>><?= htmlspecialchars($p['product_name'] . ' (' . $p['model'] . ')') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All Status</option>
                            <option value="Available" <?= (isset($_GET['status']) && $_GET['status'] == 'Available') ? 'selected' : '' ?>>Available</option>
                            <option value="Sold" <?= (isset($_GET['status']) && $_GET['status'] == 'Sold') ? 'selected' : '' ?>>Sold</option>
                            <option value="Returned" <?= (isset($_GET['status']) && $_GET['status'] == 'Returned') ? 'selected' : '' ?>>Returned</option>
                            <option value="Damaged" <?= (isset($_GET['status']) && $_GET['status'] == 'Damaged') ? 'selected' : '' ?>>Damaged</option>
                            <option value="Warranty Claim" <?= (isset($_GET['status']) && $_GET['status'] == 'Warranty Claim') ? 'selected' : '' ?>>Warranty Claim</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Search IMEI / Serial</label>
                        <input type="text" name="search" class="form-control" placeholder="Type to search..." value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2"><i class="fas fa-search me-1"></i>Filter</button>
                        <a href="imei_stock.php" class="btn btn-secondary"><i class="fas fa-undo me-1"></i>Reset</a>
                    </div>
                </form>
            </div>
        </div>

        <!-- IMEI Table -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="imeiTable" class="table table-bordered table-striped table-hover no-datatable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Product</th>
                                <th>IMEI Number</th>
                                <th>Serial Number</th>
                                <th>Brand</th>
                                <th>Model</th>
                                <th>Status</th>
                                <th>Created Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($imei_list)): ?>
                                <?php foreach ($imei_list as $index => $i): ?>
                                <tr>
                                    <td><?= $index + 1 ?></td>
                                    <td><?= htmlspecialchars($i['product_name']) ?></td>
                                    <td><code><?= htmlspecialchars($i['imei_number']) ?></code></td>
                                    <td><?= htmlspecialchars($i['serial_number'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($i['brand_name']) ?></td>
                                    <td><?= htmlspecialchars($i['model'] ?? '-') ?></td>
                                    <td>
                                        <?php
                                        $status_class = 'bg-secondary';
                                        if ($i['status'] == 'Available') $status_class = 'bg-success';
                                        elseif ($i['status'] == 'Sold') $status_class = 'bg-primary';
                                        elseif ($i['status'] == 'Returned') $status_class = 'bg-warning text-dark';
                                        elseif ($i['status'] == 'Damaged') $status_class = 'bg-danger';
                                        elseif ($i['status'] == 'Warranty Claim') $status_class = 'bg-info';
                                        ?>
                                        <span class="badge <?= $status_class ?>"><?= htmlspecialchars($i['status']) ?></span>
                                    </td>
                                    <td><?= $i['created_at'] ? date('Y-m-d', strtotime($i['created_at'])) : '-' ?></td>
                                    <td>
                                        <a href="view_imei_history.php?id=<?= (int)$i['id'] ?>" class="btn btn-sm btn-info"><i class="fas fa-history"></i></a>
                                        <?php if (hasPermission('product_management') || $is_super_admin): ?>
                                        <button class="btn btn-sm btn-warning" onclick="editStatus(<?= $i['id'] ?>, '<?= htmlspecialchars($i['imei_number'], ENT_QUOTES) ?>', '<?= htmlspecialchars($i['status'], ENT_QUOTES) ?>')"><i class="fas fa-edit"></i></button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add IMEI Modal -->
<div class="modal fade" id="addImeiModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="addImeiForm">
                <div class="modal-header"><h5 class="modal-title"><i class="fas fa-plus me-2"></i>Add IMEI / Serial</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">Product *</label>
                        <select name="product_id" class="form-select" required>
                            <option value="">Select Phone Product</option>
                            <?php foreach ($all_products as $p): ?>
                                <?php if ($p['product_type'] == 'Phone'): ?>
                                <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['product_name'] . ' (' . $p['model'] . ')') ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">IMEI Number(s) *</label>
                        <textarea name="imei_numbers" class="form-control" rows="4" placeholder="Enter one IMEI per line for bulk addition" required></textarea>
                        <small class="text-muted">Enter one IMEI per line for bulk addition</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Serial Number (optional)</label>
                        <input type="text" name="serial_number" class="form-control" placeholder="Serial number (will apply to all)">
                    </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"><i class="fas fa-save me-1"></i>Add IMEI(s)</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Status Modal -->
<div class="modal fade" id="editStatusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="editStatusForm">
                <div class="modal-header"><h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit IMEI Status</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" name="id" id="editImeiId">
                    <div class="mb-3">
                        <label class="form-label">IMEI Number</label>
                        <input type="text" id="editImeiNumber" class="form-control" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Current Status</label>
                        <input type="text" id="editCurrentStatus" class="form-control" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">New Status *</label>
                        <select name="status" class="form-select" required>
                            <option value="">Select Status</option>
                            <option value="Available">Available</option>
                            <option value="Sold">Sold</option>
                            <option value="Returned">Returned</option>
                            <option value="Damaged">Damaged</option>
                            <option value="Warranty Claim">Warranty Claim</option>
                        </select>
                        <small class="text-muted">Note: Cannot change from 'Sold' to 'Available' directly. Use return workflow.</small>
                    </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"><i class="fas fa-save me-1"></i>Update Status</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    if ($.fn.DataTable.isDataTable('#imeiTable')) {
        $('#imeiTable').DataTable().destroy();
    }

    $('#imeiTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[0, 'desc']],
        columnDefs: [
            { orderable: false, targets: [8] }
        ],
        language: {
            emptyTable: "No IMEI records found"
        }
    });

    // Add IMEI form submission
    $('#addImeiForm').on('submit', function(e) {
        e.preventDefault();
        var form = $(this);
        var data = {
            product_id: form.find('select[name="product_id"]').val(),
            imei_numbers: form.find('textarea[name="imei_numbers"]').val(),
            serial_number: form.find('input[name="serial_number"]').val()
        };
        $.ajax({
            url: 'add_imei.php',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function(resp) {
                if (resp.success) {
                    $('#addImeiModal').modal('hide');
                    location.reload();
                } else {
                    alert(resp.message || 'Failed to add IMEI');
                }
            },
            error: function() {
                alert('An error occurred while adding IMEI.');
            }
        });
    });

    // Edit status form submission
    $('#editStatusForm').on('submit', function(e) {
        e.preventDefault();
        var form = $(this);
        var data = {
            id: form.find('input[name="id"]').val(),
            status: form.find('select[name="status"]').val()
        };
        if (!data.status) {
            alert('Please select a status.');
            return;
        }
        $.ajax({
            url: 'edit_imei.php',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function(resp) {
                if (resp.success) {
                    $('#editStatusModal').modal('hide');
                    location.reload();
                } else {
                    alert(resp.message || 'Failed to update status');
                }
            },
            error: function() {
                alert('An error occurred while updating status.');
            }
        });
    });
});

function editStatus(id, imei, status) {
    $('#editImeiId').val(id);
    $('#editImeiNumber').val(imei);
    $('#editCurrentStatus').val(status);
    $('#editStatusModal').modal('show');
}
</script>

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