<?php
if(!isset($_SERVER['HTTP_REFERER'])){
    header('location:../index.php');
    exit;
}
require_once('../controller/config.php');
// L'accolade qui était ici a été supprimée car elle était inutile
?>
<?php include_once('head.php'); ?>
<?php include_once('../view/header_dpt.php'); ?>
<?php include_once('sidebar_dpt.php'); ?>
<?php include_once('alert.php'); ?>

<?php
/**
 * نظام إدارة الغيابات وتدقيق البيانات
 * الميزات: استيراد Excel، فلترة متقدمة، تعديل النواقص، سجل أمان IP
 */

if(!isset($_SERVER['HTTP_REFERER'])){
    header('location:../index.php');
    exit;
}

require_once('../controller/config.php');

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

// --- [1] دالة جلب الـ IP الحقيقي ---
function get_user_ip() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    return $_SERVER['REMOTE_ADDR'];
}

$user_ip = get_user_ip();
$admin_name = $_SESSION['user_full_name'] ?? $_SESSION['username'] ?? 'Admin';

// --- [2] معالجة رفع ملف الإكسيل (Import) ---
if (isset($_POST['save_to_db']) && isset($_FILES['excel_file']['tmp_name'])) {
    require_once('SimpleXLSX.php');
    if ($xlsx = Shuchkin\SimpleXLSX::parse($_FILES['excel_file']['tmp_name'])) {
        $headers = $xlsx->rows()[0];
        $import_count = 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] ?? ''; 
            $p_note = !empty(trim($row[13] ?? '')) ? trim($row[13]) : ""; 
            
            // استخراج المقياس من الأعمدة المتغيرة
            $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];
                    $att_id = $respId.$reg; // معرف فريد للسجل
                    
                    $sql = "REPLACE INTO attendance (id, registration_number, full_name, specialization, subject, professor_name, session_date, status, prof_notes) 
                            VALUES ('$att_id', '$reg', '".mysqli_real_escape_string($conn, $name)."', 
                                    '$spe', '".mysqli_real_escape_string($conn, $sub)."', 
                                    '".mysqli_real_escape_string($conn, $prof)."', '$date', '$val', 
                                    '".mysqli_real_escape_string($conn, $p_note)."')";
                    if(mysqli_query($conn, $sql)) $import_count++;
                }
            }
        }
        // تسجيل في سجل الأمان
        mysqli_query($conn, "INSERT INTO attendance_audit (admin_name, ip_address, action_type, edit_date) 
                            VALUES ('$admin_name', '$user_ip', 'Excel Import ($import_count)', NOW())");
        
        header("Location: " . $_SERVER['PHP_SELF'] . "?success=upload");
        exit();
    }
}

