Wednesday, 28 January 2026

Estimator ( Cost Estimator)

 <?php

// ------------------- PHP SECTION -------------------

// Load CSV into array

function loadCSV($filename) {

    $rows = array_map('str_getcsv', file($filename));

    $header = array_shift($rows);

    $csv = [];

    foreach ($rows as $row) {

        $csv[] = array_combine($header, $row);

    }

    return $csv;

}


$data = loadCSV("estimator.csv");


function loadXML($filename) {

    $xml = simplexml_load_file($filename) or die("Unable to load XML file");

    $data = [];


    foreach ($xml->Estimator as $est) {

        $data[] = [

            "Techstack"   => trim((string)$est->Techstack),

            "Platform"    => trim((string)$est->Platform),

            "Env"         => trim((string)$est->Env),

            "T-Shirt Size"=> trim((string)$est->TShirtSize),

            "Compute"     => trim((string)$est->Compute),

            "License"     => trim((string)$est->License),

            "Input Notes" => trim((string)$est->InputNotes)

        ];

    }

    return $data;

}


//$data = loadXML("estimator.xml");



// Handle AJAX requests


if (isset($_GET['action'])) {

    header('Content-Type: application/json');

    $action = $_GET['action'];


    // Techstack

/*

    if ($action == 'getTechstack') {

        $techs = [];

        foreach ($data as $row) {

            if (!empty(trim($row['Techstack']))) {

                $techs[] = trim($row['Techstack']);

            }

        }

        echo json_encode(array_values(array_unique($techs)));

        exit;

    }

*/

if ($action == 'getTechstack') {

    $techs = [];

    foreach ($data as $row) {

        if (!empty($row['Techstack'])) {

            $techs[] = $row['Techstack'];

        }

    }

    echo json_encode(array_values(array_unique($techs)));

    exit;

}


    // Platform

    if ($action == 'getPlatform' && !empty($_GET['tech'])) {

        $platforms = [];

        foreach ($data as $row) {

            if (trim($row['Techstack']) === trim($_GET['tech'])) {

                $platforms[] = trim($row['Platform']);

            }

        }

        echo json_encode(array_values(array_unique($platforms)));

        exit;

    }


    // Env

    if ($action == 'getEnv' && !empty($_GET['tech']) && !empty($_GET['platform'])) {

        $envs = [];

        foreach ($data as $row) {

            if (trim($row['Techstack']) === trim($_GET['tech']) &&

                trim($row['Platform']) === trim($_GET['platform'])) {

                $envs[] = trim($row['Env']);

            }

        }

        echo json_encode(array_values(array_unique($envs)));

        exit;

    }


    // T-Shirt Size

    if ($action == 'getSize' && !empty($_GET['tech']) && !empty($_GET['platform']) && !empty($_GET['env'])) {

        $sizes = [];

        foreach ($data as $row) {

            if (trim($row['Techstack']) === trim($_GET['tech']) &&

                trim($row['Platform']) === trim($_GET['platform']) &&

                trim($row['Env']) === trim($_GET['env'])) {

                $sizes[] = trim($row['T-Shirt Size']);

            }

        }

        echo json_encode(array_values(array_unique($sizes)));

        exit;

    }


    // Details (Compute, License, Notes)

    if ($action == 'getDetails' && !empty($_GET['tech']) && !empty($_GET['platform']) && !empty($_GET['env']) && !empty($_GET['size'])) {

        foreach ($data as $row) {

            if (trim($row['Techstack']) === trim($_GET['tech']) &&

                trim($row['Platform']) === trim($_GET['platform']) &&

                trim($row['Env']) === trim($_GET['env']) &&

                trim($row['T-Shirt Size']) === trim($_GET['size'])) {

                echo json_encode([

                    "compute" => trim($row['Compute']),

                    "license" => trim($row['License']),

                    "notes"   => trim($row['Input Notes'])

                ]);

                exit;

            }

        }

    }

}



?>


<!DOCTYPE html>

<html>

<head>

    <title>Estimator</title>

    <style>

        body { font-family: Arial, sans-serif; background: #f4f6f9; }

        table { border-collapse: collapse; width: 100%; margin: 20px 0; }

        th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }

        th { background: #007acc; color: white; }

        tr:nth-child(even) { background: #f9f9f9; }

        button { background: #007acc; color: white; border: none; padding: 6px 12px; cursor: pointer; }

        button:hover { background: #005f99; }

        #grandTotal { font-weight: bold; margin-top: 20px; }

/* Grand Total row styling */

.grand-total {

    background-color: #f4f6f9;   /* subtle light gray background */

    font-weight: bold;           /* bold text */

    color: #2c3e50;              /* dark slate text */

    border-top: 2px solid #34495e; /* strong top border */

}


.grand-total td {

    padding: 8px 12px;           /* consistent spacing */

    text-align: center;          /* center align numbers */

}


.grand-total td:first-child {

    text-align: left;            /* label aligned left */

    font-size: 1.1em;            /* slightly larger font */

    color: #1a5276;              /* accent color for label */

}


/* CAPEX Table Styling */

#capexTable {

    border-collapse: collapse;

    width: 100%;

    margin-top: 20px;

    font-family: Arial, sans-serif;

    font-size: 14px;

}


#capexTable th, #capexTable td {

    border: 1px solid #ccc;

    padding: 8px 12px;

    text-align: center;

}


#capexTable th {

    background-color: #2c3e50;   /* dark header */

    color: #fff;                 /* white text */

    font-weight: bold;

}


#capexTable tr:nth-child(even) {

    background-color: #f9f9f9;   /* zebra striping */

}


