<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include_once '../METHODS/PHPFUNCTIONS.php';
include_once '../METHODS/INSERTUPDATE.JAVA';
 //GFunction('FRD','' ,$Qsql,22,'','0-0')

 if(isset($_SESSION['DbName'])){  $DbName ; $DbName =$_SESSION['DbName']; }
?>

<script>
   
    let  moduls='' ;
  let data;

//                                  function customAlert(title, message) {
//   const modal = document.createElement('div');
//   modal.innerHTML = `
//     <div style="position:fixed;top:0;left:0;width:100%;height:100%;
//                 background:rgba(248, 213, 213, 0.5);z-index:9999;
//                 display:flex;align-items:center;justify-content:center;">
//       <div style="background:#fff;border-radius:8px;min-width:300px;
//                   font-family:sans-serif;overflow:hidden;">
//         <div style="background:#4a90e2;color:#fff;padding:12px 16px;
//                     font-weight:bold;font-size:16px;">
//           ${title}
//         </div>
//         <div style="padding:20px;font-size:14px;">${message}</div>
//         <div style="padding:12px 16px;text-align:right;">
//           <button onclick="this.closest('div[style]').remove()"
//             style="background:#4a90e2;color:#fff;border:none;
//                    padding:8px 20px;border-radius:4px;cursor:pointer;">
//             OK
//           </button>
//         </div>
//       </div>
// //     </div>`;
//   document.body.appendChild(modal);
// }



                  var Msg = new Array(100)