// --- [3] التعديل اليدوي للنواقص (Update) ---
if (isset($_POST['update_missing'])) {
    $row_id = mysqli_real_escape_string($conn, $_POST['row_id']);
    $up_notes = mysqli_real_escape_string($conn, $_POST['up_notes']);
    
    // جلب البيانات القديمة للتحقق
    $old = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM attendance WHERE id = '$row_id'"));
    
    // تحديث فقط إذا كان الحقل "غير محدد" أو فارغاً
    $new_sub = ($old['subject'] == 'غير محدد' || empty($old['subject'])) ? mysqli_real_escape_string($conn, $_POST['new_subject']) : $old['subject'];
    $new_prof = ($old['professor_name'] == 'غير محدد' || empty($old['professor_name'])) ? mysqli_real_escape_string($conn, $_POST['new_prof']) : $old['professor_name'];
    $new_date = (empty($old['session_date']) || $old['session_date'] == '0000-00-00') ? mysqli_real_escape_string($conn, $_POST['new_date']) : $old['session_date'];
    
    $update_sql = "UPDATE attendance SET 
                    subject = '$new_sub', 
                    professor_name = '$new_prof', 
                    session_date = '$new_date', 
                    prof_notes = '$up_notes' 
                   WHERE id = '$row_id'";
    
    if(mysqli_query($conn, $update_sql)) {
        mysqli_query($conn, "INSERT INTO attendance_audit (admin_name, ip_address, action_type, edit_date) 
                            VALUES ('$admin_name', '$user_ip', 'Manual Edit ID: $row_id', NOW())");
    }
    header("Location: " . $_SERVER['PHP_SELF'] . "?success=update");
    exit();
}

// --- [4] جلب خيارات الفلترة والبيانات ---
$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 != ''");

$sql_main = "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_main);

include_once('head.php');
include_once('../view/header_dpt.php');
include_once('sidebar_dpt.php');
include_once('alert.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); }
    .missing-row { background-color: #fff9c4 !important; border-right: 5px solid #dd4b39; }
    .label-missing { font-size: 10px; background: #dd4b39; color: #fff; padding: 2px 5px; border-radius: 3px; margin-right: 5px; }
    .prof-note-badge { font-size: 11px; background: #f3f4f5; border: 1px solid #d2d6de; padding: 3px; border-radius: 3px; display: block; margin-top: 5px; color: #444; }
    .locked-input { background-color: #eee !important; cursor: not-allowed; border: 1px solid #ccc; }
    .data-row:hover { background-color: #f5f5f5 !important; }
</style>

<div class="content-wrapper">
    <section class="content">
        
        <div class="box box-danger collapsed-box">
            <div class="box-header with-border">
                <h3 class="box-title"><i class="fa fa-shield"></i> سجل الرقابة والأمان (IP Log)</h3>
                <div class="box-tools pull-right"><button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-plus"></i></button></div>
            </div>
            <div class="box-body no-padding">
                <table class="table table-condensed text-center" style="font-size: 13px;">
                    <tr class="bg-gray"><th>المسؤول</th><th>IP Address</th><th>العملية</th><th>التاريخ</th></tr>
                    <?php 
                    $audit = mysqli_query($conn, "SELECT * FROM attendance_audit ORDER BY edit_date DESC LIMIT 5");
                    while($a = mysqli_fetch_assoc($audit)): ?>
                    <tr>
                        <td><strong><?= $a['admin_name'] ?></strong></td>
                        <td><code><?= $a['ip_address'] ?></code></td>
                        <td><?= $a['action_type'] ?></td>
                        <td><?= date('Y-m-d H:i', strtotime($a['edit_date'])) ?></td>
                    </tr>
                    <?php endwhile; ?>
                </table>
            </div>
        </div>

        <div class="box box-success box-solid">
            <div class="box-body text-center">
                <form 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-2">
                    <label>التخصص:</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_data_type" class="form-control js-filter">
                        <option value="all">عرض الكل</option>
                        <option value="missing">النواقص فقط</option>
                        <option value="has_notes">بها ملاحظات</option>
                    </select>
                </div>
                <div class="col-md-5">
                    <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 class="btn btn-warning btn-sm" onclick="quickFilter('missing')">عرض كل النواقص <i class="fa fa-warning"></i></button>
                <button class="btn btn-primary btn-sm" onclick="quickFilter('has_notes')">ملاحظات الأساتذة <i class="fa fa-comment"></i></button>
                <button class="btn btn-default btn-sm" 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" id="printableTable">
                    <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);
                            $hasNote = !empty($row['prof_notes']);
                        ?>
                        <tr class="data-row <?= $isMissing ? 'missing-row' : '' ?>" 
                            data-spe="<?= $row['student_speId'] ?>" 
                            data-niv="<?= $row['libelle_niveau'] ?>"
                            data-missing="<?= $isMissing ? '1' : '0' ?>" 
                            data-notes="<?= $hasNote ? '1' : '0' ?>">
                            
                            <td><?= $row['registration_number'] ?></td>
                            <td class="text-right"><b><?= $row['full_name'] ?></b></td>
                            <td><?= $row['libelle_niveau'] ?></td>
                            <td><?= $row['student_speId'] ?></td>
                            <td>
                                <?= $row['subject'] ?> <?= $mSub ? '<span class="label-missing">ناقص</span>' : '' ?>
                                <?php if($hasNote): ?>
                                    <span class="prof-note-badge"><i class="fa fa-comment"></i> <?= $row['prof_notes'] ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?= $row['professor_name'] ?> <?= $mProf ? '<span class="label-missing">ناقص</span>' : '' ?></td>
                            <td><?= $row['session_date'] ?> <?= $mDate ? '<span class="label-missing">ناقص</span>' : '' ?></td>
                            <td>
                                <button type="button" class="btn btn-xs btn-<?= $isMissing ? 'danger' : 'default' ?>" 
                                onclick="openSmartModal('<?= $row['id'] ?>','<?= addslashes($row['subject']) ?>','<?= addslashes($row['professor_name']) ?>','<?= $row['session_date'] ?>','<?= htmlspecialchars($row['prof_notes']) ?>')">
                                <i class="fa fa-edit"></i> تعديل</button>
                            </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">
              <label>المقياس:</label>
              <input type="text" name="new_subject" id="m_sub" class="form-control">
          </div>
          <div class="form-group">
              <label>الأستاذ:</label>
              <input type="text" name="new_prof" id="m_prof" class="form-control">
          </div>
          <div class="form-group">
              <label>التاريخ:</label>
              <input type="date" name="new_date" id="m_date" class="form-control">
          </div>
          <div class="form-group">
              <label>إضافة/تعديل ملاحظات الأستاذ:</label>
              <textarea name="up_notes" id="m_notes" class="form-control" rows="3"></textarea>
          </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>
// --- [1] محرك الفلترة الذكي ---
function runFilters() {
    const niv = document.getElementById('f_niv').value;
    const spe = document.getElementById('f_spe').value;
    const type = document.getElementById('f_data_type').value;
    const search = document.getElementById('f_search').value.toLowerCase();

    document.querySelectorAll('.data-row').forEach(row => {
        const text = row.innerText.toLowerCase();
        const matchNiv = !niv || row.getAttribute('data-niv') === niv;
        const matchSpe = !spe || row.getAttribute('data-spe') === spe;
        const matchSearch = text.includes(search);
        
        let matchType = true;
        if (type === 'missing') matchType = (row.getAttribute('data-missing') === '1');
        if (type === 'has_notes') matchType = (row.getAttribute('data-notes') === '1');

        row.style.display = (matchNiv && matchSpe && matchSearch && matchType) ? '' : 'none';
    });
}

function quickFilter(mode) {
    document.getElementById('f_data_type').value = mode;
    runFilters();
}

// --- [2] محرك المودال الذكي ---
function openSmartModal(id, sub, prof, date, notes) {
    document.getElementById('m_id').value = id;
    document.getElementById('m_notes').value = notes;
    
    // تعريف الحقول وحالاتها "الفارغة"
    const fields = [
        {id:'m_sub', v:sub, e:'غير محدد'}, 
        {id:'m_prof', v:prof, e:'غير محدد'}, 
        {id:'m_date', v:date, e:'0000-00-00'}
    ];

    fields.forEach(f => {
        const input = document.getElementById(f.id);
        let val = f.v.trim();
        
        // إذا كان الحقل ناقصاً، اجعله متاحاً للكتابة
        if (val === f.e || val === '' || val.includes('0000')) {
            input.value = ''; 
            input.readOnly = false; 
            input.classList.remove('locked-input');
        } else {
            // إذا كان مكتملاً، اقفله لحماية البيانات المستوردة
            input.value = val; 
            input.readOnly = true; 
            input.classList.add('locked-input');
        }
    });
    
    // إظهار المودال (يستخدم jQuery الخاص بـ AdminLTE/Bootstrap)
    $('#smartModal').modal('show');
}

// ربط مستمعات الأحداث للفلاتر
document.querySelectorAll('.js-filter').forEach(el => {
    el.addEventListener('change', runFilters);
    el.addEventListener('input', runFilters);
});
</script>

<?php include_once('footer.php'); ?>