#capexTable tr:hover {

    background-color: #eef;      /* subtle hover effect */

}


#capexTable .grand-total {

    background-color: #f4f6f9;   /* light gray background */

    font-weight: bold;

    border-top: 2px solid #34495e;

}


#capexTable .grand-total td {

    color: #1a5276;              /* accent color for totals */

    font-size: 1.05em;

}

/* CAPEX Table Styling */

#capexTable {

    border-collapse: collapse;

    width: 100%;

    margin-top: 20px;

    font-family: Arial, sans-serif;

    font-size: 14px;

}


#capexTable th, #capexTable td {

    border: 1px solid #ccc;

    padding: 10px 14px;

    text-align: center;

}


#capexTable th {

    background-color: #2c3e50;   /* dark header */

    color: #fff;                 /* white text */

    font-weight: bold;

    text-transform: uppercase;

}


#capexTable tr:nth-child(even) {

    background-color: #f9f9f9;   /* zebra striping */

}


#capexTable tr:hover {

    background-color: #eef;      /* subtle hover effect */

}


#capexTable .grand-total {

    background-color: #f4f6f9;   /* light gray background */

    font-weight: bold;

    border-top: 2px solid #34495e;

}


#capexTable .grand-total td {

    color: #1a5276;              /* accent color for totals */

    font-size: 1.05em;

}


    </style>

</head>

<body>


<h2>Estimator Table</h2>

<button onclick="addRow()">Add Row</button>

<button onclick="exportCSV()">Export to CSV</button>


<table id="estimatorTable">

    <tr>

        <th>Techstack</th>

        <th>Platform</th>

        <th>Env</th>

        <th>T-Shirt Size</th>

        <th>Compute</th>

        <th>License</th>

        <th>Units/Cluster</th>

        <th>Input Notes</th>

        <th>User Notes</th>

        <th>Total Cost/Year</th>

        <th>Delete</th>

    </tr>

</table>



<div id="grandTotal">Grand Total: 0 | HW: 0 | SW: 0</div>


<h3>5-Year CAPEX</h3>

<table id="capexTable">

    <tr><th>Year</th><th>HW Cost</th><th>SW Cost</th><th>Total</th></tr>

</table>


<script>

let table = document.getElementById("estimatorTable");

let grandTotal = document.getElementById("grandTotal");


console.log("Platforms for", tech, data);


function addRow() {

    let row = table.insertRow();

    // Techstack dropdown

    let techCell = row.insertCell();

    let techSelect = document.createElement("select");

    techSelect.onchange = () => {

    if (techSelect.value) {

        loadPlatform(row, techSelect.value);

    }

};


function updateCapexTable(hwCosts, swCosts) {

    let tbody = document.getElementById("capexBody");

    tbody.innerHTML = "";


    // HW row

    let hwRow = tbody.insertRow();

    hwRow.innerHTML = `

        <td>HW Cost</td>

        <td>${hwCosts[0]}</td>

        <td>${hwCosts[1]}</td>

        <td>${hwCosts[2]}</td>

        <td>${hwCosts[3]}</td>

        <td>${hwCosts[4]}</td>

        <td>${hwCosts.reduce((a,b)=>a+b,0)}</td>

    `;


    // SW row

    let swRow = tbody.insertRow();

    swRow.innerHTML = `

        <td>SW Cost</td>

        <td>${swCosts[0]}</td>

        <td>${swCosts[1]}</td>

        <td>${swCosts[2]}</td>

        <td>${swCosts[3]}</td>

        <td>${swCosts[4]}</td>

        <td>${swCosts.reduce((a,b)=>a+b,0)}</td>

    `;


    // Total row

    let totalRow = tbody.insertRow();

    totalRow.classList.add("grand-total"); // <-- reapply CSS class

    totalRow.innerHTML = `

        <td>Total</td>

        <td>${hwCosts[0]+swCosts[0]}</td>

        <td>${hwCosts[1]+swCosts[1]}</td>

        <td>${hwCosts[2]+swCosts[2]}</td>

        <td>${hwCosts[3]+swCosts[3]}</td>

        <td>${hwCosts[4]+swCosts[4]}</td>

        <td><b>${hwCosts.reduce((a,b)=>a+b,0)+swCosts.reduce((a,b)=>a+b,0)}</b></td>

    `;

}



// After populating options, trigger once

techSelect.selectedIndex = 0; // or 1 if you want first real value

techSelect.dispatchEvent(new Event("change"));




    techCell.appendChild(techSelect);


    // Platform dropdown

    let platCell = row.insertCell();

    let platSelect = document.createElement("select");

    platSelect.onchange = () => loadEnv(row, techSelect.value, platSelect.value);

    platCell.appendChild(platSelect);


    // Env dropdown

    let envCell = row.insertCell();

    let envSelect = document.createElement("select");

    envSelect.onchange = () => loadSize(row, techSelect.value, platSelect.value, envSelect.value);

    envCell.appendChild(envSelect);


    // Size dropdown

    let sizeCell = row.insertCell();

    let sizeSelect = document.createElement("select");

    sizeSelect.onchange = () => loadDetails(row, techSelect.value, platSelect.value, envSelect.value, sizeSelect.value);

    sizeCell.appendChild(sizeSelect);


    // Compute

    let computeCell = row.insertCell();

    computeCell.innerHTML = "0";


    // License

    let licenseCell = row.insertCell();

    licenseCell.innerHTML = "0";


    // Units

    let unitCell = row.insertCell();

    let unitInput = document.createElement("input");

    unitInput.type = "number"; unitInput.value = 1;

    unitInput.oninput = () => calculateRow(row);

    unitCell.appendChild(unitInput);


    // Input Notes

    let notesCell = row.insertCell();

    notesCell.innerHTML = "";


    // User Notes

    let userNotesCell = row.insertCell();

    let userNotesInput = document.createElement("input");

    userNotesInput.type = "text";

    userNotesCell.appendChild(userNotesInput);


    // Total Cost

    let costCell = row.insertCell();

    costCell.innerHTML = "0";


    // Delete

    let delCell = row.insertCell();

    let delBtn = document.createElement("button");

    delBtn.innerHTML = "Delete";

    delBtn.onclick = () => { table.deleteRow(row.rowIndex); updateTotals(); };

    delCell.appendChild(delBtn);


    // Load Techstack options

 fetch("?action=getTechstack")

    .then(res => res.json())

    .then(data => {

        techSelect.innerHTML = "";

        let defaultOpt = document.createElement("option");

        defaultOpt.value = "";

        defaultOpt.text = "-- Select Techstack --";

        techSelect.add(defaultOpt);


        data.forEach(val => {

            let opt = document.createElement("option");

            opt.value = val;

            opt.text = val;

            techSelect.add(opt);

        });

    });

//updateGrandTotal();

}


