<?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_dpt.php'); ?>
<?php include_once('../view/header_dpt.php'); ?>
<?php include_once('sidebar_dpt.php'); ?>
<?php include_once('alert.php'); ?>

<?php
if(!isset($_SERVER['HTTP_REFERER'])){ header('location:../index.php'); exit; }
require_once('../controller/config.php');
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// 1. الإعدادات والفلترة
$threshold = (isset($_GET['limit']) && $_GET['limit'] !== '') ? intval($_GET['limit']) : 0; 
$f_search  = isset($_GET['search_text']) ? mysqli_real_escape_string($conn, $_GET['search_text']) : '';
$f_rfid    = isset($_GET['rfid_card']) ? mysqli_real_escape_string($conn, $_GET['rfid_card']) : '';
$f_start   = isset($_GET['date_from']) ? mysqli_real_escape_string($conn, $_GET['date_from']) : '';
$f_end     = isset($_GET['date_to']) ? mysqli_real_escape_string($conn, $_GET['date_to']) : '';
$f_niveau  = isset($_GET['libelle_niveau']) ? mysqli_real_escape_string($conn, $_GET['libelle_niveau']) : '';
$f_speId   = isset($_GET['speId']) ? mysqli_real_escape_string($conn, $_GET['speId']) : '';
$is_grouped = isset($_GET['group_by']) && $_GET['group_by'] == '1'; 
$show_prof  = isset($_GET['show_prof']) && $_GET['show_prof'] == '1';

// 2. الاستعلام
$where_att = " WHERE 1=1 ";
if (!empty($f_start)) $where_att .= " AND session_date >= '$f_start' ";
if (!empty($f_end))   $where_att .= " AND session_date <= '$f_end' ";

$sql = "SELECT registration_number, professor_name, 
               TRIM(REPLACE(REPLACE(REPLACE(subject, 'أ', 'ا'), 'إ', 'ا'), 'آ', 'ا')) as clean_subject, 
               COUNT(*) as total 
        FROM attendance $where_att 
        GROUP BY registration_number, clean_subject 
        HAVING total >= $threshold 
        ORDER BY registration_number ASC";

$res = mysqli_query($conn, $sql);
$data_final = [];

if($res) {
    while($r = mysqli_fetch_assoc($res)) {
        $reg = trim($r['registration_number']);
        $st_sql = "SELECT * FROM etudiants WHERE TRIM(nins)='$reg'";
        if (!empty($f_rfid)) $st_sql .= " AND carte_rfid = '$f_rfid'";
        $st_q = mysqli_query($conn, $st_sql);
        $st = mysqli_fetch_assoc($st_q);
        
        if(!$st) continue;
        if(!empty($f_search) && stripos($st['noma'].$st['prenoma'], $f_search) === false) continue;
        if(!empty($f_niveau) && $st['libelle_niveau'] != $f_niveau) continue;
        if(!empty($f_speId) && $st['speId'] != $f_speId) continue;

        if($is_grouped) {
            $data_final[$reg]['info'] = $st;
            $data_final[$reg]['subs'][] = $r;
        } else {
            $data_final[] = ['info' => $st, 'data' => $r];
        }
    }
}

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