Msg[0] ='';
Msg[1] = '3';
Msg[2] = '3';
Msg[3] = '4';
Msg[4] = '5';


                        // function DeletRecord(QueryElemt){
                        //     QElemt=QueryElemt...split('-')
                        //     // 0- Data base Table
                        //     // 1- Whhere  Columne
                        //     // 2- Where Value
                        //      Query='DELETE FROM '+QElemt[0]+=' WHERE '+QElemt[1]+'"'+QElemt[2]+'"'
                        // alert(Query)
                        //       const formData = new FormData();
                        //       formData.append('user_regist', Query );
                        //       fetch('../METHODS/MysqlQuery.PHP', {
                        //             method: 'POST',
                        //             body: formData})
                        //             .then(response => {
                        //       if (!response.ok) {
                        //       throw new Error('Network response was not ok');
                        //     }
                        //       return response.text(); // Or response.json() if your PHP returns JSON
                        // })    
                        //     .then(data => {//alert(data)
                        //     if(data){ MsgAlert(Msg[0],'لقد تم التسجيل بنجاح','info','false','')}
                               
                        //     })
                        //             .catch(error => {
                        //             //alert('Fetch error:', data);
                        // });
                    
                        // }
                        function checkfelds(DivId, FeldsId, FormId) {
                               // alert(DivId + ' - ' + FeldsId); // Optional debugging
                                    const FeldsIdx = FeldsId.split(',');
                                    let hasEmptyField = false; 
                                    for (let i = 0; i < FeldsIdx.length; i++) {
                                        const field = document.getElementById(FeldsIdx[i].trim());
                                        if (field && (field.value === null || field.value.trim() === '')) {
                                            hasEmptyField = true;
                                            break; // Stop loop as soon as one empty field is found
                                        } 
                                    }
                                    if (hasEmptyField) {//alert(t.party)
                                        MsgAlert('', 'يجب ادخال البيانات الاساسيه', 'info');
                                    } else {
                                        switch (DivId) {
                                            case 'student_info':
                                                INSERTUPDATE('yes', '', 'student_info', '<?= $DbName?>', 'cerdit,disdebit,Notice,debit,blance,familyoption,uniformfeescerdit,bookfeescerdit,PrintDocu');
                                                break;
                                            case 'users':
                                                INSERTUPDATE('yes', '', 'users', '<?= $DbName?>', 'usertype,crPSW');
                                                break;
                                            case 'myschool_info':
                                                INSERTUPDATE('yes', 'datakey', 'myschool_info', '<?= $DbName ?>', '');
                                                break;
                                            case 'school_info':
                                                INSERTUPDATE('yes', '', 'school_info', 'myschool', '');
                                                break;
                                            case 'teacher_info':  //alert('yes');
                                                INSERTUPDATE('yes', '', 'teacher_info', '<?= $DbName?>', '');
                                                break; 
                                            case 'teacher_task':  //alert('yes');
                                                INSERTUPDATE('yes', '', 'teacher_task', '<?= $DbName?>', '');
                                                break; 
                                            case 'teachersubjcts_info':
                                                    INSERTUPDATE('yes','','teachersubjcts_info', '<?php echo $DbName?>','');
                                            break; 
                                                case 'question_info':
                                                    INSERTUPDATE('yes','','question_info', '<?php echo $DbName?>','');
                                            break; 
                                            default:
                                        break;
        }
    }
}

                 
               
      function MsgAlert(Ptitle, Ptext, Ptype, callbackAction = null) {
    let options = {
        title: Ptitle,
        text: Ptext,
        icon: Ptype === 'Yes/Cancel' ? 'question' : Ptype // Maps custom types to valid Swal icons
    };

    switch (Ptype) {
        case 'info':
            options.confirmButtonColor = "#5cb85c";
            options.confirmButtonText = "موافق"; // Arabic standard for UX continuity
            break;

        case 'Yes/Cancel':
            options.showCancelButton = true; // Fixed: Explicitly set instead of undefined variable
            options.cancelButtonColor = "#d33";
            options.confirmButtonColor = "#5cb85c";
            options.confirmButtonText = "نعم";
            options.cancelButtonText = "إلغاء";
            break;

        case 'error':
            options.confirmButtonColor = "#d33";
            options.confirmButtonText = "موافق";
            
            break;

        default:
            options.confirmButtonColor = "#3085d6";
            options.confirmButtonText = "موافق";
            break;
    }

    // Fire the modern SweetAlert2 modal instance
    Swal.fire(options).then(function (result) {
        if (result.isConfirmed) {
            // Safely execute your callback action if it was passed
            if (typeof callbackAction === 'function') {
                callbackAction();
            }
        }
    });
}


                            function par(name){return document.getElementById(name)}

                            



                            function MySqlDate(Queries){//alert(Queries)
                            const formData = new FormData();
                              formData.append('user_regist', Queries );
                              fetch('../METHODS/MysqlQuery.PHP', {
                                    method: 'POST',
                                    body: formData})
                                    .then(response => {
                              if (!response.ok) {
                              throw new Error('Network response was not ok');
                            }
                              return response.text(); // Or response.json() if your PHP returns JSON
                        })    
                            .then(data => {//alert(data)
                            if(data){ MsgAlert('','لقد تم العمليه بنجاح','info','false','')}
                               
                            })
                                    .catch(error => {
                                    //alert('Fetch error:', data);
                        });
                    }

                    //     function PropertiesChanged(Idname,Property,ConditionItem){//alert(Idname+" - "+Property+" - "+ConditionItem)
                    //             myDiv = document.getElementById(Idname);                           
                    //             elements = myDiv.querySelectorAll('input, button, select, textarea');
                    //                switch(Property){
                    //                    case 'readonly':
                    //                 if(ConditionItem==true){///alert('readonly')
                    //                     myDiv.readonly='true'
                    //                 }else if(ConditionItem==false){///alert('not readonly')
                    //                     myDiv.readonly='false'
                    //                 }
                    //                 break;
                    //                 case 'display':
                    //                     if(ConditionItem==true){//alert('display')
                    //                     myDiv.style.display='block'
                    //                     }else if(ConditionItem==false){///alert('not display')
                    //                     myDiv.style.display='none'
                    //                     }
                    //                 break;
                    //                 case 'disabled':
                    //                     if(ConditionItem==true){//alert('disabled')
                    //                     //myDiv.classList.add('disabled-div');
                    //                     elements.forEach(el => el.disabled = false);
                    //                     }else if(ConditionItem==false){///alert('not disabled')
                    //                     //myDiv.classList.remove('disabled-div');
                    //                     elements.forEach(el => el.disabled = true);
                    //                     }
                    //                 break;
                    //                 case 'hidden':
                    //                     if(ConditionItem==true){//alert('hidden')
                    //                     myDiv.hidden=true
                    //                     }else if(ConditionItem==false){///alert('not hidden')
                    //                     myDiv.hidden=false
                    //                     }
                    //                 break;
                    //                 case 'type':
                    //                     if(ConditionItem==true){//alert('type')
                    //                     myDiv.type='checkbox'
                    //                     }else if(ConditionItem==false){///alert('not type')
                    //                     myDiv.type='text'
                    //                     }
                    //                 break;
                    //                }
                    //   }


        function studentoption(Idname,GENERALVARfetch,GENERALVARkey){ //alert(Idname);alert(GENERALVARfetch)
                        x=0
                        privefetch= GENERALVARfetch.split(",");
                        privekey= GENERALVARkey.split(",");
                        Queries='UPDATE  information_schol SET data_key = CASE '
                         WhereQ=' WHERE controlfetch IN ( '
                        myDiv = document.getElementById('studenption')
                        elms = myDiv.querySelectorAll('input[type="checkbox"]');
            if(!Idname){
                                       
                           for(i=0;i< elms.length ;i++){ 
                          if(elms[i].checked){status='on'}else{status='off'}
                            Queries+= ' WHEN controlfetch = "'+elms[i].id  + '" THEN "'  +status +'"' 
                            WhereQ+='"'+elms[i].id+'",'
                         };
                         WhereQ=WhereQ.slice(0, -1) + " ";
                          Queries+= ' ELSE data_key END'
                          WhereQ+=') ' 
                          Queries+= WhereQ
                       // alert(Queries)
                          MySqlDate(Queries)
                }else  if(Idname){
                    
                for (i = 0; i < privefetch.length; i++) {//alert('ok2'+' - '+privefetch+' - '+privekey)
                        //alert(privekey[i] + " - " + privefetch[i])
                    if(privekey[i]=='on'){
                       document.getElementById(privefetch[i]).checked = true;
                       //alert(privekey[i] + " - " + privefetch[i])
                    }else if(privekey[i]=='off' && document.getElementById(privefetch[i])){
                       document.getElementById(privefetch[i]).checked = false;
                      // alert(privekey[i] + " - " + privefetch[i])
                    }    
                }
            }
        }
    //
                       //alert(privefetch+" - "+privekey)

     
                          function UI_Select(felds,options) {//alert(felds+' - '+options);
                        if(options=="on"){
                           document.getElementById(felds).style.display = "block";
                            }else if(options=="off"){
                         document.getElementById(felds).style.display = "none";;    
                        } 
                    };                 






                            function privacies(index){//alert(index)
                    x=index
                                        prive= pricty.split("");   
                    elms = document.querySelectorAll('div[id]');
                  //alert(elms)
            for (var t = 0; t < elms.length; t++) {
            if(pricty[x]==0 && elms[t].id.startsWith('priv')){//alert( elms[t].id)
                elms[t].style.display='none' 
            }else if(pricty[x]==1 && elms[t].id.startsWith('priv')){//alert( elms[t].id)
                elms[t].style.display='block'     
            }   x++
        } 
    }
       ///////////////////////////////////dele func /////////////////
        // function DeletRecord(TableName,ColumneName,optionValue){
        //   optionValue=  optionValue.split(',')
        //    ColumneName=  ColumneName.split(',')
          
        //      for (var i = 0; i < ColumneName.length; i++) {alert(optionValue[i]+' / '+ColumneName[i])
               
        //      if(i==0 && par(optionValue[i]).value){ alert(i)
        //      let   QueryDelet =' DELETE FROM '+ TableName+' WHERE  '+ColumneName[i]+' = "'+par(optionValue[i]).value +'"'
        //         }else if(par(optionValue[i]).value) {
        //                 QueryDelet +=' and '+ColumneName[i]+' = "'+par(optionValue[i]).value +'"'
        //         }
        //      }
           
                
            
        //     alert(QueryDelet)
        //     //MysqlQuery(QueryDelet)
        // }