function loadPlatform1(row, tech) {

    fetch("?action=getPlatform&tech="+tech)

        .then(res => res.json())

        .then(data => {

            let platSelect = row.cells[1].children[0];

            platSelect.innerHTML = "";

            data.forEach(val => {

                let opt = document.createElement("option");

                opt.value = val; opt.text = val;

                platSelect.add(opt);

            });

        });

}


function loadPlatform(row, tech) {

    fetch("?action=getPlatform&tech=" + encodeURIComponent(tech))

        .then(res => res.json())

        .then(data => {

            let platSelect = row.cells[1].children[0];

            platSelect.innerHTML = "";


            // Add default option

            let defaultOpt = document.createElement("option");

            defaultOpt.value = "";

            defaultOpt.text = "-- Select Platform --";

            platSelect.add(defaultOpt);


            data.forEach(val => {

                let opt = document.createElement("option");

                opt.value = val;

                opt.text = val;

                platSelect.add(opt);

            });

        });

}



function loadEnv(row, tech, platform) {

    fetch("?action=getEnv&tech=" + encodeURIComponent(tech) + "&platform=" + encodeURIComponent(platform))

        .then(res => res.json())

        .then(data => {

            let envSelect = row.cells[2].children[0];

            envSelect.innerHTML = "";


            let defaultOpt = document.createElement("option");

            defaultOpt.value = "";

            defaultOpt.text = "-- Select Env --";

            envSelect.add(defaultOpt);


            data.forEach(val => {

                let opt = document.createElement("option");

                opt.value = val;

                opt.text = val;

                envSelect.add(opt);

            });

        });

}


function loadSize(row, tech, platform, env) {

    fetch("?action=getSize&tech=" + encodeURIComponent(tech) + "&platform=" + encodeURIComponent(platform) + "&env=" + encodeURIComponent(env))

        .then(res => res.json())

        .then(data => {

            let sizeSelect = row.cells[3].children[0];

            sizeSelect.innerHTML = "";


            let defaultOpt = document.createElement("option");

            defaultOpt.value = "";

            defaultOpt.text = "-- Select Size --";

            sizeSelect.add(defaultOpt);


            data.forEach(val => {

                let opt = document.createElement("option");

                opt.value = val;

                opt.text = val;

                sizeSelect.add(opt);

            });

        });

}


function loadDetails(row, tech, platform, env, size) {

    fetch("?action=getDetails&tech="+tech+"&platform="+platform+"&env="+env+"&size="+size)

        .then(res => res.json())

        .then(data => {

            row.cells[4].innerHTML = data.compute;

            row.cells[5].innerHTML = data.license;

            row.cells[7].innerHTML = data.notes;

            row.dataset.compute = data.compute;

            row.dataset.license = data.license;

            calculateRow(row);

        });

}


// ------------------- CALCULATIONS -------------------

function calculateRow(row) {

    let compute = parseFloat(row.dataset.compute || 0);

    let license = parseFloat(row.dataset.license || 0);

    let units = parseInt(row.cells[6].children[0].value || 1);

    let total = (compute + license) * units;

    row.cells[9].innerHTML = total.toFixed(2);

    updateTotals();

//updateGrandTotal();

}


function updateTotals() {

    let total = 0, hw = 0, sw = 0;

    for(let i=1; i<table.rows.length; i++) {

        let row = table.rows[i];

        let units = parseInt(row.cells[6].children[0].value || 1);

        let compute = parseFloat(row.dataset.compute || 0);

        let license = parseFloat(row.dataset.license || 0);

        total += parseFloat(row.cells[9].innerHTML || 0);

        hw += compute * units;

        sw += license * units;

    }

    grandTotal.innerHTML = `Grand Total: ${total.toFixed(0)} | HW: ${hw.toFixed(0)} | SW: ${sw.toFixed(0)}`;

    generateCAPEX(hw, sw);

}