<style>
body, .content-wrapper { font-family: 'Cairo', sans-serif !important; background-color: #f4f7f9 !important; }
.filter-section { background: #fff; padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border-top: 4px solid #00c0ef; margin-bottom: 20px; }
.rfid-pulse { color: #e74c3c; animation: pulse 1s infinite; margin-left: 8px; }
@keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.4; } 100% { opacity: 1; } }

/* توسيط محتوى الجدول عمودياً */
.table-centered td { vertical-align: middle !important; }

/* تنسيق المقاييس المجمعة */
.subject-card { background: #fff; border: 1px solid #e1e8ed; border-right: 4px solid #3c8dbc; padding: 10px 15px; margin-bottom: 6px; border-radius: 6px; display: flex; justify-content: space-between; align-items: center; }
.badge-abs { background: #dd4b39; color: white; padding: 3px 10px; border-radius: 12px; font-weight: bold; }
.prof-clean { display: block; font-size: 11px; color: #888; margin-top: 2px; }

/* نظام إدارة الملفات */
.file-manage-zone { display: none; margin-top: 8px; border: 1px dashed #ced4da; padding: 8px; border-radius: 5px; background: #fafafa; }
</style>

<div class="content-wrapper">
    <section class="content">
        <div class="text-left" style="margin-bottom: 15px;">
            <button onclick="window.location.href='export.php?'+window.location.search.substring(1)" class="btn btn-success"><i class="fa fa-file-excel-o"></i> تصدير Excel</button>
        </div>

        <div class="filter-section" dir="rtl">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-3 pull-right">
                        <label>البحث:</label>
                        <input type="text" name="search_text" class="form-control" value="<?php echo $f_search; ?>" placeholder="اسم الطالب...">
                    </div>
                    <div class="col-md-3 pull-right">
                        <label><i class="fa fa-rss rfid-pulse"></i> SCAN RFID:</label>
                        <input type="text" name="rfid_card" class="form-control" value="<?php echo $f_rfid; ?>" autofocus style="border: 2px solid #e74c3c;">
                    </div>
                    <div class="col-md-2 pull-right">
                        <label>من:</label>
                        <input type="date" name="date_from" class="form-control" value="<?php echo $f_start; ?>">
                    </div>
                    <div class="col-md-2 pull-right">
                        <label>إلى:</label>
                        <input type="date" name="date_to" class="form-control" value="<?php echo $f_end; ?>">
                    </div>
                    <div class="col-md-2 pull-right">
                        <label>العتبة:</label>
                        <input type="number" name="limit" class="form-control text-center" value="<?php echo $threshold; ?>">
                    </div>
                </div>
                <div class="row" style="margin-top: 15px;">
                    <div class="col-md-3 pull-right">
                        <label>التخصص:</label>
                        <select name="speId" class="form-control">
                            <option value="">-- الكل --</option>
                            <?php $qs=mysqli_query($conn,"SELECT DISTINCT speId FROM etudiants"); 
                            while($s=mysqli_fetch_assoc($qs)) echo "<option value='{$s['speId']}' ".($f_speId==$s['speId']?'selected':'').">{$s['speId']}</option>"; ?>
                        </select>
                    </div>
                    <div class="col-md-3 pull-right">
                        <label>المستوى:</label>
                        <select name="libelle_niveau" class="form-control">
                            <option value="">-- الكل --</option>
                            <?php $qn=mysqli_query($conn,"SELECT DISTINCT libelle_niveau FROM etudiants"); 
                            while($n=mysqli_fetch_assoc($qn)) echo "<option value='{$n['libelle_niveau']}' ".($f_niveau==$n['libelle_niveau']?'selected':'').">{$n['libelle_niveau']}</option>"; ?>
                        </select>
                    </div>
                    <div class="col-md-4 pull-right" style="padding-top: 30px;">
                        <label style="margin-left: 15px;"><input type="checkbox" name="group_by" value="1" <?php echo $is_grouped?'checked':''; ?>> تجميع</label>
                        <label><input type="checkbox" name="show_prof" value="1" <?php echo $show_prof?'checked':''; ?>> إظهار الأستاذ</label>
                    </div>
                    <div class="col-md-2 pull-right">
                        <button type="submit" class="btn btn-info btn-block" style="margin-top:25px;">تحديث</button>
                    </div>
                </div>
            </form>
        </div>

        <table class="table table-bordered text-center table-centered" dir="rtl" style="background: #fff;">
            <thead style="background: #222d32; color: #fff;">
                <tr>
                    <th width="10%">رقم التسجيل</th>
                    <th width="15%">اللقب والاسم</th>
                    <th width="10%">التخصص</th>
                    <th width="10%">المستوى</th>
                    <th>المقياس / الغيابات</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $modals = "";
                foreach($data_final as $reg_id => $item) {
                    $st = $item['info'];
                    if($is_grouped) { ?>
                        <tr>
                            <td><b><?php echo $st['nins']; ?></b></td>
                            <td><b><?php echo $st['noma'].' '.$st['prenoma']; ?></b></td>
                            <td><span class="label label-primary"><?php echo $st['speId']; ?></span></td>
                            <td><span class="label label-info"><?php echo $st['libelle_niveau']; ?></span></td>
                            <td style="text-align: right; padding: 10px;">
                                <?php foreach($item['subs'] as $s): 
                                    $m_id = "m_".preg_replace('/[^A-Za-z0-9]/','',$st['nins'].md5($s['clean_subject'])); ?>
                                    <div class="subject-card">
                                        <div>
                                            <strong><?php echo $s['clean_subject']; ?></strong>
                                            <?php if($show_prof) echo "<span class='prof-clean'>{$s['professor_name']}</span>"; ?>
                                        </div>
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span class="badge-abs"><?php echo $s['total']; ?></span>
                                            <button class="btn btn-sm btn-default" data-toggle="modal" data-target="#<?php echo $m_id; ?>"><i class="fa fa-folder-open"></i></button>
                                        </div>
                                    </div>
                                <?php $modals .= createEnhancedModal($m_id, $st['noma'].' '.$st['prenoma'], $s['clean_subject'], $st['nins'], $conn); endforeach; ?>
                            </td>
                        </tr>
                    <?php } else {
                        $s = $item['data'];
                        $m_id = "m_".preg_replace('/[^A-Za-z0-9]/','',$st['nins'].md5($s['clean_subject'])); ?>
                        <tr>
                            <td><?php echo $st['nins']; ?></td>
                            <td><b><?php echo $st['noma'].' '.$st['prenoma']; ?></b></td>
                            <td><?php echo $st['speId']; ?></td>
                            <td><?php echo $st['libelle_niveau']; ?></td>
                            <td>
                                <div class="subject-card">
                                    <div>
                                        <strong><?php echo $s['clean_subject']; ?></strong>
                                        <?php if($show_prof) echo "<span class='prof-clean'>{$s['professor_name']}</span>"; ?>
                                    </div>
                                    <div style="display: flex; align-items: center; gap: 8px;">
                                        <span class="badge-abs"><?php echo $s['total']; ?></span>
                                        <button class="btn btn-sm btn-default" data-toggle="modal" data-target="#<?php echo $m_id; ?>"><i class="fa fa-cog"></i></button>
                                    </div>
                                </div>
                            </td>
                        </tr>
                <?php $modals .= createEnhancedModal($m_id, $st['noma'].' '.$st['prenoma'], $s['clean_subject'], $st['nins'], $conn); } } ?>
            </tbody>
        </table>
    </section>
</div>

<?php 
echo $modals; 
include_once('footer.php');

function createEnhancedModal($id, $name, $sub, $reg, $conn) {
    ob_start(); ?>
    <div class="modal fade" id="<?php echo $id; ?>" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content" dir="rtl">
                <div class="modal-header bg-navy"><h4>إدارة تبريرات: <?php echo $name; ?></h4></div>
                <div class="modal-body">
                    <p class="well well-sm">المقياس: <b><?php echo $sub; ?></b></p>
                    <table class="table table-bordered">
                        <thead><tr class="bg-gray"><th>التاريخ</th><th>الحالة</th><th>ملف التبرير</th><th>حفظ</th></tr></thead>
                        <tbody>
                        <?php $s_esc = mysqli_real_escape_string($conn, $sub);
                        $res = mysqli_query($conn, "SELECT * FROM attendance WHERE registration_number='$reg' AND REPLACE(REPLACE(REPLACE(subject, 'أ', 'ا'), 'إ', 'ا'), 'آ', 'ا') = '$s_esc'");
                        while($d = mysqli_fetch_assoc($res)): ?>
                            <tr>
                                <td><?php echo $d['session_date']; ?></td>
                                <td>
                                    <select class="form-control" onchange="toggleFileZone(this)">
                                        <option value="غياب غير مبرر" <?php echo ($d['notes']=='غياب غير مبرر')?'selected':''; ?>>غياب غير مبرر</option>
                                        <option value="غياب مبرر" <?php echo ($d['notes']=='غياب مبرر')?'selected':''; ?>>غياب مبرر</option>
                                        <option value="لا يحتسب" <?php echo ($d['notes']=='لا يحتسب')?'selected':''; ?>>لا يحتسب</option>
                                        <option value="حالات أخرى" <?php echo ($d['notes']=='حالات أخرى')?'selected':''; ?>>حالات أخرى</option>
                                    </select>
                                </td>
                                <td>
                                    <div class="file-manage-zone" <?php echo ($d['notes']!=='غياب غير مبرر')?'style="display:block"':''; ?>>
                                        <input type="file" class="form-control input-sm">
                                        <div class="btn-group btn-group-xs" style="margin-top:5px">
                                            <button class="btn btn-info"><i class="fa fa-eye"></i> عرض</button>
                                            <button class="btn btn-warning"><i class="fa fa-refresh"></i> تغيير</button>
                                        </div>
                                    </div>
                                    <?php if($d['notes']=='غياب غير مبرر'): ?>
                                        <span class="text-muted no-file-msg">---</span>
                                    <?php endif; ?>
                                </td>
                                <td><button class="btn btn-success btn-sm"><i class="fa fa-save"></i></button></td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <?php return ob_get_clean();
}
?>

<script>
function toggleFileZone(sel) {
    var zone = $(sel).closest('tr').find('.file-manage-zone');
    var msg = $(sel).closest('tr').find('.no-file-msg');
    if (sel.value === 'غياب غير مبرر') {
        zone.fadeOut();
        msg.fadeIn();
    } else {
        zone.fadeIn();
        msg.fadeOut();
    }
}

// RFID Auto Focus
setInterval(function() {
    if (!$("input").is(":focus")) {
        $("input[name='rfid_card']").focus();
    }
}, 3000);
</script>