<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$product_id = intval($_GET['id'] ?? 0);
if (!$product_id) {
    echo "<div class='alert alert-danger'>Invalid Product ID.</div>";
    exit;
}

// ================= FETCH PRODUCT =================
$stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$result = $stmt->get_result();
$product = $result->fetch_assoc();

if (!$product) {
    echo "<div class='alert alert-danger'>Product not found.</div>";
    exit;
}

// ================= FETCH CATEGORIES & DEPARTMENTS =================
$categories = $conn->query("SELECT * FROM categories ORDER BY name ASC");
$departments = $conn->query("SELECT * FROM departments ORDER BY name ASC");

// ================= UPDATE PRODUCT =================
if (isset($_POST['update_product'])) {
    $name = $_POST['name'] ?? '';
    $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : NULL;
    $department_id = !empty($_POST['department_id']) ? intval($_POST['department_id']) : NULL;
    $buying_price = floatval($_POST['buying_price'] ?? 0);
    $selling_price = floatval($_POST['selling_price'] ?? 0);
    $vat_rate = floatval($_POST['vat_rate'] ?? 0);
    $quantity = intval($_POST['quantity'] ?? 0);
    $min_level = intval($_POST['min_level'] ?? 0);
    $barcode = $_POST['barcode'] ?? '';
    $raw_materials = $_POST['raw_materials'] ?? 'No';
    $can_sell = isset($_POST['can_sell']) ? 1 : 0;

    $stmtUpdate = $conn->prepare("
        UPDATE products SET 
            name=?, category_id=?, buying_price=?, selling_price=?, vat_rate=?, min_level=?, barcode=?, raw_materials=?, can_sell_when_out_of_stock=?
        WHERE id=?
    ");
    $stmtUpdate->bind_param(
        "siiddiisii",
        $name,
        $category_id,
        $buying_price,
        $selling_price,
        $vat_rate,
        $min_level,
        $barcode,
        $raw_materials,
        $can_sell,
        $product_id
    );
    if ($stmtUpdate->execute()) {

        // Update stock quantity in main store
        $stmtStock = $conn->prepare("
            UPDATE product_stock SET quantity=?, department_id=? 
            WHERE product_id=? AND store_id=1
        ");
        $stmtStock->bind_param("iii", $quantity, $department_id, $product_id);
        $stmtStock->execute();

        echo "<script>alert('Product updated successfully');window.location='products.php';</script>";
        exit;
    } else {
        echo "Error updating product: " . $stmtUpdate->error;
    }
}
?>

<div class="container mt-4">
    <h3 class="text-center">Edit Product</h3>
    <hr>

    <form method="POST" class="row g-3">
        <div class="col-md-3">
            <input type="hidden" class="form-control" value="<?= $product['sku'] ?>" readonly>
        </div>
        <div class="col-md-3">
            Product Name
            <input type="text" name="name" class="form-control" placeholder="Product Name" value="<?= $product['name'] ?>" required>
        </div>
        <div class="col-md-3">
            Category
            <select name="category_id" class="form-control" required>
                <option value="">-- Select Category --</option>
                <?php
                $categories->data_seek(0);
                while ($cat = $categories->fetch_assoc()):
                    $selected = ($cat['id'] == $product['category_id']) ? 'selected' : '';
                ?>
                    <option value="<?= $cat['id'] ?>" <?= $selected ?>><?= $cat['name'] ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-3">
            Department
            <select name="department_id" class="form-control" required>
                <option value="">-- Select Department --</option>
                <?php
                $departments->data_seek(0);
                while ($dep = $departments->fetch_assoc()):
                    $selected = ($dep['id'] == ($conn->query("SELECT department_id FROM product_stock WHERE product_id={$product_id} AND store_id=1")->fetch_assoc()['department_id'] ?? 0)) ? 'selected' : '';
                ?>
                    <option value="<?= $dep['id'] ?>" <?= $selected ?>><?= $dep['name'] ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-3"><input type="hidden" name="barcode" class="form-control" placeholder="Barcode" value="<?= $product['barcode'] ?>"></div>
        <div class="col-md-2">Cost Price<input type="number" step="0.01" name="buying_price" class="form-control" placeholder="Buying Price" value="<?= $product['buying_price'] ?>"></div>
        <div class="col-md-2">Selling Price<input type="number" step="0.01" name="selling_price" class="form-control" placeholder="Selling Price" value="<?= $product['selling_price'] ?>"></div>
        <div class="col-md-2"><input type="hidden" step="0.01" name="vat_rate" class="form-control" placeholder="VAT Rate (%)" value="<?= $product['vat_rate'] ?>"></div>
        <div class="col-md-2">Quantity<input type="number" name="quantity" class="form-control" placeholder="Quantity" value="<?= $conn->query("SELECT quantity FROM product_stock WHERE product_id={$product_id} AND store_id=1")->fetch_assoc()['quantity'] ?? 0 ?>"></div>
        <div class="col-md-2">Minimum<input type="number" name="min_level" class="form-control" placeholder="Min Level" value="<?= $product['min_level'] ?>"></div>
        <div class="col-md-2">
            Raw Material?
            <select name="raw_materials" class="form-control" required>
                <option value="" disabled <?= !$product['raw_materials'] ? 'selected' : '' ?>>Raw Material?</option>
                <option value="No" <?= $product['raw_materials']=='No' ? 'selected' : '' ?>>No</option>
                <option value="Yes" <?= $product['raw_materials']=='Yes' ? 'selected' : '' ?>>Yes</option>
            </select>
        </div>
        <div class="col-md-3 d-flex align-items-center mt-4">
            <input type="checkbox" name="can_sell" id="can_sell" class="mr-2" <?= $product['can_sell_when_out_of_stock'] ? 'checked' : '' ?>>
            <label for="can_sell">Can sell when out of stock</label>
        </div>
        <div class="col-md-2 mt-4"><button type="submit" name="update_product" class="btn btn-success w-100">Update Product</button></div>
    </form>
</div>

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