// ------------------- CAPEX -------------------

function generateCAPEX(hw, sw) {

    let capexTable = document.getElementById("capexTable");

    capexTable.innerHTML = "";


    // Header row: Years

    let headerRow = capexTable.insertRow();

    headerRow.insertCell().innerHTML = "Cost Type";

    for (let year = 1; year <= 5; year++) {

        headerRow.insertCell().innerHTML = `Year ${year}`;

    }

    headerRow.insertCell().innerHTML = "Grand Total (5 yrs)";


    // HW row

    let hwRow = capexTable.insertRow();

    hwRow.insertCell().innerHTML = "HW Cost";

    for (let year = 1; year <= 5; year++) {

        hwRow.insertCell().innerHTML = hw.toFixed(0);

    }

    hwRow.insertCell().innerHTML = (hw * 5).toFixed(0);


    // SW row

    let swRow = capexTable.insertRow();

    swRow.insertCell().innerHTML = "SW Cost";

    for (let year = 1; year <= 5; year++) {

        swRow.insertCell().innerHTML = sw.toFixed(0);

    }

    swRow.insertCell().innerHTML = (sw * 5).toFixed(0);


    // Total row

    let totalRow = capexTable.insertRow();

    totalRow.insertCell().innerHTML = "Total";

    for (let year = 1; year <= 5; year++) {

        totalRow.insertCell().innerHTML = (hw + sw).toFixed(0);

    }

    totalRow.insertCell().innerHTML = ((hw + sw) * 5).toFixed(0);

}


// ------------------- EXPORT TO CSV -------------------


