<?php

// base name
global $base;
global $imolHITRAN;
$base       = 'RuCaSDa';
$imolHITRAN = 99;

// session
session_name(strtolower($base));
session_start();

// absolute server root
$aROOT = $_SERVER['DOCUMENT_ROOT']; // absolute server root

// variables
global $aWORKD; // absolute WORK directory
global $sid; // session ID
global $link;

$rBASD  = '/PHP/' . strtolower($base) . '/'; // relative application directory
$aBASD  = $aROOT . $rBASD; // absolute application directory
$rWORKD = $rBASD . 'WORK/'; // relative WORK directory
$aWORKD = $aROOT . $rWORKD; // absolute WORK directory

$sid  = session_id(); // session ID
$rSID = $rWORKD . $sid . '/'; // relative session directory
$aSID = $aROOT . $rSID; // absolute session directory

$isoName    = array();
$isoCode    = array();
$isoTex     = array();
$isoChecked = 0;
$isoParam   = '';
$isoParamTex= '';
$isoList    = '';
$nbIso;
$isoFmin = array(); // isotopes min wavenumber
$isoFmax = array(); //          max

$ccINTmin = array(); // characterisation min intensity
$ccINTmax = array(); //                  max

$faultStep  = false;
$faultFmin  = false;
$faultFmax  = false;
$faultThres = false;
$sterrStep  = '';
$sterrFmin  = '';
$sterrFmax  = '';
$sterrThres = '';

$finalName = '';
$typeOfDot = '';

// include
include($aROOT . '/PHP/common/MySQL_include.php');
include($aROOT . '/PHP/common/fonctions.php'); // functions
include($aBASD . 'Extract.class.php'); // Extract class

try {
    $link = new PDO('mysql:host=localhost;dbname=' . strtolower($base), $login, $password);
} catch (Exception $e) {
    die('Unable to connect to MySQL database : ' . strtolower($base) . ' ' . $e->getMessage());
}

