<?php
include 'db.php';
include 'auth_check.php';

$msg = "";

// Get product ID
if (!isset($_GET['id'])) {
    die("Product ID is required.");
}

$id = intval($_GET['id']);

// Fetch existing product
$result = $conn->query("SELECT * FROM purchase_stock WHERE id=$id");
if ($result->num_rows == 0) {
    die("Product not found.");
}
$product = $result->fetch_assoc();

// Fetch existing fault remarks
$fault_remarks = '';
$fault_res = $conn->query("SELECT remarks FROM fault_stock WHERE purchase_stock_id=$id LIMIT 1");
if ($fault_res && $fault_res->num_rows > 0) {
    $fault_row = $fault_res->fetch_assoc();
    $fault_remarks = $fault_row['remarks'] ?? '';
}

// ✅ Calculate available qty
$available_sql = "
    SELECT 
        (ps.qty 
         - COALESCE((SELECT SUM(o2.qty) FROM outward_stock o2 WHERE o2.purchase_stock_id = ps.id), 0)
         - COALESCE((SELECT SUM(f.qty) FROM fault_stock f WHERE f.purchase_stock_id = ps.id), 0)
        ) AS available_qty
    FROM purchase_stock ps
    WHERE ps.id = $id
";
$avail_res = $conn->query($available_sql);
$available_qty = 0;
if ($avail_res && $avail_res->num_rows > 0) {
    $avail_row = $avail_res->fetch_assoc();
    $available_qty = $avail_row['available_qty'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $invoice = $conn->real_escape_string($_POST['invoice_number']);
    $incoming_date = $conn->real_escape_string($_POST['incoming_date']);
    $courier = $conn->real_escape_string($_POST['courier_name']);
    $company_name = $conn->real_escape_string($_POST['company_name']);
    $item = $conn->real_escape_string($_POST['item_name']);
    $particular = $conn->real_escape_string($_POST['particular_name']);
    $spec = $conn->real_escape_string($_POST['specification']);
    $model = $conn->real_escape_string($_POST['model_number']);

    $qty = floatval($_POST['qty']);
    $rate = floatval($_POST['rate']);
    $gst = floatval($_POST['gst']);

    $fault_raw = isset($_POST['fault_count']) ? trim($_POST['fault_count']) : '';
    if ($fault_raw === '') {
        $fault_count = null;
        $fault_count_sql = "NULL";
    } else {
        $fault_count = intval($fault_raw);
        $fault_count_sql = $fault_count;
    }

    $fault_remarks = isset($_POST['remarks']) ? $conn->real_escape_string(trim($_POST['remarks'])) : '';

    // ✅ Backend validation
    if ($qty < 0) {
        $msg = "Quantity cannot be negative.";
    } elseif ($fault_count !== null && $fault_count < 0) {
        $msg = "Fault Quantity cannot be negative.";
    } elseif ($fault_count !== null && $fault_count > $qty) {
        $msg = "Fault Quantity cannot exceed Purchase Quantity.";
    } elseif ($fault_count !== null && $fault_count > 0 && $fault_remarks === '') {
        $msg = "Remarks are required for fault quantity.";
    } else {
        // 🔹 Get outward qty for this purchase stock
        $outward_sql = "SELECT COALESCE(SUM(qty),0) as total_outward 
                        FROM outward_stock WHERE purchase_stock_id = $id";
        $outward_res = $conn->query($outward_sql);
        $outward_qty = ($outward_res && $outward_res->num_rows > 0) 
                        ? $outward_res->fetch_assoc()['total_outward'] 
                        : 0;

        // 🔹 Check available
        $available_qty_check = $qty - $outward_qty - ($fault_count ?? 0);

        if ($available_qty_check < 0) {
            $msg = "⚠️ Fault quantity cannot exceed available stock (" . ($qty - $outward_qty) . ")";
        } else {
            $total = ($qty * $rate) + $gst;
            $conn->begin_transaction();

            try {
                // Update purchase_stock
                $sql = "UPDATE purchase_stock SET
                            invoice_number='$invoice',
                            incoming_date='$incoming_date',
                            courier_name='$courier',
                            company_name='$company_name',
                            item_name='$item',
                            particular_name='$particular',
                            specification='$spec',
                            model_number='$model',
                            qty=$qty,
                            rate=$rate,
                            gst=$gst,
                            total=$total,
                            fault_count=$fault_count_sql
                        WHERE id=$id";

                if (!$conn->query($sql)) throw new Exception($conn->error);

                if ($fault_count === null) {
                    // delete only if both conditions match
                    $conn->query("DELETE FROM fault_stock 
                                  WHERE purchase_stock_id=$id 
                                  AND company_name='$company_name' 
                                  AND given_to='Nilatech'");
                } else {
                    $new_given_to = "Nilatech";
                    $res = $conn->query("SELECT id FROM fault_stock 
                                         WHERE purchase_stock_id=$id 
                                         AND company_name='$company_name' 
                                         AND given_to='$new_given_to'");

                    if ($res->num_rows > 0) {
                        // ✅ Update only matching record
                        $conn->query("UPDATE fault_stock 
                                    SET item_name='$item',
                                        particular_name='$particular',
                                        specification='$spec',
                                        model_number='$model',
                                        qty=$fault_count, 
                                        remarks='$fault_remarks', 
                                        fault_date=NOW(), 
                                        updated_at=NOW() 
                                    WHERE purchase_stock_id=$id 
                                      AND company_name='$company_name' 
                                      AND given_to='$new_given_to'");
                    } else {
                        // Insert new record
                        $conn->query("INSERT INTO fault_stock 
                                    (purchase_stock_id, company_name, item_name, model_number, particular_name, specification, qty, remarks, fault_date, given_to, created_at, updated_at)
                                    VALUES ($id, '$company_name', '$item', '$model', '$particular', '$spec', $fault_count, '$fault_remarks', NOW(), '$new_given_to', NOW(), NOW())");
                    }
                }

                $conn->commit();
                header("Location: inventory.php");
                exit;
            } catch (Exception $e) {
                $conn->rollback();
                $msg = "Error: " . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit Product</title>
    <link rel="icon" type="image/png" href="assets/logo/logo_icon.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<?php
if (session_status() == PHP_SESSION_NONE) session_start();
include 'navbar.php';
?>

<div class="container mt-3">
    <h2 class="text-center text-success mb-4">Edit Product</h2>

    <?php if($msg != "") { ?>
        <div class="alert alert-info text-center"><?php echo htmlspecialchars($msg); ?></div>
    <?php } ?>

    <form method="POST">
        <div class="row g-3 mb-3">
            <div class="col-md-4">
                <label class="form-label">Invoice Number</label>
                <input type="text" class="form-control" name="invoice_number" value="<?php echo htmlspecialchars($product['invoice_number']); ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">Date</label>
                <input type="date" class="form-control" name="incoming_date" value="<?php echo htmlspecialchars($product['incoming_date']); ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">Courier Name</label>
                <input type="text" class="form-control" name="courier_name" value="<?php echo htmlspecialchars($product['courier_name']); ?>">
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-4">
                <label class="form-label">Company Name</label>
                <input type="text" class="form-control" name="company_name" value="<?php echo htmlspecialchars($product['company_name']); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">Item Name</label>
                <input type="text" class="form-control" name="item_name" value="<?php echo htmlspecialchars($product['item_name']); ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">Particular</label>
                <input type="text" class="form-control" name="particular_name" value="<?php echo htmlspecialchars($product['particular_name']); ?>">
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-4">
                <label class="form-label">Specification</label>
                <input type="text" class="form-control" name="specification" value="<?php echo htmlspecialchars($product['specification']); ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">Model</label>
                <input type="text" class="form-control" name="model_number" value="<?php echo htmlspecialchars($product['model_number']); ?>">
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-2">
                <label class="form-label">Qty</label>
                <input type="number" class="form-control" name="qty" id="qty" value="<?php echo htmlspecialchars($product['qty']); ?>" min="0" step="any" required>
            </div>
            <div class="col-md-2">
                <label class="form-label">Rate</label>
                <input type="number" step="0.01" class="form-control" name="rate" value="<?php echo htmlspecialchars($product['rate']); ?>" required>
            </div>
            <div class="col-md-2">
                <label class="form-label">GST %</label>
                <input type="number" step="0.01" class="form-control" name="gst" value="<?php echo htmlspecialchars($product['gst']); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Fault Count</label>
                <input type="number" class="form-control" name="fault_count" id="fault_count"
                    value="<?= htmlspecialchars($product['fault_count'] ?? 0) ?>"
                    min="0">
                <small class="text-muted" id="availableText">Available: <?= $available_qty ?></small>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label">Fault Remarks</label>
            <textarea class="form-control" name="remarks" rows="2"><?php echo htmlspecialchars($fault_remarks, ENT_QUOTES); ?></textarea>
        </div>

        <div class="text-center mt-3">
            <button type="submit" class="btn btn-success">Update Product</button>
            <a href="inventory.php" class="btn btn-secondary">Back</a>
        </div>
    </form>
</div>

<script>
    const qtyInput = document.getElementById('qty');
    const faultInput = document.getElementById('fault_count');
    const availableText = document.getElementById('availableText');

    //Outward qty = Purchase - Available - Fault
    let outwardQty = <?php echo (int)($product['qty'] - $available_qty - ($product['fault_count'] ?? 0)); ?>;

    function updateAvailable() {
        let qty = parseFloat(qtyInput.value) || 0;
        let fault = parseInt(faultInput.value) || 0;

        let available = qty - outwardQty - fault;

        if (available < 0) {
            availableText.textContent = "Fault exceeds available stock!";
            availableText.classList.add("text-danger");
            availableText.classList.remove("text-muted");
        } else {
            availableText.textContent = "Available: " + available;
            availableText.classList.add("text-success");
            availableText.classList.remove("text-danger");
        }
    }

    faultInput.addEventListener('input', updateAvailable);
    qtyInput.addEventListener('input', updateAvailable);
    updateAvailable();

    // Prevent form submission if invalid
    document.querySelector("form").addEventListener("submit", function (e) {
        let qty = parseFloat(qtyInput.value) || 0;
        let fault = parseInt(faultInput.value) || 0;
        let available = qty - outwardQty - fault;

        if (available < 0) {
            alert("Fault quantity cannot exceed available stock (" + (qty - outwardQty) + ")");
            e.preventDefault(); // Block form submission
        }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