function exportCSV() {

    let csv = [];


    // ---------------- Estimator Table ----------------

    let estTable = document.getElementById("estimatorTable");

    let estRows = estTable.querySelectorAll("tr");


    estRows.forEach(row => {

        let cols = row.querySelectorAll("th, td");

        let rowData = [];

        cols.forEach((col, idx) => {

            // Skip the last column (Delete button)

            if (idx === cols.length - 1) return;


            let text = "";


            // Handle dropdowns

            if (col.querySelector("select")) {

                let sel = col.querySelector("select");

                text = sel.options[sel.selectedIndex]?.text || "";

            }

            // Handle inputs

            else if (col.querySelector("input")) {

                text = col.querySelector("input").value;

            }

            // Otherwise plain text

            else {

                text = col.innerText.trim();

            }


            text = '"' + text.replace(/"/g, '""') + '"';

            rowData.push(text);

        });

        csv.push(rowData.join(","));

    });


    // ---------------- CAPEX Table ----------------

    csv.push(""); // Blank line separator

    csv.push("CAPEX Projection (Horizontal)");


    let capexTable = document.getElementById("capexTable");

    let capexRows = capexTable.querySelectorAll("tr");


    capexRows.forEach(row => {

        let cols = row.querySelectorAll("th, td");

        let rowData = [];

        cols.forEach(col => {

            let text = col.innerText.trim();

            text = '"' + text.replace(/"/g, '""') + '"';

            rowData.push(text);

        });

        csv.push(rowData.join(","));

    });


    // ---------------- Branded Footer ----------------

    // csv.push("");

    // csv.push('"Developed by Dilip"');


    // ---------------- Download ----------------

    let csvString = csv.join("\n");

    let blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" });

    let link = document.createElement("a");

    link.href = URL.createObjectURL(blob);

    link.download = "estimator_with_capex.csv";

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);

}


function updateGrandTotal() {

    let table = document.getElementById("estimatorTable");

    let rows = table.querySelectorAll("tr");


    let hwSum = 0, swSum = 0;


    // Loop through rows to accumulate HW and SW

    rows.forEach((row, idx) => {

        if (idx === 0) return; // skip header

        let computeCell = row.cells[4]; // HW

        let licenseCell = row.cells[5]; // SW


        let hwVal = parseFloat(computeCell.innerText || computeCell.querySelector("input")?.value || 0);

        let swVal = parseFloat(licenseCell.innerText || licenseCell.querySelector("input")?.value || 0);


        hwSum += hwVal || 0;

        swSum += swVal || 0;

    });


    // Remove old Grand Total row if exists

    let lastRow = table.rows[table.rows.length - 1];

    if (lastRow && lastRow.classList.contains("grand-total")) {

        table.deleteRow(table.rows.length - 1);

    }


    // Add new Grand Total row

    let totalRow = table.insertRow();

    totalRow.classList.add("grand-total");


    let cell = totalRow.insertCell();

    cell.colSpan = 4;

    cell.innerHTML = "<b>Grand Total</b>";


    let hwCell = totalRow.insertCell();

    hwCell.innerHTML = hwSum.toFixed(2);


    let swCell = totalRow.insertCell();

    swCell.innerHTML = swSum.toFixed(2);


    let totalCell = totalRow.insertCell();

    totalCell.colSpan = 4;

    totalCell.innerHTML = "<b>" + (hwSum + swSum).toFixed(2) + "</b>";

}



</script>

</body>

</html>

Saturday, 24 January 2026

TreeView

 <?php

error_reporting(E_ALL);

ini_set('display_errors', 0);

header('Content-Type: application/json');


$mysqli = new mysqli("localhost", "xxx", "xxx", "xxxx");

if ($mysqli->connect_error) {

    echo json_encode(["error" => "DB connection failed: " . $mysqli->connect_error]);

    exit;

}


$type   = $_GET['type']   ?? '';

$value  = $_GET['value']  ?? '';   // month or other

$symbol = $_GET['symbol'] ?? '';

$symbolsParam = $_GET['symbols'] ?? '';


$result = [];


if ($type === "symbols") {


    $symbolsParam = $_GET['symbols'] ?? '';

    $sql = "SELECT DISTINCT symbol, concat(symbol,' | ','Shares') company_name, 'TECH' sector 

            FROM stock 

            WHERE symbol IN ($symbolsParam) 

            ORDER BY symbol";

    $res = $mysqli->query($sql);

    while ($row = $res->fetch_assoc()) {

        $result[] = [

            "label"    => $row['symbol'] . " (" . $row['company_name'] . ", " . $row['sector'] . ")",

            "value"    => $row['symbol'],

            "nextType" => "symbol"

        ];

    }

}

/*

elseif ($type === "symbol") {

    // Under each symbol, show 3 fixed nodes

    $result = [

        ["label" => "Database",      "value" => $symbol, "nextType" => "database",      "symbol" => $symbol],

        ["label" => "Allapps",       "value" => $symbol, "nextType" => "allapps",       "symbol" => $symbol],

        ["label" => "Microservices", "value" => $symbol, "nextType" => "microservices", "symbol" => $symbol]

    ];

}

*/

elseif ($type === "symbol") {

    $result = [

        ["label" => "Database",      "value" => $symbol, "nextType" => "database",      "symbol" => $symbol, "cssClass" => "database-label"],

        ["label" => "Allapps",       "value" => $symbol, "nextType" => "allapps",       "symbol" => $symbol, "cssClass" => "allapps-label"],

        ["label" => "Microservices", "value" => $symbol, "nextType" => "microservices", "symbol" => $symbol, "cssClass" => "microservices-label"]

    ];

}



elseif ($type === "database") {

    $stmt = $mysqli->prepare("SELECT * FROM myinv WHERE sym=?");

    $stmt->bind_param("s", $symbol);

    $stmt->execute();

    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {

        $result[] = $row;

    }

    $stmt->close();

}

elseif ($type === "allapps") {

    $stmt = $mysqli->prepare("SELECT * FROM corona WHERE symbol=?");

    $stmt->bind_param("s", $symbol);

    $stmt->execute();

    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {

        $result[] = $row;

    }

    $stmt->close();

}

elseif ($type === "microservices") {

    $stmt = $mysqli->prepare("SELECT * FROM stock WHERE symbol=?");

    $stmt->bind_param("s", $symbol);

    $stmt->execute();

    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {

        $result[] = $row;

    }

    $stmt->close();

}


echo json_encode($result ?? []);




#################JS ###########################



<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Stock TreeView</title>

<style>

/* General page styling */

body {

  font-family: "Segoe UI", Roboto, Arial, sans-serif;

  background: linear-gradient(135deg, #f0f4f8, #d9e2ec);

  margin: 0;

  padding: 20px;

  color: #333;

}


h2 {

  text-align: center;

  font-size: 28px;

  color: #2a4365;

  margin-bottom: 20px;

}


/* Input area */

#inputArea {

  text-align: center;

  margin-bottom: 30px;

}


textarea {

  width: 400px;

  padding: 10px;

  border: 2px solid #cbd5e0;

  border-radius: 6px;

  font-size: 14px;

  resize: none;

  transition: border-color 0.3s;

}


textarea:focus {

  border-color: #3182ce;

  outline: none;

}


button {

  padding: 10px 18px;

  margin-left: 10px;

  cursor: pointer;

  background: #3182ce;

  color: #fff;

  border: none;

  border-radius: 6px;

  font-size: 14px;

  transition: background 0.3s;

}


button:hover {

  background: #2b6cb0;

}


/* Tree styling */

ul.tree, ul.tree ul {

  list-style-type: none;

  margin: 0;

  padding: 0;

}


ul.tree li {

  margin: 6px 0;

  cursor: pointer;

  position: relative;

}


.caret::before {

  font-family: "Font Awesome

  margin-right: 6px;

}


.caret::before {

  content: "\25B6"; /* ? right-pointing triangle */

  color: #3182ce;

  font-weight: bold;

  margin-right: 6px;

  transition: transform 0.3s;

}


.caret-down::before {

  content: "\25BC"; /* ? down-pointing triangle */

}

.node-label:hover {

  background: #e2e8f0;

  transform: translateX(3px);

}


.nested {

  display: none;

  margin-left: 20px;

}


.active {

  display: block;

}


/* Shared table styling */

table {

  border-collapse: collapse;

  width: 95%;

  margin: 15px auto;

  box-shadow: 0 2px 6px rgba(0,0,0,0.1);

  border-radius: 6px;

  overflow: hidden;

}


th, td {

  border: 1px solid #e2e8f0;

  padding: 10px;

  text-align: left;

  font-size: 14px;

}


tr:nth-child(even) {

  background: #f7fafc;

}


tr:hover {

  background: #ebf8ff;

}


/* Search box styling */

input.search-box {

  margin: 10px auto;

  display: block;

  padding: 8px 12px;

  width: 50%;

  border: 2px solid #cbd5e0;

  border-radius: 6px;

  font-size: 14px;

  transition: border-color 0.3s;

}


input.search-box:focus {

  border-color: #3182ce;

  outline: none;

}


/* Section-specific themes */

.database-table th {

  background: #2b6cb0; /* Deep blue */

  color: #fff;

}


.allapps-table th {

  background: #38a169; /* Green */

  color: #fff;

}


.microservices-table th {

  background: #d69e2e; /* Amber/Orange */

  color: #fff;

}


/* Section-specific label icons */

.database-label::before {

  content: "??? "; /* database cylinder/file cabinet */

}


.allapps-label::before {

  content: "?? "; /* app icon (mobile) */

}


.microservices-label::before {

  content: "?? "; /* gear for microservices */

}


.database-label::before {

  content: "\25A3 "; /* ? square with fill */

  color: #2b6cb0;

}


.allapps-label::before {

  content: "\25A0 "; /* ¦ solid square */

  color: #38a169;

}


.microservices-label::before {

  content: "\25CF "; /* ? solid circle */

  color: #d69e2e;

}


/* Extra indentation for tables under child nodes */

.nested li div {

  margin-left: 30px;   /* pushes the wrapper (search + table) to the right */

}


.database-table {

  margin-left: 30px;

}


.allapps-table {

  margin-left: 30px;

}


.microservices-table {

  margin-left: 30px;

}


/* Indent the child headings under each symbol */

.database-label,

.allapps-label,

.microservices-label {

  margin-left: 25px;   /* push the caret + label right */

  display: inline-block;

}


ul.tree ul li .node-label {

  margin-left: 25px;

}


#symbolInputContainer {

  max-width: 500px;

  margin: 0 auto 30px auto;

  padding: 20px;

  background: #ffffff;

  border: 2px solid #cbd5e0;

  border-radius: 8px;

  box-shadow: 0 4px 10px rgba(0,0,0,0.05);

  text-align: center;

}


