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

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

if ($edit_id) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id=?");
    $stmt->execute([$edit_id]);
    $product = $stmt->fetch();
    if (!$product) { header('Location: products.php'); exit; }
}

$categories = $pdo->query("SELECT * FROM categories WHERE status=1 ORDER BY category_name")->fetchAll();
$brands = $pdo->query("SELECT * FROM brands WHERE status=1 ORDER BY brand_name")->fetchAll();
$suppliers = $pdo->query("SELECT * FROM suppliers WHERE status=1 ORDER BY company_name")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $brand_id = !empty($_POST['brand_id']) ? (int)$_POST['brand_id'] : null;
    $model = trim($_POST['model']);
    $sku = trim($_POST['sku']);
    $barcode = trim($_POST['barcode']);
    $product_type = $_POST['product_type'];

    // Auto-generate barcode if empty
    if (empty($barcode)) {
        $type_map = ['Phone' => 'phone', 'Accessory' => 'accessory', 'Spare Part' => 'spare_part'];
        $prod_type_key = $type_map[$product_type] ?? 'phone';
        $barcode = generateUniqueBarcode($prod_type_key);
    }
    $cost_price = (float)$_POST['cost_price'];
    $selling_price = (float)$_POST['selling_price'];
    $wholesale_price = (float)$_POST['wholesale_price'];
    $low_stock_qty = (int)$_POST['low_stock_qty'];
    $warranty_period = (int)$_POST['warranty_period'];
    $supplier_id = !empty($_POST['supplier_id']) ? (int)$_POST['supplier_id'] : null;
    $compatible_models = trim($_POST['compatible_models']);
    $description = trim($_POST['description']);
    $status = isset($_POST['status']) ? 1 : 0;
    $image = $product['product_image'] ?? '';

    // Handle image upload
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $allowed = ['jpg','jpeg','png','gif','webp'];
        if (in_array(strtolower($ext), $allowed)) {
            $filename = 'product_' . time() . '_' . uniqid() . '.' . $ext;
            $upload_path = __DIR__ . '/../assets/uploads/' . $filename;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                $image = 'assets/uploads/' . $filename;
                // Delete old image
                if ($product && $product['product_image'] && file_exists(__DIR__ . '/../' . $product['product_image'])) {
                    unlink(__DIR__ . '/../' . $product['product_image']);
                }
            }
        } else {
            $_SESSION['error'] = 'Invalid image format. Allowed: jpg, jpeg, png, gif, webp';
        }
    }

    if (empty($name) || empty($sku)) {
        $_SESSION['error'] = 'Product name and SKU are required.';
    } elseif (!empty($barcode)) {
        $dup_check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE barcode = ?" . ($edit_id ? " AND id != ?" : ""));
        $dup_params = [$barcode];
        if ($edit_id) $dup_params[] = $edit_id;
        $dup_check->execute($dup_params);
        if ($dup_check->fetchColumn() > 0) {
            $_SESSION['error'] = 'Barcode "' . htmlspecialchars($barcode) . '" is already in use by another product.';
        } else {
            try {
                if ($edit_id) {
                    $stmt = $pdo->prepare("UPDATE products SET category_id=?, brand_id=?, product_name=?, model=?, sku=?, barcode=?, product_type=?, cost_price=?, selling_price=?, wholesale_price=?, low_stock_qty=?, warranty_period_days=?, supplier_id=?, compatible_models=?, product_image=?, description=?, status=? WHERE id=?");
                    $stmt->execute([$category_id, $brand_id, $name, $model, $sku, $barcode, $product_type, $cost_price, $selling_price, $wholesale_price, $low_stock_qty, $warranty_period, $supplier_id, $compatible_models, $image, $description, $status, $edit_id]);
                    logActivity('Updated Product', 'Products', $edit_id);
                    $_SESSION['success'] = 'Product updated successfully.';
                } else {
                    $stmt = $pdo->prepare("INSERT INTO products (category_id, brand_id, product_name, model, sku, barcode, product_type, cost_price, selling_price, wholesale_price, low_stock_qty, warranty_period_days, supplier_id, compatible_models, product_image, description, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                    $stmt->execute([$category_id, $brand_id, $name, $model, $sku, $barcode, $product_type, $cost_price, $selling_price, $wholesale_price, $low_stock_qty, $warranty_period, $supplier_id, $compatible_models, $image, $description, $status]);
                    logActivity('Created Product', 'Products', $pdo->lastInsertId());
                    $_SESSION['success'] = 'Product created successfully.';
                }
                header('Location: products.php');
                exit;
            } catch (PDOException $e) {
                $_SESSION['error'] = 'Error: ' . $e->getMessage();
            }
        }
    }
}

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-<?= $edit_id ? 'edit' : 'plus' ?> me-2"></i><?= $edit_id ? 'Edit Product' : 'Add Product' ?></h4>

        <?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" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Product Name *</label>
                            <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($product['product_name'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Product Type *</label>
                            <select name="product_type" class="form-select" required>
                                <option value="Phone" <?= ($product['product_type'] ?? '') == 'Phone' ? 'selected' : '' ?>>Phone</option>
                                <option value="Accessory" <?= ($product['product_type'] ?? '') == 'Accessory' ? 'selected' : '' ?>>Accessory</option>
                                <option value="Spare Part" <?= ($product['product_type'] ?? '') == 'Spare Part' ? 'selected' : '' ?>>Spare Part</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Status</label>
                            <div class="form-check mt-2">
                                <input type="checkbox" name="status" class="form-check-input" id="statusCheck" <?= !isset($product) || $product['status'] ? 'checked' : '' ?>>
                                <label class="form-check-label" for="statusCheck">Active</label>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Category</label>
                            <select name="category_id" class="form-select">
                                <option value="">Select Category</option>
                                <?php foreach ($categories as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= ($product['category_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['category_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Brand</label>
                            <select name="brand_id" class="form-select">
                                <option value="">Select Brand</option>
                                <?php foreach ($brands as $b): ?>
                                <option value="<?= $b['id'] ?>" <?= ($product['brand_id'] ?? '') == $b['id'] ? 'selected' : '' ?>><?= htmlspecialchars($b['brand_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Supplier</label>
                            <select name="supplier_id" class="form-select">
                                <option value="">Select Supplier</option>
                                <?php foreach ($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>" <?= ($product['supplier_id'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['company_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Model</label>
                            <input type="text" name="model" class="form-control" value="<?= htmlspecialchars($product['model'] ?? '') ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">SKU / Barcode *</label>
                            <input type="text" name="sku" class="form-control" value="<?= htmlspecialchars($product['sku'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Barcode</label>
                            <div class="input-group">
                                <input type="text" name="barcode" class="form-control" id="barcodeField" value="<?= htmlspecialchars($product['barcode'] ?? '') ?>" placeholder="Enter or generate">
                                <button type="button" class="btn btn-outline-primary" id="generateBarcodeBtn" onclick="generateBarcode()"><i class="fas fa-qrcode me-1"></i>Generate</button>
                            </div>
                            <small class="text-muted" id="barcodeStatus"></small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Cost Price</label>
                            <input type="number" step="0.01" name="cost_price" class="form-control" value="<?= $product['cost_price'] ?? 0 ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Selling Price</label>
                            <input type="number" step="0.01" name="selling_price" class="form-control" value="<?= $product['selling_price'] ?? 0 ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Wholesale Price</label>
                            <input type="number" step="0.01" name="wholesale_price" class="form-control" value="<?= $product['wholesale_price'] ?? 0 ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Low Stock Alert</label>
                            <input type="number" name="low_stock_qty" class="form-control" value="<?= $product['low_stock_qty'] ?? 5 ?>">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Warranty (months)</label>
                            <input type="number" name="warranty_period" class="form-control" value="<?= $product['warranty_period_days'] ?? 0 ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Product Image</label>
                            <input type="file" name="image" class="form-control" accept="image/*">
                            <?php if (!empty($product['product_image'])): ?>
                            <small class="text-muted">Current: <a href="<?= BASE_URL ?><?= $product['product_image'] ?>" target="_blank">View</a></small>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-4 mb-3" id="compatibleModelsDiv">
                            <label class="form-label">Compatible Phone Models (for spare parts)</label>
                            <input type="text" name="compatible_models" class="form-control" value="<?= htmlspecialchars($product['compatible_models'] ?? '') ?>" placeholder="e.g. iPhone 12, Samsung S21">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($product['description'] ?? '') ?></textarea>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i><?= $edit_id ? 'Update' : 'Save' ?> Product</button>
                        <a href="products.php" class="btn btn-secondary">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    function toggleCompatibleModels() {
        var type = $('select[name="product_type"]').val();
        $('#compatibleModelsDiv').toggle(type === 'Spare Part');
    }
    $('select[name="product_type"]').change(toggleCompatibleModels);
    toggleCompatibleModels();

    <?php if (!$edit_id): ?>
    $('select[name="product_type"]').change(function() {
        var val = $(this).val();
        $('#barcodeField').val('');
        $('#barcodeStatus').text('');
    });
    <?php endif; ?>
});

function generateBarcode() {
    var type = $('select[name="product_type"]').val();
    var typeMap = {'Phone':'phone','Accessory':'accessory','Spare Part':'spare_part'};
    var mappedType = typeMap[type] || '';

    if (!mappedType) {
        $('#barcodeStatus').text('Please select a product type first.').css('color','red');
        return;
    }

    var btn = $('#generateBarcodeBtn');
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Generating...');

    $.get('<?= BASE_URL ?>products/generate_barcode.php', { product_type: mappedType }, function(data) {
        if (data.success) {
            $('#barcodeField').val(data.barcode);
            $('#barcodeStatus').text('Barcode generated: ' + data.barcode).css('color','green');
        } else {
            $('#barcodeStatus').text(data.message || 'Failed to generate barcode.').css('color','red');
        }
    }, 'json').fail(function() {
        $('#barcodeStatus').text('Server error. Try again.').css('color','red');
    }).always(function() {
        btn.prop('disabled', false).html('<i class="fas fa-qrcode me-1"></i>Generate');
    });
}
</script>

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