<?php
require_once('../controller/config.php');
require_once('SimpleXLSX.php');

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// --- 1. معالجة رفع ملف الإكسيل (الأساسي) ---
if (isset($_POST['save_to_db']) && isset($_FILES['excel_file']['tmp_name'])) {
    if ($xlsx = Shuchkin\SimpleXLSX::parse($_FILES['excel_file']['tmp_name'])) {
        $headers = $xlsx->rows()[0];
        foreach ($xlsx->rows() as $idx => $row) {
            if ($idx === 0) continue;
            $respId = $row[0] ?? '0';
            $prof   = !empty(trim($row[7] ?? '')) ? trim($row[7]) : "غير محدد";
            $date   = !empty($row[10]) ? date("Y-m-d", strtotime($row[10])) : ""; 
            $spe    = $row[12] ?? ''; 
            
            $sub = "غير محدد";
            for ($i = 14; $i <= 38; $i++) { 
                if (!empty($row[$i]) && $row[$i] !== 'N/A') { $sub = trim($row[$i]); break; } 
            }

            foreach ($row as $key => $val) {
                if ($key < 39 || empty($val) || $val === 'N/A') continue;
                if (isset($headers[$key]) && strpos($headers[$key], '[') !== false) {
                    preg_match('/\[(\d+)\s+(.*?)\]/', $headers[$key], $m);
                    $reg = $m[1] ?? '';
                    $name = $m[2] ?? $headers[$key];
                    
                    $sql = "REPLACE INTO attendance (id, registration_number, full_name, specialization, subject, professor_name, session_date, status) 
                            VALUES ('".$respId.$reg."', '$reg', '".mysqli_real_escape_string($conn, $name)."', '$spe', '$sub', '$prof', '$date', '$val')";
                    mysqli_query($conn, $sql);
                }
            }
        }
        header("Location: " . $_SERVER['PHP_SELF'] . "?success=upload");
        exit();
    }
}

// --- 2. معالجة تحديث النواقص يدوياً ---
if (isset($_POST['update_missing'])) {
    $row_id = mysqli_real_escape_string($conn, $_POST['row_id']);
    // جلب البيانات القديمة للتأكد من عدم استبدال البيانات الموجودة أصلاً
    $check = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM attendance WHERE id = '$row_id'"));
    
    $new_sub = ($check['subject'] == 'غير محدد' || empty($check['subject'])) ? mysqli_real_escape_string($conn, $_POST['new_subject']) : $check['subject'];
    $new_prof = ($check['professor_name'] == 'غير محدد' || empty($check['professor_name'])) ? mysqli_real_escape_string($conn, $_POST['new_prof']) : $check['professor_name'];
    $new_date = (empty($check['session_date']) || $check['session_date'] == '0000-00-00') ? mysqli_real_escape_string($conn, $_POST['new_date']) : $check['session_date'];
    
    mysqli_query($conn, "UPDATE attendance SET subject = '$new_sub', professor_name = '$new_prof', session_date = '$new_date' WHERE id = '$row_id'");
    header("Location: " . $_SERVER['PHP_SELF'] . "?success=update");
    exit();
}

// --- 3. جلب البيانات والربط مع التخصص والمستوى ---
$sql = "SELECT a.*, e.libelle_niveau, e.speId as student_speId 
        FROM attendance a 
        LEFT JOIN etudiants e ON (TRIM(a.registration_number) COLLATE utf8mb4_unicode_ci) = TRIM(e.nins)
        ORDER BY a.session_date DESC";
$res = mysqli_query($conn, $sql);

// خيارات الفلاتر
$levels_opt = mysqli_query($conn, "SELECT DISTINCT libelle_niveau FROM etudiants WHERE libelle_niveau != ''");
$specialties_opt = mysqli_query($conn, "SELECT DISTINCT speId FROM etudiants WHERE speId != ''");
$professors_opt = mysqli_query($conn, "SELECT DISTINCT professor_name FROM attendance WHERE professor_name != ''");

include_once('head.php');
include_once('../view/header_dpt.php');
?>