// session management
if (!is_dir($aSID) || (!isset($_SESSION['NbIso']))) { // missing means 1st call
    if (!is_dir($aSID)) {
        mkdir($aSID, 0777, true); // create it
        if (function_exists('cleanDisk')) {
            cleanDisk(); // suppress directories of previous sessions
        }
    }
    
    // initialize
    $aid                  = 1; // access#
    $_SESSION['aid']      = $aid;
    $fmin                 = 0.;
    $_SESSION['fmin']     = $fmin;
    $fmax                 = 0.;
    $_SESSION['fmax']     = $fmax;
    $thres                = 0.;
    $_SESSION['thres']    = $thres;
    $charac               = 1; // dip
    $_SESSION['charac']   = $charac;
    $datatype             = 1; // line by line
    $_SESSION['datatype'] = $datatype;
    $cs_step              = 1.;
    $_SESSION['cs_step']  = $cs_step;
    
    // isotopes characteristics
    try {
        // isotope names and isotope codes
        $sql = 'SELECT isotopename,isotopeid,formtex FROM molecules_isotopes';
        $req = $link->query($sql);
        
        $i = 0;
        while ($res = $req->fetch()) {
            $isoName[$i] = $res[0];
            $isoCode[$i] = $res[1];
            $isoTex[$i]  = $res[2];
            $i           = $i + 1;
        }
        $req->closeCursor();
    }
    catch (Exception $e) {
        die('Unable to extract isotope names and/or isotopeid :' . $e->getMessage());
    }
    $nbIso = count($isoName);
    
    $_SESSION['isoName'] = $isoName;
    $_SESSION['isoTex']  = $isoTex;
    $_SESSION['isoCode'] = $isoCode;
    $_SESSION['nbIso']   = $nbIso;
    
    // get isotopes wavenumber limits
    for ($i = 0; $i < $nbIso; $i++) {
        // initialize
        $isSetIso[$i] = false;
        try {
            // get limits
            $sql         = 'SELECT MIN(wavenumber),MAX(wavenumber) FROM transitions WHERE isotopeid = \'' . $isoCode[$i] . '\'';
            $req         = $link->query($sql);
            $row         = $req->fetch();
            $isoFmin[$i] = $row[0] ?? 600.0;
            $isoFmax[$i] = $row[1] ?? 2200.0;
            $req->closeCursor(); //fermeture
        }
        catch (Exception $e) {
        
        }
        
        // save in session
        $_SESSION['isSetIso'][$i] = $isSetIso[$i];
        $_SESSION['isoFmin'][$i]  = $isoFmin[$i];
        $_SESSION['isoFmax'][$i]  = $isoFmax[$i];
    }
    
    // get characterisation intensity limits
    for ($i = 0; $i < 2; $i++) {
        // initialize
        try {
            // get limits
            $sql          = 'SELECT MIN(intHITRAN),MAX(intHITRAN) FROM transitions WHERE characid = ' . ($i + 1);
            $req          = $link->query($sql);
            $row          = $req->fetch();
            $ccINTmin[$i] = $row[0] ?? (($i == 0) ? 1e-30 : 1e-35);
            $ccINTmax[$i] = $row[1] ?? (($i == 0) ? 1e-20 : 1e-25);
            $req->closeCursor(); //fermeture
        }
        catch (Exception $e) {
            // Valeurs par défaut
            $ccINTmin[$i] = ($i == 0) ? 1e-30 : 1e-35;
            $ccINTmax[$i] = ($i == 0) ? 1e-20 : 1e-25;
        }
        
        // save in session
        $_SESSION['ccINTmin'][$i] = $ccINTmin[$i];
        $_SESSION['ccINTmax'][$i] = $ccINTmax[$i];
    }
} else {
    // NOT the first call, increment access#
    $aid = $_SESSION['aid'];
    $aid++;
    $_SESSION['aid'] = $aid; // save it
    
    $fmin     = $_SESSION['fmin'];
    $fmax     = $_SESSION['fmax'];
    $thres    = $_SESSION['thres'];
    $isoName  = $_SESSION['isoName'];
    $isoTex   = $_SESSION['isoTex'];
    $isoCode  = $_SESSION['isoCode'];
    $nbIso    = $_SESSION['nbIso'];
    $charac   = $_SESSION['charac'];
    $datatype = $_SESSION['datatype'];
    $cs_step  = $_SESSION['cs_step'];
    for ($i = 0; $i < $nbIso; $i++) {
        $isSetIso[$i] = $_SESSION['isSetIso'][$i] ?? false;
        $isoFmin[$i]  = $_SESSION['isoFmin'][$i];
        $isoFmax[$i]  = $_SESSION['isoFmax'][$i];
    }
    for ($i = 0; $i < 2; $i++) {
        $ccINTmin[$i] = $_SESSION['ccINTmin'][$i];
        $ccINTmax[$i] = $_SESSION['ccINTmax'][$i];
    }
}