function DeletRecord(TableName, ColumneName, optionValue) {
    var columns = ColumneName.split(',');
    var values = optionValue.split(',');
    var QueryDelet = '';
    
    for (var i = 0; i < columns.length; i++) {
        var col = columns[i].trim();
        var elemId = values[i].trim();
        var elem = document.getElementById(elemId); // Fixed: use elemId here
        
        if (elem) {
            if (QueryDelet === '') {
                QueryDelet = 'DELETE FROM ' + TableName + ' WHERE ' + col + ' = "' + elem.value + '"';
            } else {
                QueryDelet += ' AND ' + col + ' = "' + elem.value + '"';
            }
        }
    }
    
    if (QueryDelet !== '') {alert(QueryDelet)
        MySqlDate(QueryDelet);
    }
}



//////////////////////////////////////////////////////////////
        function privaciesCreated(dividname,privacies){//alert(dividname+" - "+privacies)
                        x=0
                        userprivacies = document.getElementById('userprivacies');
                        userprivacies.value=''
                        prive= privacies.split("");
                         myDiv = document.getElementById(dividname)
                        elms = myDiv.querySelectorAll('input[type="checkbox"]');
                    for (i = 0; i < elms.length; i++) {
                    if(privacies.length==0){//alert(' privacies')
                    if(!elms[i].checked ){ //alert(elms[i].checked)
                        userprivacies.value+=0;
                    }else  if(elms[i].checked ){//
                        userprivacies.value+=1}
                    }else if(privacies.length>0){//alert('no userprivacies')
                    if (elms[i].id) {
                    if(prive[x]==0){//alert(elms[i].id)
                        userprivacies.value+=0
                        elms[i].checked = false;
                    }else  if(prive[x]==1){//
                        userprivacies.value+=1
                        elms[i].checked = true;  // Check
                    } x=x+1;                      
                }
            }
        }  
    }          
                        function printDiv(DivId) {
                                                    const content = document.getElementById(DivId).innerHTML;
                                                    const printWindow = window.open('', '', 'width=800,height=600');
                                                    printWindow.document.write(`
                                                        <html>
                                                        <head>
                                                            <title>طباعة</title>
                                                            <style>
                                                            table { width: 100%; border-collapse: collapse; direction: rtl; }
                                                            th, td { border: 1px solid #333; padding: 8px; text-align: center; }
                                                            </style>
                                                        </head>
                                                        <body>${content}</body>
                                                        </html>
                                                    `);
                                                    printWindow.document.close();
                                                    printWindow.focus();
                                                    printWindow.print();
                                                    printWindow.close();
                                                    }
                        function printResult(DivId) {
                                                        // 1. جلب محتوى العنصر المراد طباعته
                                                        var printContents = document.getElementById(DivId).innerHTML;
                                                        
                                                        // 2. فتح نافذة طباعة جديدة
                                                        var originalContents = document.body.innerHTML;
                                                        document.body.innerHTML = printContents;
                                                        
                                                        // 3. تنفيذ أمر الطباعة
                                                        window.print();
                                                        
                                                        // 4. استعادة محتوى الصفحة الأصلي بعد الطباعة
                                                        document.body.innerHTML = originalContents;
                                                        window.location.reload(); // لتحديث الصفحة وإعادة تفعيل الأكواد العادية
                                                    }
                                                    // Usage
                                                    customAlert("My Custom Title", "This is my message!");

                    function GFunction(FunctionType, Idname, QeryCode, WhereOption, AdditionOption) {
                                    const Queries = FunctionType + "," + QeryCode + "," + WhereOption + "," + AdditionOption;
                                    alert(Queries+'q')
                                    const formData = new FormData();
                                    formData.append('user_regist', Queries);
                            fetch('../METHODS/JAVATOPHP.PHP', { 
                                        method: 'POST', 
                                        body: formData 
                                    })
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error('Network response was not ok');
                                        }
                                        return response.text();
                                    })
                                    .then(data => {alert(data+' / '+document.getElementById(Idname).id)
                                            if (!data.includes('Warning')) {
                                            const element = document.getElementById(Idname);
                                            if (!element) return; // Exit if element doesn't exist
                                                        if (element.tagName === 'TABLE') {
                                                element.innerHTML = data;
                                            } else if (element.tagName === 'SELECT') {
                                                const firstOptionHTML = element.options[0] ? element.options[0].outerHTML : '';
                                                element.innerHTML = `<option value="${data}">${data}</option>` + firstOptionHTML;
                                            } else if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' ) {
                                                vlu=data;
                                                document.getElementById(Idname).value =vlu 
                                               // alert(data+' / '+ Idname )

                                            }
                                        }
                                    })
                                    .catch(error => {
                                        console.error('Error:', error);
                                    });
                                }


