<?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'];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aggregate Calculator</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    <style>
    :root {
        --red: #d40000;
        --red-light: #ff3c3c;
        --dark-bg: #111;
        --gray-bg: #1a1a1a;
        --text-light: #f1f1f1;
        --text-muted: #aaa;
    }

    body {
        font-family: "Poppins", sans-serif;
        margin: 0;
        background: url('https://advancedemolink.com/Ivan/wp-content/uploads/2025/10/fotr-bg.png') center/cover fixed, #0b0b0b;
        color: var(--text-light);
        min-height: 100vh;
    }

    .page-wrapper {
        background: rgba(0, 0, 0, 0.65);
        backdrop-filter: blur(5px);
        min-height: 100vh;
        padding: 80px 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;
    }

    .calculator {
        width: 100%;
        max-width: 700px;
        background: rgba(30, 30, 30, 0.95);
        border-radius: 18px;
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.6);
        padding: 40px 35px;
        animation: fadeIn .8s ease;
        text-align: center;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(15px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    h2 {
        color: #fff;
        font-weight: 600;
        margin-bottom: 6px;
        font-size: 28px;
    }

    p.desc {
        color: var(--text-muted);
        margin-bottom: 30px;
        font-size: 15px;
    }

    .grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        align-items: center;
    }

    .grid>div {
        width: 100%;
        display: flex;
    }

    .grid input,
    .grid select {
        flex: 1;
        min-width: 0;
    }

    @media(max-width: 768px) {
        .grid {
            grid-template-columns: 1fr;
        }
    }


    input,
    select {
        width: 100%;
        padding: 14px 12px;
        border: 1px solid #333;
        border-radius: 10px;
        font-size: 15px;
        background: #222;
        color: var(--text-light);
        transition: .2s;
    }

    input:focus,
    select:focus {
        border-color: var(--red);
        outline: none;
        box-shadow: 0 0 8px rgba(212, 0, 0, 0.3);
    }

    button {
        width: 100%;
        margin-top: 25px;
        padding: 14px;
        border: none;
        border-radius: 10px;
        background: linear-gradient(135deg, var(--red), var(--red-light));
        color: #fff;
        font-weight: 600;
        font-size: 16px;
        cursor: pointer;
        transition: .3s;
        letter-spacing: 0.3px;
    }

    button:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(212, 0, 0, 0.45);
    }

    .result {
        margin-top: 25px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 12px;
        padding: 20px;
        border: 1px solid #333;
        display: none;
        text-align: left;
    }

    .result.visible {
        display: block;
    }

    .result strong {
        color: var(--red-light);
    }

    .table-container {
        width: 95%;
        max-width: 900px;
        margin: 50px auto 0;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        background: rgba(30, 30, 30, 0.95);
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
        color: var(--text-light);
    }

    th,
    td {
        padding: 12px 15px;
        text-align: center;
        border-bottom: 1px solid #333;
    }

    th {
        background: var(--red);
        color: white;
        font-weight: 500;
    }

    .delBtn {
        background: #ff4d4d;
        border: none;
        color: white;
        padding: 6px 10px;
        border-radius: 6px;
        cursor: pointer;
        transition: 0.2s ease;
        margin-top: 0px !important;
    }

    .delBtn:hover {
        background: #e60000;
        transform: scale(1.05);
    }

    @media(max-width:600px) {
        .grid {
            grid-template-columns: 1fr;
        }

        .calculator {
            padding: 30px 20px;
        }
    }
    </style>
</head>

<body>

    <div class="page-wrapper">
        <div class="calculator">
            <h2>🧮 Aggregate Calculator</h2>
            <p class="desc">Quickly estimate cubic yards and tons</p>
            <div class="grid">
                <div><input type="number" id="width" min="0" step="0.01" placeholder="Width (ft)"></div>
                <div><input type="number" id="length" min="0" step="0.01" placeholder="Length (ft)"></div>
                <div><input type="number" id="depth" min="0" step="0.01" placeholder="Depth (inches)"></div>
                <div><select id="material"></select></div>
            </div>


            <button id="calcBtn">Calculate</button>

            <div id="result" class="result">
                <p><strong>Material:</strong> <span id="resMaterial"></span></p>
                <p><strong>Depth (ft):</strong> <span id="resDepth"></span></p>
                <p><strong>Cubic Feet:</strong> <span id="resCF"></span></p>
                <p><strong>Cubic Yards:</strong> <span id="resCY"></span></p>
                <p><strong>Tons Required:</strong> <span id="resTons"></span></p>
            </div>
        </div>

        <div class="table-container" id="historyTable"></div>
    </div>

    <script>
    const userToken = "<?php echo $user_token; ?>";

    // Material list
    const materials = {
        "Crushed Limestone 1\"": 1.25,
        "Crushed Limestone 3/8\"": 1.30,
        "Top Soil / Dirt": 1.20,
        "Native Mulch": 0.50,
        "Dyed Mulch": 0.45,
        "Landscape Mix": 1.25,
        "Growers Mix": 1.10,
        "River Gravel": 1.20,
        "Pea Gravel (3/8\")": 1.20,
        "Black Star Gravel": 1.30,
        "Decomposed Granite": 1.30,
        "Granite Gravel": 1.20,
        "Sand (Masonry/Concrete)": 1.30,
        "Roadbase": 1.30,
        "Screened Chocolate Loam": 1.20,
        "Remix": 1.30,
        "Mexican Beach Pebble": 1.20,
        "White Crushed Marble": 1.25,
        "Colorado Salt & Pepper Rock": 1.25,
        "Arizona Rainbow Rock": 1.25
    };

