<?php
// Create or get user token
if (!isset($_COOKIE['user_token'])) {
    $token = bin2hex(random_bytes(16));
    setcookie('user_token', $token, time() + (86400 * 365), "/");
    $_COOKIE['user_token'] = $token;
}
$user_token = $_COOKIE['user_token'];

include '../inc/db.php';

$product_id = (int)($_GET['product_id'] ?? 0);

/* FETCH PRODUCT MATERIALS */
$sqftMaterials = [];
$lnftMaterials = [];

if ($product_id > 0) {

    $res = mysqli_query($conn, "
        SELECT pm.*, sm.name, sm.slug
        FROM product_materials pm
        JOIN stone_materials sm ON sm.id = pm.material_id
        WHERE pm.product_id = $product_id
        AND pm.status='active'
    ");

    while ($row = mysqli_fetch_assoc($res)) {

        if ($row['calc_type'] == 'sqft') {
            $sqftMaterials[$row['slug']] = [
                'label' => $row['name'],
                'value' => (float)$row['sqft_value']
            ];
        }

        if ($row['calc_type'] == 'lnft') {
            $lnftMaterials[$row['slug']] = [
                'label' => $row['name'],
                'value' => (float)$row['lnft_value']
            ];
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stone Calculator</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="stone_cal.css">
</head>

<body>

<div class="page-wrapper">
<div class="calculator">

<h2>Stone Calculator</h2>
<p class="desc">Estimate tonnage for sawn chop, ledge stone, patio & drystack</p>

<!-- SQFT -->
<h3 style="color:#fff;">Sqft Tons Calculator</h3>

<div class="grid">
    <div>
        <input type="number" id="sqftInput" placeholder="Enter Sqft Needed">
    </div>

    <div>
        <select id="materialSelect">
            <option value="">-- Select SQFT Material --</option>
            <?php foreach ($sqftMaterials as $slug => $m): ?>
                <option value="<?= $slug ?>">
                    <?= htmlspecialchars($m['label']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
</div>

<button onclick="calcSqft()">Calculate Tons</button>
<div id="sqftResult" class="result"></div>

<hr style="margin:30px 0; border-color:#333;">

<!-- LNFT -->
<h3 style="color:#fff;">Linear Ft Tons Calculator</h3>

<div class="grid">
    <div>
        <input type="number" id="lnftInput" placeholder="Enter Linear Ft">
    </div>

    <div>
        <select id="sizeSelect">
            <option value="">-- Select LNFT Material --</option>
            <?php foreach ($lnftMaterials as $slug => $m): ?>
                <option value="<?= $slug ?>">
                    <?= htmlspecialchars($m['label']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
</div>

<button onclick="calcLnft()">Calculate Tons</button>
<div id="lnftResult" class="result"></div>

<p class="disclaimer">
⚠️ It is recommended to include a 5% margin of error in the quantities calculated to account for potential spillage and breakage.
</p>

</div>

<div id="stoneHistoryTable"></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
 const productId = <?= (int)$product_id ?>;   
const userToken = "<?= $user_token ?>";

// SAFE OBJECTS
const sqftValues = <?= json_encode($sqftMaterials) ?>;
const lnftValues = <?= json_encode($lnftMaterials) ?>;

/* ---------------- SQFT ---------------- */
function calcSqft() {

    let sqft = parseFloat(document.getElementById("sqftInput").value);
    let material = document.getElementById("materialSelect").value;

    let data = sqftValues[material];

    if (!sqft || !material || !data) {
        Swal.fire('Error', 'Invalid material or input', 'error');
        return;
    }

    let tons = sqft / data.value;

    showResult("sqftResult",
        "You need approximately <strong>" + tons.toFixed(2) + " tons</strong>"
    );

    saveStoneCalculation("sqft", sqft, null, material, null, tons);
}

/* ---------------- LNFT ---------------- */
function calcLnft() {

    let lnft = parseFloat(document.getElementById("lnftInput").value);
    let size = document.getElementById("sizeSelect").value;

    let data = lnftValues[size];

    if (!lnft || !size || !data) {
        Swal.fire('Error', 'Invalid size or input', 'error');
        return;
    }

    let tons = lnft / data.value;

    showResult("lnftResult",
        "You need approximately <strong>" + tons.toFixed(2) + " tons</strong>"
    );

    saveStoneCalculation("lnft", null, lnft, null, size, tons);
}

/* ---------------- SAVE ---------------- */
function saveStoneCalculation(type, sqft, lnft, material, size, tons) {

    fetch("save_stone_calculation.php", {
        method: "POST",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body: new URLSearchParams({
            calc_type: type,
            sqft,
            lnft,
            material,
            stone_size: size,
            tons,
            token: userToken,
            product_id: productId   // ✅ ADD THIS
        })
    }).then(() => loadStoneTable());
}

/* ---------------- UI ---------------- */
function showResult(id, text) {
    let box = document.getElementById(id);
    box.innerHTML = text;
    box.classList.add("visible");
}

/* ---------------- HISTORY ---------------- */
function loadStoneTable() {

    fetch("load_stone_table.php?token=" + userToken)
        .then(res => res.text())
        .then(html => {

            const container = document.getElementById("stoneHistoryTable");
            container.innerHTML = html;
        });
}

/* =========================
   DELETE (FIXED - DELEGATION)
========================= */
document.addEventListener("click", function (e) {

    if (e.target.classList.contains("delBtn")) {

        let id = e.target.dataset.id;

        Swal.fire({
            title: 'Delete this record?',
            text: "This cannot be undone.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#555',
            background: '#1a1a1a',
            color: '#fff',
        }).then(result => {

            if (result.isConfirmed) {

                fetch("delete_stone_calculation.php", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: new URLSearchParams({
                        id: id,
                        token: userToken
                    })
                })
                .then(res => res.text())
                .then(resp => {

                    loadStoneTable();

                    Swal.fire({
                        title: "Deleted!",
                        icon: "success",
                        background: "#1a1a1a",
                        color: "#fff",
                    });
                });
            }
        });
    }
});

loadStoneTable();
</script>

</body>
</html>