<style>
    .filter-box { background: #fff; padding: 20px; border-radius: 5px; margin-bottom: 20px; border-top: 3px solid #3c8dbc; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    .bg-navy { background-color: #001f3f !important; color: white; }
    .missing-row { background-color: #fff9c4 !important; }
    .locked-input { background-color: #eee !important; color: #777; cursor: not-allowed; pointer-events: none; }
    .label-missing { font-size: 10px; background: #dd4b39; color: #fff; padding: 2px 5px; border-radius: 3px; }
</style>

<div class="content-wrapper">
    <section class="content">
        
        <div class="box box-success box-solid">
            <div class="box-body text-center">
                <form action="" method="post" enctype="multipart/form-data" class="form-inline">
                    <label>تحميل إكسيل جديد: </label>
                    <input type="file" name="excel_file" class="form-control" required>
                    <button type="submit" name="save_to_db" class="btn btn-success"><i class="fa fa-upload"></i> رفع ومزامنة البيانات</button>
                </form>
            </div>
        </div>

        <div class="filter-box" dir="rtl">
            <div class="row">
                <div class="col-md-2">
                    <label>المستوى:</label>
                    <select id="f_niv" class="form-control js-filter">
                        <option value="">-- الكل --</option>
                        <?php while($n = mysqli_fetch_assoc($levels_opt)) echo "<option value='{$n['libelle_niveau']}'>{$n['libelle_niveau']}</option>"; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>التخصص (speId):</label>
                    <select id="f_spe" class="form-control js-filter">
                        <option value="">-- الكل --</option>
                        <?php while($s = mysqli_fetch_assoc($specialties_opt)) echo "<option value='{$s['speId']}'>{$s['speId']}</option>"; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>الأستاذ:</label>
                    <select id="f_prof" class="form-control js-filter">
                        <option value="">-- الكل --</option>
                        <?php while($p = mysqli_fetch_assoc($professors_opt)) echo "<option value='{$p['professor_name']}'>{$p['professor_name']}</option>"; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label>بحث بالاسم أو الرقم:</label>
                    <input type="text" id="f_search" class="form-control js-filter" placeholder="بحث...">
                </div>
            </div>
            <div class="row text-center" style="margin-top: 15px;">
                <button type="button" class="btn btn-warning" onclick="filterMissingOnly()"> عرض كل النواقص <i class="fa fa-warning"></i></button>
                <button type="button" class="btn btn-default" onclick="window.location.reload()">إظهار الكل</button>
            </div>
        </div>

        <div class="box box-primary">
            <div class="table-responsive">
                <table class="table table-bordered text-center" dir="rtl">
                    <thead>
                        <tr class="bg-navy">
                            <th>الرقم</th>
                            <th>الاسم الكامل</th>
                            <th>المستوى</th>
                            <th>التخصص</th>
                            <th>المقياس</th>
                            <th>الأستاذ</th>
                            <th>التاريخ</th>
                            <th>الإجراء</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <?php while($row = mysqli_fetch_assoc($res)): 
                            $mSub = ($row['subject'] == 'غير محدد' || empty($row['subject']));
                            $mProf = ($row['professor_name'] == 'غير محدد' || empty($row['professor_name']));
                            $mDate = (empty($row['session_date']) || $row['session_date'] == '0000-00-00');
                            $isMissing = ($mSub || $mProf || $mDate);
                        ?>
                        <tr class="data-row <?= $isMissing ? 'missing-row' : '' ?>" 
                            data-spe="<?= $row['student_speId'] ?>" 
                            data-niv="<?= $row['libelle_niveau'] ?>"
                            data-prof="<?= $row['professor_name'] ?>"
                            data-missing="<?= $isMissing ? '1' : '0' ?>">
                            
                            <td><?= $row['registration_number'] ?></td>
                            <td class="text-right"><?= $row['full_name'] ?></td>
                            <td><?= $row['libelle_niveau'] ?></td>
                            <td><b><?= $row['student_speId'] ?></b></td>
                            <td><?= $row['subject'] ?> <?= $mSub ? '<span class="label-missing">ناقص</span>' : '' ?></td>
                            <td><?= $row['professor_name'] ?> <?= $mProf ? '<span class="label-missing">ناقص</span>' : '' ?></td>
                            <td><?= $row['session_date'] ?> <?= $mDate ? '<span class="label-missing">ناقص</span>' : '' ?></td>
                            <td>
                                <?php if($isMissing): ?>
                                    <button class="btn btn-xs btn-danger" onclick="openSmartModal('<?= $row['id'] ?>', '<?= $row['subject'] ?>', '<?= $row['professor_name'] ?>', '<?= $row['session_date'] ?>')">تعديل النقص</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </section>
</div>

<div id="smartModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post">
        <div class="modal-header bg-red"><h4 class="modal-title">تعديل البيانات الناقصة فقط</h4></div>
        <div class="modal-body text-right" dir="rtl">
          <input type="hidden" name="row_id" id="m_id">
          
          <div class="form-group" id="group_sub">
            <label>المقياس (Subject):</label>
            <input type="text" name="new_subject" id="m_sub" class="form-control">
            <small class="text-muted" id="lock_sub_msg"></small>
          </div>
          
          <div class="form-group" id="group_prof">
            <label>اسم الأستاذ:</label>
            <input type="text" name="new_prof" id="m_prof" class="form-control">
            <small class="text-muted" id="lock_prof_msg"></small>
          </div>
          
          <div class="form-group" id="group_date">
            <label>تاريخ الحصة:</label>
            <input type="date" name="new_date" id="m_date" class="form-control">
            <small class="text-muted" id="lock_date_msg"></small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="update_missing" class="btn btn-success">حفظ التغييرات</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function openSmartModal(id, sub, prof, date) {
    document.getElementById('m_id').value = id;
    
    const fields = [
        {id: 'm_sub', val: sub, msg: 'lock_sub_msg', emptyVal: 'غير محدد'},
        {id: 'm_prof', val: prof, msg: 'lock_prof_msg', emptyVal: 'غير محدد'},
        {id: 'm_date', val: date, msg: 'lock_date_msg', emptyVal: '0000-00-00'}
    ];

    fields.forEach(field => {
        const input = document.getElementById(field.id);
        const msg = document.getElementById(field.msg);
        
        // إذا كانت الخانة فارغة أو "غير محدد" نفتحها للتعديل
        if (field.val === field.emptyVal || field.val === '' || (field.id === 'm_date' && field.val === '0000-00-00')) {
            input.value = '';
            input.readOnly = false;
            input.classList.remove('locked-input');
            msg.innerText = "هذه الخانة فارغة، يمكنك إدخال البيانات.";
        } else {
            // إذا كانت الخانة ممتلئة، نغلقها
            input.value = field.val;
            input.readOnly = true;
            input.classList.add('locked-input');
            msg.innerText = "تم جلب هذه البيانات من الإكسيل ولا يمكن تعديلها.";
        }
    });

    $('#smartModal').modal('show');
}

function runFilters() {
    const niv = document.getElementById('f_niv').value;
    const spe = document.getElementById('f_spe').value;
    const prof = document.getElementById('f_prof').value;
    const search = document.getElementById('f_search').value.toLowerCase();

    document.querySelectorAll('.data-row').forEach(row => {
        const text = row.innerText.toLowerCase();
        const mN = !niv || row.getAttribute('data-niv') === niv;
        const mS = !spe || row.getAttribute('data-spe') === spe;
        const mP = !prof || row.getAttribute('data-prof') === prof;
        const mT = text.includes(search);
        row.style.display = (mN && mS && mP && mT) ? '' : 'none';
    });
}

function filterMissingOnly() {
    document.querySelectorAll('.data-row').forEach(row => {
        row.style.display = (row.getAttribute('data-missing') === '1') ? '' : 'none';
    });
}

document.querySelectorAll('.js-filter').forEach(el => {
    el.addEventListener('change', runFilters);
    el.addEventListener('input', runFilters);
});
</script>