const matSelect = document.getElementById("material");

Object.entries(materials).forEach(([name, dens]) => {
  // Remove inch/fraction indicators such as 1", 3/8", (3/8"), etc.
  const cleanName = name
    .replace(/\s*\(?\d+\/?\d*"?\)?/g, "") // removes things like (3/8"), 1", etc.
    .replace(/\s{2,}/g, " ")               // remove double spaces
    .trim();                               // trim spaces

  const opt = document.createElement("option");
  opt.value = dens;          // still stores density for calculation
  opt.textContent = cleanName; // show clean name only
  matSelect.appendChild(opt);
});

matSelect.value = 1.25;



    function num(v) {
        return parseFloat(v) || 0;
    }

    function round(n, p = 3) {
        return Math.round(n * 10 ** p) / 10 ** p;
    }

    function calculate() {
        const w = num(document.getElementById("width").value);
        const l = num(document.getElementById("length").value);
        const d_in = num(document.getElementById("depth").value);
        const density = num(matSelect.value);

        if (w <= 0 || l <= 0 || d_in <= 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Missing Values',
                text: 'Please fill all fields correctly before calculating!',
                background: '#1a1a1a',
                color: '#fff',
                confirmButtonColor: '#d33'
            });
            return;
        }

        const depth_ft = d_in / 12;
        const cubic_feet = w * l * depth_ft;
        const cubic_yards = cubic_feet / 27;
        const tons = cubic_yards * density;

        document.getElementById("resMaterial").textContent = matSelect.options[matSelect.selectedIndex].text.split(
            " — ")[0];
        document.getElementById("resDepth").textContent = round(depth_ft);
        document.getElementById("resCF").textContent = round(cubic_feet);
        document.getElementById("resCY").textContent = round(cubic_yards);
        document.getElementById("resTons").textContent = round(tons) + " tons";

        document.getElementById("result").classList.add("visible");

        // Save to database
        fetch("save_calculation.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: new URLSearchParams({
                width: w,
                length: l,
                depth_in: d_in,
                depth_ft,
                cubic_feet,
                cubic_yards,
                tons,
                material: matSelect.options[matSelect.selectedIndex].text.split(" — ")[0],
                token: userToken
            })
        }).then(() => {
            loadTable();
            // Clear fields
            document.getElementById("width").value = "";
            document.getElementById("length").value = "";
            document.getElementById("depth").value = "";
            matSelect.selectedIndex = 0;
            
            setTimeout(() => {
      document.getElementById("result").classList.remove("visible");
    }, 60000);
        });
    }


    document.getElementById("calcBtn").addEventListener("click", calculate);

    function loadTable() {
        fetch("load_table.php?token=" + userToken)
            .then(res => res.text())
            .then(html => {
                const container = document.getElementById("historyTable");
                container.innerHTML = html;
                container.querySelectorAll(".delBtn").forEach(btn => {
                    btn.addEventListener("click", () => {
                        Swal.fire({
                            title: 'Delete this record?',
                            text: "This action cannot be undone!",
                            icon: 'warning',
                            showCancelButton: true,
                            confirmButtonColor: '#d33',
                            cancelButtonColor: '#555',
                            background: '#1a1a1a',
                            color: '#fff',
                            confirmButtonText: 'Yes, delete it',
                            cancelButtonText: 'Cancel'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                fetch("delete_calculations.php", {
                                    method: "POST",
                                    headers: {
                                        "Content-Type": "application/x-www-form-urlencoded"
                                    },
                                    body: new URLSearchParams({
                                        id: btn.dataset.id,
                                        token: userToken
                                    })
                                }).then(() => {
                                    loadTable();
                                    Swal.fire({
                                        title: 'Deleted!',
                                        text: 'The record has been removed.',
                                        icon: 'success',
                                        background: '#1a1a1a',
                                        color: '#fff',
                                        confirmButtonColor: '#d33'
                                    });
                                });
                            }
                        });
                    });
                });
            });
    }
    loadTable();
    </script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</body>

</html>