function WherePerpare(Type, Idname, Qcode, TableName, IdNames, Group, AdditonOption) {
   //alert(Type + " - " + Idname + " - " + Qcode + " - " + TableName + " - " + IdNames + " - " + Group + " - " + AdditonOption);
    
    if (TableName) {
        // Use clean native split arrays directly instead of manually assigning items in a loop
        const ConditionsArray = IdNames.split('-');
        const TableArray = TableName.split('-');
        
        // Use the length of the split array to safely bound the loop
        let totalItems = TableArray.length;
        let x = 0;
        let WhereCondition = " where "; 
        
        do {
            // Check if the HTML element exists on page using par()
            if (par(ConditionsArray[x])) {
                WhereCondition += TableArray[x] + " like '%" + par(ConditionsArray[x]).value + "%'";
            } else {
                WhereCondition += TableArray[x] + " like '%" + ConditionsArray[x] + "%'";
            }
            
            // Only add 'and' if there is another condition following this one
            if (x < totalItems - 1) {
                WhereCondition += " and ";
            }
            x++;
        } while (x < totalItems); // Corrected boundary condition
        
        //alert(Type + " / " + Idname + " / " + Qcode + " / " + WhereCondition + " / " + AdditonOption);
        
        WhereCondition += " " + Group;
         Queries=Type+ "," +Qcode+ "," +WhereCondition+ "," +Idname + "," + AdditonOption;
    } else  if (TableName==='') {
         Queries=Type+ "," +Qcode+ "," +Group+ "," + Idname + "," + AdditonOption;
        
    }

//alert(Queries+'q')
                                    const formData = new FormData();
                                    formData.append('user_regist', Queries);
                            fetch('../METHODS/JAVATOPHP.PHP', { 
                                        method: 'POST', 
                                        body: formData 
                                    })
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error('Network response was not ok');
                                        }
                                        return response.text();
                                    })
                                    .then(data => {//alert(data)
                                            if (!data.includes('Warning')) {
                                                            const element =par(Idname);
                                                      //  alert(element)
                                            if (!element) return; // Exit if element doesn't exist
                                            //alert('ok')
                                                if (element.tagName === 'TABLE') {
                                                // Use && so it updates only if NEITHER string is present
                                                if (!data.includes('Warning') && !data.includes('\\wamp64\\www\\')) {
                                                    element.innerHTML = data;
                                                }else{element.innerHTML =''}
                                                } else if (element.tagName === 'SELECT') {
                                                            //const firstOptionHTML = element.options[0] ? element.options[0].outerHTML : '';
                                                           element.innerHTML='';
                                                            element.innerHTML = `<option value="${data}">${data}</option>` //+ firstOptionHTML;
                                                } else if (element.tagName === 'TEXTAREA' ) {
                                                            vlu=data;
                                                            document.getElementById(Idname).value =vlu 
                                                           // alert(data+' / '+ Idname )
                                                }else if (element.tagName === 'INPUT'  ) {
                                                            vlu=data;
                                                            document.getElementById(Idname).value =vlu 
                                                           // alert(data+' / '+ Idname )
                                            }
                                        }
                                    })
                                    .catch(error => {
                                        console.error('Error:', error);
                                    });
                               } 









                        function GroupOption(IdDivTabel,ColmnConditon){
                                    OptionCode='';
                                    Queries='';
                                    const wordx = IdDivTabel.split('-');
                                    const words = ColmnConditon.split('-');
                                    parentDiv = document.getElementById(wordx[0]);
                                    childElements = parentDiv.children; 
                                for (let i = 0; i < childElements.length; i++) {//alert(childElements[i].value+" - "+ColmnConditon+' - '+childElements[i].tagName)
                            if(   childElements[i].tagName=='INPUT' ){ 
                                if(childElements[i].checked){OptionCode+=1 }else{OptionCode+=0}
                                    ;//alert(OptionCode)
                                        }}
                                Queries='update '+words[2]+'.'+wordx[1]+' set '+words[0]+'='+'"'+OptionCode+'"'+ ' where id ="'+words[1] +'"';
                                    // alert(Queries)
                                        const formData = new FormData();
                                        formData.append('user_regist', Queries );
                                        fetch('../METHODS/INSERT.PHP', {
                                        method: 'POST',
                                        body: formData})
                                        .then(response => {
                                            //  alert(response.ok)
                                    if (!response.ok) { 
                                        throw new Error('Network response was not ok');
                                }
                                        return response.text(); // Or response.json() if your PHP returns JSON
                            })
                                        .then(data => {alert(data)
                                        if(data === 'لقد تم تسجيل بنجاح ' && clean=='yes') { 
                                            for (let i = 0; i < childElements.length; i++){
                                                if(!RegExp('\\b'+ childElements[i].id +'\\b').test( Aception )){childElements[i].value=''; }
                                    } 
                                } 
                                        // alert('تم تسجيل البيانات بنجاح'); // Handle the response from the PHP script
                            })
                                        .catch(error => {
                                    // alert('Fetch error:', error);
                    });
                
                                }


                        function GroupBehavior(Idname,Behavior){//alert(Idname+" - "+Behavior)
                                    let wordX = Behavior.split(/\s+/);
                                    let words = Idname.split(/\s+/);
                                    i=0;
                                    words.forEach(word => {//alert(word)
                                        element = document.getElementById(word);
                                    if(wordX[i*2]=="required"){
                                        element.required = wordX[(i*2)+1]
                                    }
                                    if(wordX[i*2]=="display"){
                                        element.style.display = wordX[(i*2)+1] ; 
                                    };
                                    if(wordX[i*2]=="readOnly"){
                                        element.style.readOnly = wordX[(i*2)+1];
                                    };
                                    if(wordX[i*2]=="disabled" ){
                                        element.style.disabled = wordX[(i*2)+1];
                                    };
                                    if(wordX[i*2]=="hidden" ){
                                        element.style.hidden = wordX[(i*2)+1];
                                    };
                                    // if(wordX[i*2]=="type" ){alert(wordX[(i*2)+1])
                                    //     element.style.type = 'checkbox'//wordX[(i*2)+1];
                                    // };
                                        i++;
                            }  );
                        }

                    function ElementFeeds(Idname,FeedData){//alert(Idname+" - "+FeedData);
                                            let words = Idname.split(/\s+/);
                                            words.forEach(word => {
                                            let selectElement = document.getElementById(word);
                                        if (selectElement) {
                                            // Check if the element is an input or textarea
                                        if (selectElement.tagName === 'INPUT' || selectElement.tagName === 'TEXT') {
                                            //alert(document.getElementById(Idname).id)
                                            selectElement.value = FeedData;
                                        } else {
                                            //alert(document.getElementById(Idname).id)
                                        // alert(selectElement.options.length);
                                        selectElement.selectedIndex = 0; 
                                            selectElement.innerHTML += FeedData
                                        
                                        }
                    
                                    }
                                })
                            };


