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

$pdo = getDB();

// POST handler - JSON response
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
    $imei_input = trim($_POST['imei_numbers'] ?? '');
    $serial_number = trim($_POST['serial_number'] ?? '');

    if (!$product_id) {
        echo json_encode(['success' => false, 'message' => 'Product is required.']);
        exit;
    }

    // Validate product is phone type
    $stmt = $pdo->prepare("SELECT product_type FROM products WHERE id = ? AND status = 1");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();

    if (!$product) {
        echo json_encode(['success' => false, 'message' => 'Product not found or inactive.']);
        exit;
    }

    if ($product['product_type'] !== 'Phone') {
        echo json_encode(['success' => false, 'message' => 'IMEI can only be added to phone products.']);
        exit;
    }

    if (empty($imei_input)) {
        echo json_encode(['success' => false, 'message' => 'At least one IMEI number is required.']);
        exit;
    }

    $imei_numbers = array_filter(array_map('trim', explode("\n", $imei_input)));
    $imei_numbers = array_map(function($v) { return trim($v); }, $imei_numbers);
    $imei_numbers = array_filter($imei_numbers);

    if (empty($imei_numbers)) {
        echo json_encode(['success' => false, 'message' => 'Valid IMEI numbers are required.']);
        exit;
    }

    $added = 0;
    $errors = [];

    foreach ($imei_numbers as $imei) {
        // Validate unique
        $check = $pdo->prepare("SELECT COUNT(*) FROM product_imei WHERE imei_number = ?");
        $check->execute([$imei]);
        if ($check->fetchColumn() > 0) {
            $errors[] = 'IMEI ' . htmlspecialchars($imei) . ' already exists.';
            continue;
        }

        try {
            $stmt = $pdo->prepare("INSERT INTO product_imei (product_id, imei_number, serial_number, status) VALUES (?, ?, ?, 'Available')");
            $stmt->execute([$product_id, $imei, $serial_number ?: null]);
            $added++;
        } catch (PDOException $e) {
            $errors[] = 'Failed to add IMEI ' . htmlspecialchars($imei) . ': ' . $e->getMessage();
        }
    }

    if ($added > 0) {
        logActivity('Added IMEI(s)', 'Products', $product_id, 'Added ' . $added . ' IMEI(s) to product #' . $product_id);
    }

    $message = $added . ' IMEI(s) added successfully.';
    if (!empty($errors)) {
        $message .= ' Errors: ' . implode(' | ', $errors);
    }

    echo json_encode(['success' => $added > 0, 'message' => $message]);
    exit;
}

// GET handler - HTML form page
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';

$phone_products = $pdo->query("SELECT id, product_name, model FROM products WHERE product_type = 'Phone' AND status = 1 ORDER BY product_name")->fetchAll();
?>
<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-plus me-2"></i>Add IMEI / Serial Numbers</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; ?>

        <div class="card">
            <div class="card-body">
                <form method="POST" action="add_imei.php">
                    <div class="mb-3">
                        <label class="form-label">Product *</label>
                        <select name="product_id" class="form-select select2" required>
                            <option value="">Select Phone Product</option>
                            <?php foreach ($phone_products as $p): ?>
                            <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['product_name'] . ' (' . $p['model'] . ')') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">IMEI Number(s) *</label>
                        <textarea name="imei_numbers" class="form-control" rows="6" placeholder="Enter one IMEI number per line" required></textarea>
                        <small class="text-muted">Enter one IMEI number 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="Will apply to all IMEIs above">
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Add IMEI(s)</button>
                    <a href="imei_stock.php" class="btn btn-secondary">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
