<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gestion des coefficients</title>
<link rel="stylesheet" href="w3.css">

<style>
body {width:90%; margin:auto; font-family:sans-serif;}
.class-box {margin:20px 0; padding:10px; border:1px solid #ccc; border-radius:10px;}
.class-title {font-weight:bold; color:teal; margin-bottom:10px;}
.sub-item {display:flex; align-items:center; justify-content:space-between; padding:6px 0; border-bottom:1px solid #eee; transition:all .18s ease;}
.sub-item.move {background:#e8f7f6;}
.sub-left {flex:1; cursor:grab;}
.sub-right button {margin-left:5px;}
input.coef-input {width:60px; text-align:center;}
.order-btn {cursor:pointer;}
.add-box {margin-top:10px; padding:10px; border:1px dashed teal; border-radius:8px; display:none;}
.add-toggle {cursor:pointer; color:teal; font-weight:bold;}

/* Notification box */
#notifBox {
  display:none;
  position:fixed;
  top:20px;
  right:20px;
  z-index:99999;
  padding:12px 18px;
  border-radius:8px;
  font-weight:bold;
  color:white;
  box-shadow:0 4px 10px rgba(0,0,0,0.2);
  opacity:0;
  transform:translateY(-10px);
  transition:opacity 0.4s ease, transform 0.4s ease;
}
#notifBox.show {
  display:block;
  opacity:1;
  transform:translateY(0);
}

/* Fade-in animation for new row */
@keyframes fadeIn { from { opacity:0; transform: translateY(-6px); } to { opacity:1; transform: translateY(0); } }
.sub-item.new { animation: fadeIn 0.45s ease-out; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
// --- Show notification ---
function showMessage(msg, type='info'){
  const box = document.getElementById('notifBox');
  box.textContent = msg;

  let bg = '#555';
  if (type === 'green') bg = '#2e7d32';
  else if (type === 'red') bg = '#c62828';
  else if (type === 'blue') bg = '#0277bd';
  else if (type === 'orange') bg = '#ef6c00';

  box.style.backgroundColor = bg;
  box.classList.add('show');
  setTimeout(()=> box.classList.remove('show'), 2500);
}

// --- Initialize everything ---
document.addEventListener('DOMContentLoaded',()=>{
  document.querySelectorAll('.coef-input').forEach(inp=>{
    inp.addEventListener('input',function(){
      const btn=this.closest('.sub-item').querySelector('.w3-blue');
      if(btn) btn.style.backgroundColor='orange';
    });
  });

  // Drag & Drop ordering
  document.querySelectorAll('[id^="list_"]').forEach(list=>{
    new Sortable(list,{
      animation:150,
      handle:'.sub-left',
      onEnd:function(evt){
        const classID = evt.from.id.replace('list_','');
        const orderData = Array.from(evt.from.children).map((child,index)=>{
          const subID = child.id.replace(`row_${classID}_`,'');
          return { subSubjectID: subID, ordering:index+1 };
        });

        fetch('reorderSub.php',{
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body:JSON.stringify({ classID: classID, order: orderData })
        })
        .then(r=>r.text())
        .then(res=>showMessage(res,'blue'))
        .catch(()=>showMessage('Erreur serveur','red'));
      }
    });
  });
});

// --- Update coefficient ---
function updateCoef(classID,subID){
  const input=document.getElementById(`coef_${classID}_${subID}`);
  const btn=document.querySelector(`#row_${classID}_${subID} .w3-blue`);
  const coef=input.value;

  btn.style.backgroundColor='gray';
  btn.textContent='⏳';

  fetch('updateCoef.php',{
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:`classID=${classID}&subSubjectID=${subID}&coef=${coef}`
  })
  .then(r=>r.text())
  .then(res=>{
    if(res.toLowerCase().includes('ok')){
      btn.style.backgroundColor='green';
      btn.textContent='💾';
      showMessage('Coefficient enregistré','green');
    } else {
      btn.style.backgroundColor='red';
      btn.textContent='💾';

      showMessage(res,'red');
    }
  })
  .catch(()=>{
    btn.style.backgroundColor='red';
    btn.textContent='💾';
    showMessage('Erreur serveur','red');
  });
}

// --- Delete subject ---
function deleteSub(classID,subID){
  if(!confirm('Supprimer cette matière ?')) return;
  fetch('deleteSub.php',{
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:`classID=${classID}&subSubjectID=${subID}`
  })
  .then(r=>r.text())
  .then(res=>{
    showMessage(res,'red');
    const row=document.getElementById(`row_${classID}_${subID}`);
    if(row){
      row.style.transition='opacity 0.4s';
      row.style.opacity='0';
      setTimeout(()=>row.remove(),400);
    }
  });
}

// --- Toggle add box ---
function toggleAddBox(classID){
  const box=document.getElementById(`addBox_${classID}`);
  box.style.display=(box.style.display==='none' || box.style.display==='')?'block':'none';
}

// --- Add new subject ---
function addSub(event,classID,cycle){
  event.preventDefault();
  const form=event.target;
  const sub=form.sub.value;
  const coef=form.coef.value;

  if(!sub||coef===''){ showMessage('Complétez tous les champs','red'); return; }

  fetch('addSub.php',{ // Make sure your backend file is named addSub.php
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:`classID=${classID}&sub=${sub}&coef=${coef}&cycle=${cycle}`
  })
  .then(r=>r.json())
  .then(res=>{
    if(res.status==='ok'){
      const list=document.getElementById(`list_${classID}`);
      if(list){
        // Remove placeholder
        const placeholder=Array.from(list.children).find(ch=>ch.textContent.includes('Aucune matière'));
        if(placeholder) placeholder.remove();

        // Create new row
        const newRow=document.createElement('div');
        newRow.className='sub-item new';
        newRow.id=`row_${classID}_${res.subID}`;
        newRow.innerHTML=`
          <div class="sub-left"><span>${res.fullName}</span>
            <input type="number" id="coef_${classID}_${res.subID}" class="coef-input w3-border" value="${coef}" min="0" step="0.1" />
          </div>
          <div class="sub-right">
            <button type="button" class="w3-button w3-blue w3-small" onclick="updateCoef(${classID},${res.subID})">💾</button>
            <button type="button" class="w3-button w3-red w3-small" onclick="deleteSub(${classID},${res.subID})">🗑️</button>
          </div>
        `;
        list.appendChild(newRow);

        // Input listener for coefficient change
        newRow.querySelector('.coef-input').addEventListener('input',function(){
          const btn=this.closest('.sub-item').querySelector('.w3-blue');
          if(btn) btn.style.backgroundColor='orange';
        });

        form.reset();
        setTimeout(()=>newRow.classList.remove('new'),700);
        showMessage('✅ Matière ajoutée : ' + res.fullName,'green');
      }
    } else showMessage(res.message||'Erreur','red');
  })
  .catch(err=>{
    console.error('Erreur fetch:',err);
    showMessage('Erreur serveur','red');
  });
}
</script>
</head>

<body>
<div id="notifBox"></div>

<div class="w3-card-4 w3-padding">
<?php
include 'header.php';
include '_serveur_json.php';
mysqli_set_charset($link,"utf8");

$cycle = $_GET['cycle'] ?? '';
echo "<h2 class='w3-text-teal'>Cycle $cycle — Gestion des coefficients</h2>";

$sql_classes = "SELECT * FROM classes WHERE cycleID='$cycle' ORDER BY id ASC";
$res_classes = mysqli_query($link,$sql_classes);
$classList=[];
while($class=mysqli_fetch_assoc($res_classes)){
  $classList[]=['id'=>$class['id'],'name'=>strtoupper($class['name'])];
}

foreach($classList as $class){
  $classID=$class['id'];
  $className=$class['name'];
  echo "<div class='class-box' id='class$classID'>";
  echo "<div class='class-title'>$className 
          <span class='add-toggle' onclick='toggleAddBox($classID)'>[+ Ajouter matière]</span>
        </div>";

  // --- Add form ---
  echo "<div id='addBox_$classID' class='add-box'>
        <form onsubmit='addSub(event,$classID,\"$cycle\")'>
          <label>Matière :</label>
          <select name='sub' class='w3-select w3-border w3-light-grey' required>";
  $sql_subsAll="SELECT subSubjects.id AS subID, subSubjects.name AS subName, subjects.name AS subjectName
                 FROM subjects JOIN subSubjects ON subjects.id=subSubjects.subjectID
                 ORDER BY subjects.name ASC, subSubjects.name ASC";
  $res_subsAll=mysqli_query($link,$sql_subsAll);
  while($data=mysqli_fetch_assoc($res_subsAll)){
    echo "<option value='{$data['subID']}'>{$data['subjectName']} - {$data['subName']}</option>";
  }
  echo "</select>
        <label>Coefficient :</label>
        <input type='number' name='coef' class='w3-input w3-border w3-light-grey' min='0' step='0.1' required>
        <br><button type='submit' class='w3-button w3-teal'>Ajouter</button>
        </form></div>";

  // --- Existing subjects list ---
  $sql_subs="SELECT subSubjects.name AS subName, subjects.name AS subjectName,
                    gradesSubjects.coeficient AS coef, gradesSubjects.ordering AS ord,
                    gradesSubjects.subSubjectID AS subID
             FROM gradesSubjects
             JOIN subSubjects ON gradesSubjects.subSubjectID=subSubjects.id
             JOIN subjects ON subSubjects.subjectID=subjects.id
             WHERE gradesSubjects.classID='$classID'
             ORDER BY gradesSubjects.ordering ASC";
  $res_subs=mysqli_query($link,$sql_subs);

  echo "<div id='list_$classID'>";
  if(mysqli_num_rows($res_subs)==0){
    echo "<div style='color:gray;'>Aucune matière enregistrée</div>";
  } else {
    while($row=mysqli_fetch_assoc($res_subs)){
      $subID=$row['subID'];
      $fullName=htmlspecialchars($row['subjectName']." - ".$row['subName']);
      $coef=$row['coef'];
      echo "<div class='sub-item' id='row_{$classID}_{$subID}' data-order='{$row['ord']}'>
              <div class='sub-left'><span>$fullName</span>
                <input type='number' id='coef_{$classID}_{$subID}' class='coef-input w3-border' value='$coef' min='0' step='0.1' />
              </div>
              <div class='sub-right'>
                <button type='button' class='w3-button w3-blue w3-small' onclick='updateCoef($classID,$subID)'>💾</button>
                <button type='button' class='w3-button w3-red w3-small' onclick='deleteSub($classID,$subID)'>🗑️</button>
              </div>
            </div>";
    }
  }
  echo "</div></div>";
}
?>
</div>
</body>
</html>