// function HiddTabs(idname, stratwith) {//alert(idname+' - '+ stratwith)
//     const targetElement = document.getElementById(idname);
// // alert(targetElement.id)
//    // alert(targetElement.style.display)
//     if (targetElement) {//
//         targetElement.style.display = 'block'; // Or 'inline', 'flex', etc.
//     }
//         //
//     // Grab all divs that have an ID attribute
//     const allDivs = document.querySelectorAll('div[id]');

//     allDivs.forEach(div => {
//         const divId = div.id;
//        // alert(divId+' -'+'tab')
//         // Hide if it matches the prefix but is NOT the currently targeted element
//         if (divId.startsWith(stratwith,'TAB') && divId !== idname) {alert(div.id)
//             div.style.display = 'none';
//         }
//     });alert(targetElement.style.display)
// }

            function HiddTabs(idname,stratwith){//alert(par(idname).id)

                    const allDivs = document.querySelectorAll('div');
                    allDivs.forEach((div) => {//alert(div.id)
            if(div.id && div.id.startsWith(stratwith)){//alert(div.id);                         
                     div.style.display = 'none';
                }   
            });    
                      par(idname).style.display ='block' ;                        
        };

           function GetCellData(row,Idname) {//alert(row+'--'+Idname)
                                    Elemt=Idname.split('-')
                                    // 0-Table id
                                    // 1-Div id
                                    // 2-Qquery Code
                                    // 3-Wherre Condition Columne
                                    // 4-Where Value
                                    // format code(' ondblclick="GetCellData(this,\'myTable-student_info-56-studentregkey-1-2\')
                                const table = document.getElementById(Elemt[0]);
                                table.addEventListener("click", function(event) {
                                const clickedRow = event.target.closest("tr");
                            if (clickedRow) {
                                const rowIndex = clickedRow.rowIndex;
                                indx=table.rows[rowIndex].cells[Elemt[4]].innerText;
                                indxp=table.rows[rowIndex].cells[Elemt[5]].innerText;
                                const logElement = document.getElementById('log');
                                            Swal.fire({
                                                    title: '',
                                                    text: ( " هل ترقب في تحديث بيانات   : "+indxp+"؟"),
                                                    type: 'info',
                                                    showCancelButton: true,
                                                    confirmButtonColor: "#5cb85c",
                                                    confirmButtonText: "Yes",
                                                    closeOnConfirm: false
                                                })
                                                    .then(function (isConfirm) {
                                                        if (isConfirm.value) {//alert(isConfirm.value)
                                                                  var elm = {};
                                var elms = document.getElementById( Elemt[1]).getElementsByTagName("*");
                                for (var i = 0; i < elms.length; i++) {
                        if (elms[i].id !== '') {
                                idname=elms[i].id;    // alert(elms[i].id)
                                //ElementFetch(idname,indx)
                                WherePerpare('FRD',idname,Elemt[2],Elemt[3],indx,'',idname+'-'+idname) 
                              // WherePerpare('SOD','studentclass_r',16,'datasubobject','studentstage_r',' and datakey=1 ','0-0');
                            } 
                        }
                               // logElement.textContent = "Action confirmed: Record deleted.";           // Add your 'yes' action here (e.g., submit a form, make API call)
                        
                                                        }
                                                            
                                })




                    //         if (confirm( " هل ترقب في تعديل بيانات الطالب  : "+indxp+" ?")) {//alert('ok1')
                    //              var elm = {};
                    //             var elms = document.getElementById('student_info').getElementsByTagName("*");
                    //             for (var i = 0; i < elms.length; i++) {
                    //     if (elms[i].id !== '') {
                    //             idname=elms[i].id;     // alert(idname)
                    //             //ElementFetch(idname,indx)
                    //             WherePerpare('FRD',idname,56,'studentregkey',indx,'',idname+'-'+idname) 
                    //           // WherePerpare('SOD','studentclass_r',16,'datasubobject','studentstage_r',' and datakey=1 ','0-0');
                    //         } 
                    //     }
                    //             logElement.textContent = "Action confirmed: Record deleted.";           // Add your 'yes' action here (e.g., submit a form, make API call)
                        
                        
                    //     } else {  //alert('saving');                                              // If the user clicks "Cancel" (No                 
                    // }
                }
            });
        };
                    
            function ElementFetch(idname,indx) {//////alert(indx+' - '+idname)
                                var ajax = new XMLHttpRequest();
                                ajax.open("GET", "../METHODS/SelectConnection2.php", true);                                          // A separate file is created to get studentstage list
                                ajax.send();                                                           // Actually sending the request to get data
                                ajax.onreadystatechange = function () {                 // alert(this.readyState+' - '+this.status);  // Callback when request status changes
                        if (this.readyState == 4 && this.status == 200) {          // alert(this.responseText); // status = 200, when the request is successfull // readyState = 4, when the response is received
                                var response = JSON.parse(this.responseText);
                                           //alert(response.length)              // using function JSON.parse  // this.responseText will be JSON string, so we are converting it in Javascript object
                        for (var a = 0; a < response.length; a++) { 
                                p= response[a]
                                //alert(p.studentregkey) 
                        if (p.studentregkey==indx) { //alert(indx+' - '+p[idname]+' - '+idname)
                                 nam=idname             //alert(nam);
                                 elements=document.getElementById(idname)
                                // var elements = document.getElementsByName(idname);
                                // if (elements.length > 0) {
                                 //alert(p[idname]); // Outputs "text", "hidden", etc.
                                // }
                               // elements.text=p[idname];
                                elements.value=p[idname];
                                //alert(elements.value+' - '+  elements.innerHTML+' - '+idname)
                        }
                    }
                }
            }
        }

                                const audioFileInput = document.getElementById('filex');
                                const myAudio = document.getElementById('studentimg');
                                //alert(audioFileInput.onclick())
                                audioFileInput.addEventListener('change', (event) => {//alert('ok')
                                const selectedFile = event.target.files[0];
                        if (selectedFile) {
                                const objectURL = URL.createObjectURL(selectedFile);
                               // alert(objectURL)
                                myAudio.src = objectURL;
                                myAudio.load(); // Reload the audio element with the new source
                    }
                } 
           );    

            
              
            function CreaSerial(){console.log("Function One finished.");;
                        const StudenCode=document.getElementById('studentregkey');
                        const jkegStage=document.getElementById('kegStage').value; 
                        const jkegSerial=document.getElementById('kegSerial').value;  
                        //alert(jkegStage+' & '+jkegSerial)                
                       //  alert('ok')                                                           //  alert(clas.options[clas.selectedIndex].text+'  ;  '+stage+'   /// '+response[a].clm0+'   /// '+response[a].clm1+'   /// '+response[a].clm2);
                        num='STD' + Number( jkegStage + String(jkegSerial).padStart(3, '0'))
                       // alert(num)                                                                            // This will be displayed to users //  alert('STD'+num);
                        StudenCode.value= num                  
               }



                        function GenaStudentCode(){
                                            return new Promise(resolve => {//alert('ok')
                                            const  stage=  document.getElementById('studentstage').value;
                                            const  claso=  document.getElementById('studentclass').value;
                            if(stage && claso){
                                            WherePerpare('FRD', 'kegSerial',24,'si.studentstage-si.studentclass','studentstage-studentclass','','0-0') //+' /'+'my msg'
                                            WherePerpare('FRD', 'kegStage',23,'datasubobject-datamainobject','studentstage-studentclass','','0-0') 
                            } 
                                    setTimeout(() => {
                                            console.log('Async Function One finished.');
                                            resolve(); // Signal that the task is complete
                                    }, 150); //alert(stage+' - yes '+claso)// Waits 1 second
                                });      
                            }

                        async function RunSequentially() {
                                    await GenaStudentCode();// Wait here for the Promise to resolve
                                    CreaSerial();            // This runs only after the 'await' is done
                                }

            










            function FamilyOptions() {//alert('FamilyOptions')
                            const boxoptin =document.getElementById('familyoption');
                            const familyboxname=document.getElementById('studentfamily');
                            const familyboxnum =document.getElementById('familyregister')
                       if (familyboxname.disabled===true ) {
                            familyboxname.disabled = false;
                            familyboxname.ariaRequired = true;
                            
                            GFunction('FRD','familyregister',22,'','0-0')
                    } else {
                            familyboxname.disabled = true;
                            familyboxname.value='';
                            familyboxnum.value=0;//f("FAM%03d",1,);
                    }
                };  
 
            function StudenGetKey(){//
                    return new Promise(resolve => {
                            StuentKey=  document.getElementById('studentregkey')
                            StuentName= document.getElementById('studentname')
                            StuentMaket=document.getElementById('degres')
                            stage=      document.getElementById('studentstage_r');
                            claso=      document.getElementById('studentclass_r');
                            Exam=       document.getElementById('ExamCode');
                            document.getElementById('studentregkey').addEventListener('keyup', function(event) {
                            num=document.getElementById('studentregkey').value
                            document.getElementById('studentregkey').value=Number(num)
                            num=document.getElementById('studentregkey').value
                            document.getElementById('studentregkey').value = num.padStart(3, '0');
                            
                    if (event.key == 'Enter' && StuentKey.value  &&  stage.value && claso.value && Exam.value ) {//alert('okex')
                           
                           
                            StuentMaket.addEventListener('keydown', function(event) {
                     if (event.key == 'Enter' && !!StuentMaket.value ) {//alert(event.key+' - '+StuentMaket.value+' - '+par('DbName').value)
                    //    alert(document.getElementById('DbName').value)
                     INSERTUPDATE('','','result_std',par('DbName').value,'DbName')
                  
                            StuentKey.value='';
                            StuentName.value='';
                            StuentMaket.value='';
                          StuentKey.style.readOnly = false
                            StuentKey.focus()
                             WherePerpare('TBL','resulttable',5,'rs.ExamCode-rs.studentclass_r-rs.studentstage_r','ExamCode-studentclass_r-studentstage_r','') 
                   //  StuentKey.focus()
                    }
                });       }
                });
                            setTimeout(() => {
                            console.log('Async Function One finished.');
                            resolve(); // Signal that the task is complete
                    }, 200); // Waits 1 second
                }); 
            }

        async function RunStudenGetKey() {
                        await StudenGetKey(); // Wait here for the Promise to resolve
                       if(StuentName.value!==''){StuentMaket.focus();StuentKey.readOnly = ture;}          // This runs only after the 'await' is done
                    }
                    
        function STUDEN_RPT() {
                         StuentKey=  document.getElementById('studentregkey_rp')
                        StuentName= document.getElementById('studentname_rp')
                        studentstage_r=document.getElementById('studentstage_rp')
                       studentclass_r= document.getElementById('studentclass_rp')
                        StuentKey.addEventListener('keyup', function(event) {
                            num=document.getElementById('studentregkey_rp').value
                            document.getElementById('studentregkey_rp').value=Number(num)
                            num=document.getElementById('studentregkey_rp').value
                            document.getElementById('studentregkey_rp').value = num.padStart(3, '0');
                           
                            if (event.key == 'Enter' &&  studentstage_r.value && studentclass_r.value) {//alert('okrp')
                            WherePerpare('FRD','studentname_rp',8,'studentclass-studentstage-studentregkey','studentclass_rp-studentstage_rp-studentregkey_rp','','1-1') 
                            WherePerpare('FRD','studentregkey_rp',8,'studentclass-studentstage-studentregkey','studentclass_rp-studentstage_rp-studentregkey_rp','','0-0') 
                   document.getElementById('accident').focus() 
                    }

                            })
                            }

        function SearchTable(Idname,QueryCode) {//(FuntionType,Idname,QueryCode,Collumns,CollumnnCoditions,Group,AdditonOption)
                                Searcher=document.getElementById(Idname);
                                if( isNaN(Searcher.value) ){
                                    //alert('yes is numerice');
                                } else{
                                    if(Searcher.value){num=Searcher.value
                                    Searcher.value=Number(num)
                                    num=Searcher.value
                                    Searcher.value = num.padStart(3, '0');}
                                }
                    WherePerpare('TBL','myTable',11,'studentstage-studentclass-studentregkey','studentstage_r-studentclass_r-Searcher',' or studentname like "%'+Searcher.value+'%" ','')
                            }




        function RunInformation_schol(Idname,QueryCode,Code,i){
                        // alert(Idname+" - "+QueryCode+" - "+Code+' - '+i)
                        // Queries=FunctionType+","+QeryCode+","+WhereOption+","+AdditionOptio
                       Queries= 'ARD'+','+QueryCode+','+' where controlfetch= "'+Code+'"'+','+'1-1' 
                     
                            MysqlQuery(Queries)
   



                        return new Promise(resolve => { //alert('ok')
                                                                      i=0 ; 
                                    let words = Idname.split(/\-+/);
                                    words.forEach(word => {//alert(word+' - '+comd)
                                 ///"select Instructions,comment,attri_properties  from information_schol "
                              
                                 })
                                setTimeout(() => {
                                console.log('Async Function One finished.');
                                resolve(); // Signal that the task is complete
                                }, 200); // Waits 1 second
                          i++;   }                 
                        )


}




        async  function Information_schol(Idname,QueryCode,Code) {//alert(Code);
                               RunInformation_schol(Idname,QueryCode,Code,i);



                                 
                                   
                                    Idnamex=document.getElementById(word);
                                    
                                    Idnamex.placeholder =Idnamex.value;                         
                          };
                                
                 /////////////////////////// Messages //////////////////               
                                
                            function MysqlQuery(Queries){alert(Queries)
                            const formData = new FormData();
                              formData.append('user_regist', Queries );
                              fetch('../METHODS/JAVATOPHP.PHP', {
                                    method: 'POST',
                                    body: formData})
                                    .then(response => {
                              if (!response.ok) {
                              throw new Error('Network response was not ok');
                            }
                              return response.text(); // Or response.json() if your PHP returns JSON
                        })    
                            .then(data => {alert(data)
                            datax=data.split(',')
                                cmd=datax[1].split('-')
                                            par('datamainobject').placeholder=cmd[0]
                                            par('datasubobject').placeholder=cmd[1]
                                            par('notice').placeholder=cmd[2]
                                     Instructions=datax[0].split('-')
                                      Instructions[2]=style.display = 'block';
                                            par('datamainobject').Instructions[0]
                                            par('datasubobject').Instructions[1]
                                            par('notice').Instructions[2]
                                           
                            })
                                    .catch(error => {
                                    //alert('Fetch error:', data);
                        }); 
                                                        return data;
                                                       
                    }

            /////////////////////////////////QR FUNCTIONS EREA ////////////////////////// 

  // Global variables to hold instances
        let qrcodeInstance = null;
        let qrScannerInstance = null;

        // --- FUNCTION 1: CREATE ---
        function generateQR() {
            const textValue = document.getElementById('qr-text').value;
            const container = document.getElementById('qrcode-display');
            
            if (!textValue) return alert("Please enter text first!");
            
            // Clear previous QR code if it exists
            container.innerHTML = "";
            
            // Instantiate QRCode library to build the matrix
            qrcodeInstance = new QRCode(container, {
                text: textValue,
                width: 150,
                height: 150,
                colorDark: "#000000",
                colorLight: "#ffffff"
            });
        }

        // --- FUNCTION 2: PRINT ---
        function printQR() {
            const container = document.getElementById('qrcode-display');
            if (container.children.length === 0) return alert("Generate a QR code first!");
            
            // Triggers browser native print dialog targeted via @media print rules
            window.print();
        }

        // --- FUNCTION 3: READ ---
        function startScanning() {
            // Initializes the camera scanner module inside the designated div
            qrScannerInstance = new Html5QrcodeScanner("qr-reader", { 
                fps: 10, 
                qrbox: 250 
            });
            
            // Renders the scanner and registers success callback
            qrScannerInstance.render(onScanSuccess, onScanError);
        }

        function onScanSuccess(decodedText, decodedResult) {
            // Displays the parsed data text onto the screen
            document.getElementById('scan-result').innerText = decodedText;
            
            // Stops the camera feed after successfully parsing a barcode
            if (qrScannerInstance) {
                qrScannerInstance.clear();
            }
        }

        function onScanError(errorMessage) {
            // Console logging errors silently to avoid interrupting video frames
            console.warn(`QR scanning error: ${errorMessage}`);
        }

        // Generate an initial QR code on load
        window.onload = generateQR;
 </script>