#symbolInputContainer h3 {

  margin-bottom: 15px;

  color: #2a4365;

  font-size: 20px;

}


/* Smaller search box */

input.search-box {

  margin: 8px auto;

  display: block;

  padding: 5px 8px;       /* reduced padding */

  width: 35%;             /* narrower width */

  border: 2px solid #cbd5e0;

  border-radius: 6px;

  font-size: 13px;        /* slightly smaller font */

  transition: border-color 0.3s;

}


input.search-box:focus {

  border-color: #3182ce;

  outline: none;

}


/* Larger font for symbols */

ul.tree > li > .node-label {

  font-size: 18px;        /* bigger font for main symbols */

  font-weight: 600;

  color: #2a4365;

}


/* Larger font for Database / Allapps / Microservices headings */

.database-label,

.allapps-label,

.microservices-label {

  font-size: 16px;        /* bigger font for child headings */

  font-weight: 500;

  color: #1a202c;

  margin-left: 25px;      /* indentation to push them right */

  display: inline-block;

}


#pageFooter {

  text-align: center;

  margin-top: 40px;

  padding: 15px;

  font-size: 14px;

  font-weight: 500;

  color: #2a4365;

  background: #edf2f7;

  border-top: 2px solid #cbd5e0;

  border-radius: 0 0 8px 8px;

}


/* Below adding */


/* 1 LINE FIX - ADD THIS LAST */

.node-label, .caret { vertical-align: top; margin-right }

.node-label { vertical-align }



/* Search + Export SAME LINE */

.table-controls-row {

  display: flex;

  align-items

}



/* Export button BELOW table, indented */

.export-btn {

  display

}

  .table-controls-row { order }


  /* Export BELOW table + indented */

.wrapper-row {

  display

}


</style>

</head>

<body>

<div id="pageWrapper">


<h2>Stock TreeView</h2>


<!-- Symbol Input -->

<div id="symbolInputContainer">

  <h3>Enter Symbols</h3>

  <textarea id="symbolsInput" rows="3" placeholder="Enter symbols (space or line separated)&#10;e.g., AAPL MSFT GOOGL"></textarea><br>

  <button onclick="buildTree()">Build Tree</button>

</div>


<!-- Tree Container -->

<div id="treeContainer"></div>


</div> <!-- pageWrapper -->


<!-- Footer -->

<footer id="pageFooter">

  Developed by Dilip | Stock TreeView © 2026

</footer>

<script>

// Global event delegation for ALL export buttons

document.addEventListener('click', function(e) {

  if (e.target.classList.contains('export-btn')) {

    const tableId = e.target.parentElement.nextElementSibling.id;

    const type = e.target.dataset.type;

    exportTableToCSV(tableId, type);

  }

});


// Export CSV - filtered rows only