// get parameter values
$emptyForm = true;
if (isset($_POST['cmdSend'])) {
    // ISOTOPE
    $foundIsotope = false;
    for ($i = 0; $i < $nbIso; $i++) {
        if (isset($_POST['cb' . $isoName[$i]])) {
            $emptyForm    = false; //placé ici, on a tendance à modifier plusieurs fois la variable pour la même valeur
            $foundIsotope = true; // idem pour celle-ci. A moins que ce soit des tableaux commme "isSetIso"
            $isSetIso[$i] = true;
            $isoList      = $isoList . $isoName[$i] . ' ';
            $isoChecked++;
        } else {
            $isSetIso[$i] = false;
        }
        // All isotopologues are given in argument for plotting
        $isoParam = $isoParam . $isoName[$i] . ' ';
        $isoParamTex = $isoParamTex . $isoTex[$i] . ' ';
    }
    // Raman
    if ($_POST['charac'] == 'dip') { // cf. mp_name de ctrab
        $charac = 1; // electric dipole
    } else {
        $charac = 2; // polarizability
    }
    if ($_POST['datatype'] == 'linebyline') {
        $datatype  = 1;
        $finalName = 'line';
        $typeOfDot = ' lines';
    } else {
        $datatype  = 2;
        $finalName = 'cross sections';
        $typeOfDot = ' points';
    }
    // STEP
    if ($datatype == 2) {
        if (isset($_POST['cs_step'])) {
            $cs_step = $_POST['cs_step'];
            if ($cs_step == '') {
                $cs_step = 1.0;
            } else {
                $emptyForm = false;
                if (is_numeric($cs_step)) {
                    if ($cs_step <= 0.) {
                        $faultStep = true;
                        $sterrStep = 'Step value must be greater than zero';
                    } else {
                        if ($isoChecked != 1) {
                            $faultStep = true;
                            $sterrStep = 'Select only one isotopologue for cross sections';
                        } else if ($charac != 1) {
                            $faultStep = true;
                            $sterrStep = 'Cross sections only available for electric dipole';
                        } else {
                            $faultStep = false;
                        }
                    }
                } else {
                    $faultStep = true;
                    $sterrStep = 'Invalid step: ' . $cs_step;
                }
            }
        }
    }
    // FMIN
    if (isset($_POST['fmin'])) {
        $fmin = $_POST['fmin'];
        if ($fmin == '') {
            $faultFmin = true;
            $sterrFmin = 'Fmin value is not defined';
        } else {
            $emptyForm = false;
            if (is_numeric($fmin)) {
                if ($fmin < 0.) {
                    $faultFmin = true;
                    $sterrFmin = 'Fmin value must be greater than or equal to zero.';
                } else {
                    $faultFmin = false;
                }
            } else {
                $faultFmin = true;
                $sterrFmin = 'Invalid Fmin: ' . $fmin;
            }
        }
    }
    // FMAX
    if (isset($_POST['fmax'])) {
        $fmax = $_POST['fmax'];
        if ($fmax == '') {
            $faultFmax = true;
            $sterrFmax = 'Fmax value is not defined';
        } else {
            $emptyForm = false;
            if (is_numeric($fmax)) {
                if ($fmax < 0.) {
                    $faultFmax = true;
                    $sterrFmax = 'Fmax value must be greater than or equal to zero.';
                } else {
                    $faultFmax = false;
                }
            } else {
                $faultFmax = true;
                $sterrFmax = 'Invalid fmax: ' . $fmax;
            }
        }
    }
    if (!$faultFmax && !$faultFmin) {
        if (is_numeric($fmax) && is_numeric($fmin) && $fmax <= $fmin) {
            $faultFmax = true;
            $sterrFmax = 'Fmax must be greater than Fmin';
        }
    }
    // THRES
    if (isset($_POST['thres'])) {
        $thres = $_POST['thres'];
        if ($thres == '') {
            $faultThres = true;
            $sterrThres = 'Threshold value is not defined';
        } else {
            $emptyForm = false;
            if (is_numeric($thres)) {
                if ($thres < 0.) {
                    $faultThres = true;
                    $sterrThres = 'Threshold value must be greater than or equal to zero.';
                } else {
                    $faultThres = false;
                }
            } else {
                $faultThres = true;
                $sterrThres = 'Invalid thres: ' . $thres;
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
<script data-goatcounter="https://casda.goatcounter.com/count"
        async src="//gc.zgo.at/count.js"></script>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <title><?php echo $base . ' line lists ' . $aid; ?></title>
</head>
<body>

    <!-- Banner avec image centrée -->
    <div class="banner">
         <img src="/PHP/CaSDa24.png" class="imagebanner">
    </div>
    
    <!-- Menu home -->
    <div class="menu">
        <a href="../index.php">
            <img src="exit.png" alt="Home" height="48">
        </a>
    </div>
    
    <!-- Titre principal -->
    <div class="title">
        <?php echo 'Calculated ' . $base . ' line list extraction at 296K'; ?>
    </div>
    
    <!-- Formulaire principal -->
    <div class="form_parent">
        <form method="post">
        
        <!-- Section Isotopes avec image de molécule -->
        <div style="position: relative; overflow: hidden;">
            <div class="type_of_item">Isotope(s)</div>
            <div class="mol_img">
                <img src="rucasda.png" alt="molecule image" width="100" />
            </div>
        </div>
        
        <fieldset class="extract-info">
        <?php for ($i = 0; $i < $nbIso; $i++) { ?>
                <label style="display: flex; align-items: center; margin-bottom: 15px;">
                <?php
        $checked = (isset($isSetIso[$i]) && $isSetIso[$i]) ? 'checked' : '';
        echo '<input type="checkbox" name="cb' . $isoName[$i] . '" value="' . $isoName[$i] . '" ' . $checked . ' style="margin-right: 10px;">';
        echo '<span style="flex: 1;">';
        echo '<strong>' . $isoName[$i] . '</strong>';
        echo '<span style="color: #64748b; font-size: 13px; margin-left: 10px;">';
        echo sprintf('[%.3f → %.3f cm⁻¹]', $isoFmin[$i], $isoFmax[$i]);
        echo '</span></span>';
?>
                </label>
        <?php } ?>
            
            <div style="margin-top: 15px; text-align: center;">
                <button type="button" id="selectAllBtn">Select All</button>
                <button type="button" id="deselectAllBtn">Deselect All</button>
            </div>
        </fieldset>

        <!-- Section Characterisation -->
        <div class="type_of_item">Characterisation</div>
        <fieldset class="extract-info">
            <label style="display: flex; align-items: center; margin-bottom: 15px;">
            <?php
    $dipole_checked = ($charac == 1) ? 'checked' : '';
    echo '<input type="radio" name="charac" value="dip" ' . $dipole_checked . ' style="margin-right: 10px;">';
    echo '<span style="flex: 1;">';
    echo '<strong>Electric dipole</strong>';
    echo '<span style="color: #64748b; font-size: 13px; display: block;">';
    echo sprintf('[%.3e → %.3e cm⁻¹/(molecule cm⁻²)]', $ccINTmin[0], $ccINTmax[0]);
    echo '</span></span>';
?>
            </label>
            
            <label style="display: flex; align-items: center; margin-bottom: 15px;">
            <?php
    $pol_checked = ($charac == 2) ? 'checked' : '';
    echo '<input type="radio" name="charac" value="pol" ' . $pol_checked . ' style="margin-right: 10px;">';
    echo '<span style="flex: 1;">';
    echo '<strong>Polarizability</strong>';
    echo '<span style="color: #64748b; font-size: 13px; display: block;">';
    echo sprintf('[%.3e → %.3e arbitrary unit]', $ccINTmin[1], $ccINTmax[1]);
    echo '</span></span>';
?>
            </label>
        </fieldset>

        <!-- Section Type of Data -->
        <div class="type_of_item">Type of Data</div>
        <fieldset class="extract-info_inline" style="display: flex; flex-wrap: wrap; gap: 20px; align-items: center;">
        <?php
$linebyline_checked = ($datatype == 1) ? 'checked' : '';
$crosssection_checked = ($datatype == 2) ? 'checked' : '';

echo '<label style="display: flex; align-items: center;">';
echo '<input type="radio" name="datatype" value="linebyline" ' . $linebyline_checked . ' style="margin-right: 8px;"> Line by line';
echo '</label>';

echo '<label style="display: flex; align-items: center;">';
echo '<input type="radio" name="datatype" value="crosssection" ' . $crosssection_checked . ' style="margin-right: 8px;"> Cross sections';
echo '</label>';

echo '<label style="display: flex; align-items: center; gap: 5px;">';
echo 'with step: <input type="text" size="5" name="cs_step" value="' . $cs_step . '" style="width: 60px;"> cm⁻¹';
echo '</label>';
?>
        </fieldset>

        <!-- Section Wavenumber Range -->
        <div class="type_of_item">Wavenumber Range</div>
        <fieldset class="extract-info">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <label>
                    <strong>Lower wavenumber:</strong>
                    <?php
$fmin_value = $faultFmin ? '' : $fmin;
echo '<input type="text" name="fmin" value="' . $fmin_value . '" placeholder="600" style="width: 100%; margin-top: 5px;">';
echo '<span style="color: #64748b; font-size: 13px;">cm⁻¹</span>';
?>
                </label>
                
                <label>
                    <strong>Upper wavenumber:</strong>
                    <?php
$fmax_value = $faultFmax ? '' : $fmax;
echo '<input type="text" name="fmax" value="' . $fmax_value . '" placeholder="2200" style="width: 100%; margin-top: 5px;">';
echo '<span style="color: #64748b; font-size: 13px;">cm⁻¹</span>';
?>
                </label>
            </div>
        </fieldset>

        <!-- Section Intensity Threshold -->
        <div class="type_of_item">Intensity Threshold</div>
        <fieldset class="extract-info">
            <label>
                <strong>Threshold:</strong>
                <?php
$thres_value = $faultThres ? '' : $thres;
echo '<input type="text" name="thres" value="' . $thres_value . '" placeholder="1e-25" style="width: 100%; margin-top: 5px;">';
?>
                <span style="color: #64748b; font-size: 13px; display: block; margin-top: 5px;">
                    Minimum intensity for line inclusion
                </span>
            </label>
        </fieldset>

        <!-- Section d'action -->
        <fieldset class="extract-action">
            <input class="btn" type="submit" name="cmdSend" value="Extract">
            <label style="font-size: 16px; color: #7c7c80;">
                The extraction can last several minutes
            </label>
        </fieldset>

        <!-- Footer -->
        <div id="footer">
            <a target="_blank" href="http://www.cnrs.fr/">
                <img src="cnrs.png" alt="CNRS" height="50">
            </a>
            <a target="_blank" href="http://dataosu.obs-besancon.fr/">
                <img src="dataOSU.png" alt="Data OSU" height="50">
            </a>
            <a target="_blank" href="http://icb.cnrs.fr">
                <img src="icb.png" alt="ICB" height="50">
            </a>
            <a target="_blank" href="https://www.ube.fr">
                <img src="ub.png" alt="UB" height="50">
            </a>
            <a target="_blank" href="https://vamdc.org">
                <img src="vamdc.png" alt="VAMDC" height="50">
            </a>
        </div>

        </form>
    </div>

    <?php
    if (!$emptyForm) { // 1st call of the page
        if (!$foundIsotope) {
            echo "<script>alert('No isotope selected. Select at least one isotope');</script>";
        }
        if ($faultStep) {
            echo "<script>alert('$sterrStep');</script>"; 
        }
        if ($faultFmin) {
            echo "<script>alert('$sterrFmin');</script>";
        }
        if ($faultFmax) {
            echo "<script>alert('$sterrFmax');</script>";
        }
        if ($faultThres) {
            echo "<script>alert('$sterrThres');</script>";
        }
        
        // all parameters defined, process extraction
        if ($foundIsotope && !$faultStep && !$faultFmin && !$faultFmax && !$faultThres) {
            
            // output file name
            $outf  = 'extract';
            $isoID = array();
            for ($i = 0; $i < $nbIso; $i++) {
                if ($isSetIso[$i]) {
                    $outf    = $outf . '_' . $isoName[$i];
                    $isoID[] = $isoCode[$i];
                }
            }
            $outf = $outf . '_' . $fmin;
            $outf = $outf . '_' . $fmax;
            $outf = $outf . '_' . $thres;
            
            // implied isotopes
            $isoReq = false; // supposed all selected
            $sFmin  = $isoFmin[0]; // max wavenumber of the isotope selection
            $sFmax  = $isoFmax[0]; // min
            for ($i = 0; $i < $nbIso; $i++) {
                if ($isSetIso[$i]) {
                    $sFmin = min($isoFmin[$i], $sFmin);
                    $sFmax = max($isoFmax[$i], $sFmax);
                } else {
                    $isoReq = true; // partly selected
                }
            }
            // implied wavenumbers
            if (($fmin > $sFmin) && ($fmax < $sFmax)) {
                $wavnReq = 3;
            } elseif ($fmin > $sFmin) {
                $wavnReq = 2;
            } elseif ($fmax < $sFmax) {
                $wavnReq = 1;
            } else {
                $wavnReq = 0;
            }
            
            // create an Extract occurence
            $rRESD = $rSID . $aid . '/'; // relative result directory
            $aRESD = $aSID . $aid . '/'; // absolute result directory
            if (!is_dir($aRESD)) {
                shell_exec('mkdir -p ' . escapeshellarg($aRESD));
                shell_exec('chmod 777 ' . escapeshellarg($aRESD));
            }
            if ($charac == 1) {
                $outf = $outf . '_dip';
            } else {
                $outf = $outf . '_pol';
            }
            $outf  = $outf . '.txt';
            $aoutf = $aRESD . $outf;
            $ext   = new Extract($isoID, $isoReq, $charac, $datatype, $cs_step, $fmin, $fmax, $wavnReq, $thres, $aoutf, $link);
            
            if ($ext->getStatus() < 0) {
                // error
                echo 'status: ' . $ext->getError();
            } else {
                // happy end
                echo '<div class="extract-result"> Extracted ' . $finalName . ' list <A HREF="openFile.php?aoutf=..' . $rRESD . $outf . '&base=' . strtolower($base) . '" target="_blank">here</A> (' . number_format($ext->getLSize() ?? 0, 0, ',', ' ') . $typeOfDot . ')</div>';
                // .. due to relative to current script
                echo '<div class="extract-result"> Extracted ' . $finalName . ' file <A HREF="downloadFile.php?aoutf=..' . $rRESD . $outf . '">here</A> (' . number_format(($ext->getBSize() ?? 0) * 9.54e-7, 2) . ' MB)</div>';
                //     .. due to relative to current script
                
                try {
                    $linkSources = new PDO('mysql:host=localhost;dbname=' . strtolower($base), $login, $password);
                    
                    $outfSources = str_replace('.txt', '_sources.bib', $outf);
                    $aoutfSources = $aRESD . $outfSources;
                    
                    $extSources = new Extract($isoID, $isoReq, $charac, 3, $cs_step, $fmin, $fmax, $wavnReq, $thres, $aoutfSources, $linkSources);
                    
                    if ($extSources->getStatus() >= 0 && $extSources->getLSize() > 0) {
                        $sourceFileSize = ($extSources->getBSize() ?? 0) * 9.54e-7;
                        $sourceSizeDisplay = ($sourceFileSize < 1.0) ? 
                            number_format($sourceFileSize * 1024, 0) . ' kB' : 
                            number_format($sourceFileSize, 2) . ' MB';
                        
                        echo '<div class="extract-result"> Extracted sources bibliography (BibTeX) <A HREF="openFile.php?aoutf=..' . $rRESD . $outfSources . '&base=' . strtolower($base) . '" target="_blank">here</A> (' . number_format($extSources->getLSize() ?? 0, 0, ',', ' ') . ' references)</div>';
                        echo '<div class="extract-result"> Extracted sources file (BibTeX) <A HREF="downloadFile.php?aoutf=..' . $rRESD . $outfSources . '">here</A> (' . $sourceSizeDisplay . ')</div>';
                    } else {
                        echo '<div class="extract-result">Sources extraction failed: ' . $extSources->getError() . '</div>';
                    }
                    
                } catch (Exception $e) {
                    echo '<div class="extract-result">Sources database error: ' . $e->getMessage() . '</div>';
                }
                
                if ($ext->getLSize() > 0) {
                    // We want to check if the line number is not too huge. If > 500000, then generate a static image
                    if ($ext->getLSize() > 500000) {
                        $command = escapeshellcmd('/usr/bin/python3 /usr/local/bin/plotBase.py ' . $datatype . ' /var/www/html/vamdc' . $rRESD . $outf . ' ' . $isoParamTex);
                        $output  = shell_exec($command);
                        echo '<div class="img-result"><img src="..' . $rRESD . 'out.png" width="1000" title="plot" alt="plot"/></div>';
                    } else {
                        $command = escapeshellcmd('/usr/bin/python3 /usr/local/bin/plotBase-2.py ' . $datatype . ' /var/www/html/vamdc' . $rRESD . $outf . ' ' . $isoParam);
                        $output  = shell_exec($command);
                        $output_filename = "/var/www/html/vamdc" . $rRESD . "output.html";
                        echo '<div align="center">';  
                        include($output_filename); 
                        echo '</div>';
                    }
                }
                echo '<div align="center">For more than 500,000 transitions, a static image is displayed instead of an interactive plot.</div>';
            }
        }
    }

    // Save session data
    for ($i = 0; $i < $nbIso; $i++) {
        $_SESSION['isSetIso'][$i] = $isSetIso[$i] ?? false;
    }
    $_SESSION['fmin']     = $fmin;
    $_SESSION['fmax']     = $fmax;
    $_SESSION['thres']    = $thres;
    $_SESSION['charac']   = $charac;
    $_SESSION['datatype'] = $datatype;
    $_SESSION['cs_step']  = $cs_step;

    $link = null;
    ?>

    <!-- Scripts -->
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        // Function to handle the "Select All" button click
        document.getElementById('selectAllBtn').addEventListener('click', function () {
            var checkboxes = document.querySelectorAll('input[type="checkbox"]');
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = true;
            }
        });

        // Function to handle the "Deselect All" button click
        document.getElementById('deselectAllBtn').addEventListener('click', function () {
            var checkboxes = document.querySelectorAll('input[type="checkbox"]');
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = false;
            }
        });
    });
    </script>

    <script src="js/main.js"></script>

</body>
</html>