function exportTableToCSV(tableId, type) {

  const table = document.getElementById(tableId);

  if (!table) return;


  let csv = [];

  

  // Header always included

  const headerRow = table.rows[0];

  let headerCols = [];

  for (let cell of headerRow.cells) {

    headerCols.push('"' + cell.innerText.replace(/"/g, '""') + '"');

  }

  csv.push(headerCols.join(","));


  // Only VISIBLE rows

  for (let i = 1; i < table.rows.length; i++) {

    if (table.rows[i].style.display !== "none") {

      let cols = [];

      for (let cell of table.rows[i].cells) {

        cols.push('"' + cell.innerText.replace(/"/g, '""') + '"');

      }

      csv.push(cols.join(","));

    }

  }


  const now = new Date();

  const dateStr = now.toLocaleDateString('en-GB', { 

    day: '2-digit', month: 'short', year: 'numeric' 

  }).replace(/ /g, '-');

  const filename = `${type}_${dateStr}.csv`;


  const blob = new Blob([csv.join("\n")], { type: "text/csv" });

  const link = document.createElement("a");

  link.href = URL.createObjectURL(blob);

  link.download = filename;

  link.click();

}


function buildTree() {

  const input = document.getElementById("symbolsInput").value.trim();

  const symbols = input.split(/\s+/).filter(s => s.trim());

  

  if (symbols.length === 0) {

    alert("Please enter symbols");

    return;

  }


  const formatted = symbols.map(s => `'${s.toUpperCase()}'`).join(",");

  const container = document.getElementById("treeContainer");

  container.innerHTML = '<p style="text-align:center;">Loading tree...</p>';


  fetch(`backend.php?type=symbols&symbols=${encodeURIComponent(formatted)}`)

    .then(res => res.json())

    .then(data => {

      container.innerHTML = "";

      if (!Array.isArray(data) || data.length === 0) {

        container.innerHTML = '<p style="color:red;text-align:center;">No symbols found</p>';

        return;

      }


      const ul = document.createElement("ul");

      ul.className = "tree";


      data.forEach(item => {

        const li = document.createElement("li");

        const span = document.createElement("span");

        span.className = "caret node-label";

        span.textContent = item.label;

        span.onclick = () => toggleNode(span, item.nextType, item.value);

        li.appendChild(span);


        const nested = document.createElement("ul");

        nested.className = "nested";

        li.appendChild(nested);

        ul.appendChild(li);

      });


      container.appendChild(ul);

    })

    .catch(err => {

      document.getElementById("treeContainer").innerHTML = 

        `<p style="color:red;text-align:center;">Network error: ${err}</p>`;

    });

}


function toggleNode(element, type, value, symbol = "") {

  element.classList.toggle("caret-down");

  const nested = element.nextElementSibling;


  if (!nested.classList.contains("active")) {

    const url = `backend.php?type=${type}&value=${value}&symbol=${symbol || value}`;

    

    fetch(url)

      .then(res => res.json())

      .then(data => {

        nested.innerHTML = "";

        

        if (!Array.isArray(data)) {

          nested.innerHTML = `<li style="color:red;">Error: ${data.error || "Invalid data"}</li>`;

          nested.classList.add("active");

          return;

        }


        if (type === "database" || type === "allapps" || type === "microservices") {

          // **TABLE DATA - FIXED VERSION**

          if (data.length > 0) {

            const wrapper = document.createElement("div");


            // Controls: Search + Export (NO onclick here!)

            const controlsRow = document.createElement("div");

            controlsRow.className = "table-controls-row";


            const searchBox = document.createElement("input");

            searchBox.type = "text";

            searchBox.placeholder = "Search records...";

            searchBox.className = "search-box";


            const exportBtn = document.createElement("button");

            exportBtn.textContent = "Export CSV";

            exportBtn.className = "export-btn";

            exportBtn.dataset.type = type;  // Store type for delegation


            controlsRow.appendChild(searchBox);

            controlsRow.appendChild(exportBtn);

            wrapper.appendChild(controlsRow);


            // Table with ID

            const tableId = `${type}-table-${symbol || value}`;

            const table = document.createElement("table");

            table.id = tableId;


            if (type === "database") table.classList.add("database-table");

            if (type === "allapps") table.classList.add("allapps-table");

            if (type === "microservices") table.classList.add("microservices-table");


            // Build table

            const headerRow = document.createElement("tr");

            Object.keys(data[0]).forEach(key => {

              const th = document.createElement("th");

              th.textContent = key;

              headerRow.appendChild(th);

            });

            table.appendChild(headerRow);


            data.forEach(row => {

              const tr = document.createElement("tr");

              Object.values(row).forEach(val => {

                const td = document.createElement("td");

                td.textContent = val || '';

                tr.appendChild(td);

              });

              table.appendChild(tr);

            });


            // **Search works** - no export handler needed here

            searchBox.addEventListener("keyup", function() {

              const filter = this.value.toLowerCase();

              const rows = table.getElementsByTagName("tr");

              for (let i = 1; i < rows.length; i++) {

                const rowText = rows[i].textContent.toLowerCase();

                rows[i].style.display = rowText.includes(filter) ? "" : "none";

              }

            });


            wrapper.appendChild(table);


            const li = document.createElement("li");

            li.appendChild(wrapper);

            nested.appendChild(li);

          } else {

            nested.innerHTML = "<li>No records found</li>";

          }

        } else {

          // Tree nodes

          data.forEach(item => {

            const li = document.createElement("li");

            const span = document.createElement("span");

            span.className = `caret node-label ${item.cssClass || ""}`;

            span.textContent = item.label;

            span.onclick = () => toggleNode(span, item.nextType, item.value, item.symbol || symbol);

            li.appendChild(span);

            const childUl = document.createElement("ul");

            childUl.className = "nested";

            li.appendChild(childUl);

            nested.appendChild(li);

          });

        }

        

        nested.classList.add("active");

      })

      .catch(err => {

        nested.innerHTML = `<li style="color:red;">Fetch error: ${err}</li>`;

        nested.classList.add("active");

      });

  } else {

    nested.classList.toggle("active");

  }

}

</script>




</body>

</html>


Sunday, 4 January 2026

Show Generalize SQL output and export to csv file - php/oracle

Below PHP code with oracle as backend to Show Generalize SQL output and export to csv file - php/oracle


<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Oracle Query Tool</title>

  <style>

    body {

      font-family: 'Segoe UI', sans-serif;

      background: #f4f6f8;

      padding: 30px;

    }

    h2 {

      color: #333;

    }

    form {

      background: #fff;

      padding: 20px;

      border-radius: 8px;

      box-shadow: 0 2px 5px rgba(0,0,0,0.1);

      max-width: 1800px;

      margin-bottom: 20px;

    }

    textarea {

      width: 100%;

      min-height: 100px;

      resize: both;

      padding: 10px;

      font-size: 14px;

      border: 1px solid #ccc;

      border-radius: 4px;

      box-sizing: border-box;

    }

    input[type="submit"] {

      background: #0078D4;

      color: white;

      border: none;

      padding: 10px 20px;

      font-size: 14px;

      border-radius: 4px;

      cursor: pointer;

    }

    input[type="submit"]:hover {

      background: #005a9e;

    }

    .error {

      color: #d8000c;

      background: #ffdddd;

      padding: 10px;

      border-left: 5px solid #d8000c;

      margin-bottom: 20px;

    }

    table {

      border-collapse: collapse;

      width: 100%;

      background: #fff;

      box-shadow: 0 2px 5px rgba(0,0,0,0.1);

    }

    th, td {

      padding: 12px;

      border: 1px solid #ddd;

      text-align: left;

    }

    th {

      background: #0078D4;

      color: white;

    }

.export-btn {

  background: linear-gradient(135deg, #007BFF, #0056b3); /* Blue gradient */

  border: none;

  color: #fff;

  padding: 8px 20px;

  font-size: 16px;

  font-weight: 600;

  border-radius: 8px;

  cursor: pointer;

  transition: all 0.3s ease;

  box-shadow: 0 4px 10px rgba(0,0,0,0.25);

  display: inline-flex;

  align-items: center;

  gap: 8px;

}


.export-btn:hover {

  background: linear-gradient(135deg, #0056b3, #004080);

  transform: translateY(-2px);

}


.export-btn:active {

  transform: translateY(1px);

  box-shadow: 0 2px 6px rgba(0,0,0,0.2);

}


.export-btn i {

  font-size: 18px;

}






  </style>

</head>

<body>


<h2>Oracle Query Tool</h2>


<form method="post">

  <label for="query">Enter SQL Query:</label><br>

  <textarea name="query" id="query" placeholder="Enter SQL.........."><?php echo htmlspecialchars($_POST['query'] ?? ''); ?></textarea>

  <input type="submit" value="Run Query">

  <!-- Export Button -->

<button class="export-btn" onclick="downloadTableAsCSV('queryTable','Export_Report.csv')">

  Export to CSV

</button>




</form>


<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['query'])) {

    $query = $_POST['query'];


    // Oracle connection

    $conn = @oci_connect('xxxx', 'xxxx', '//localhost:1521/xxxx');

    if (!$conn) {

        $e = oci_error();

        echo "<div class='error'>? Connection failed: " . htmlspecialchars($e['message']) . "</div>";

    } else {

        $stmt = @oci_parse($conn, $query);

        if (!$stmt) {

            $e = oci_error($conn);

            echo "<div class='error'>? SQL Parse Error: " . htmlspecialchars($e['message']) . "</div>";

        } else {

            $exec = @oci_execute($stmt);

            if (!$exec) {

                $e = oci_error($stmt);

                echo "<div class='error'>? Execution Error: " . htmlspecialchars($e['message']) . "</div>";

            } else {

                echo "<table id='queryTable'><tr>";

                $ncols = oci_num_fields($stmt);

                for ($i = 1; $i <= $ncols; $i++) {

                    echo "<th>" . htmlspecialchars(oci_field_name($stmt, $i)) . "</th>";

                }

                echo "</tr>";


                while ($row = oci_fetch_array($stmt, OCI_ASSOC + OCI_RETURN_NULLS)) {

                    echo "<tr>";

                    foreach ($row as $val) {

                        echo "<td>" . htmlspecialchars($val ?? '') . "</td>";

                    }

                    echo "</tr>";

                }

                echo "</table>";

            }

        }

        oci_free_statement($stmt);

        oci_close($conn);

    }

}

?>


<script>

function downloadTableAsCSV(tableId, baseFilename) {

    var csv = [];

    var rows = document.querySelectorAll("#" + tableId + " tr");


    for (var i = 0; i < rows.length; i++) {

        var row = [], cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++) {

            var data = cols[j].innerText.replace(/"/g, '""');

            row.push('"' + data + '"');

        }

        csv.push(row.join(","));

    }


    // Create CSV file

    var csvFile = new Blob([csv.join("\n")], { type: "text/csv" });


    // Build filename with date (YYYYMMDD)

    var today = new Date();

    var yyyy = today.getFullYear();

    var mm = String(today.getMonth() + 1).padStart(2, '0');

    var dd = String(today.getDate()).padStart(2, '0');

    var filename = baseFilename + "_" + yyyy + mm + dd + ".csv";


    // Download link

    var downloadLink = document.createElement("a");

    downloadLink.download = filename;

    downloadLink.href = window.URL.createObjectURL(csvFile);

    downloadLink.style.display = "none";


    document.body.appendChild(downloadLink);

    downloadLink.click();

    document.body.removeChild(downloadLink);

}

</script>



</body>

</html>