<?php
// 1. حماية الصفحة: منع الدخول المباشر
if(!isset($_SERVER['HTTP_REFERER'])){
    header('location:../index.php');
    exit;
}

session_start();
include_once('../controller/config.php');

// 2. التحقق من صلاحية الجلسة
if(!isset($_SESSION["index_number"])){
    header('location:../index.php');
    exit;
}

$my_index = $_SESSION["index_number"];
$my_type = $_SESSION["type"];

// 3. جلب بيانات الطبيب
$sql = "SELECT * FROM admin WHERE index_number='$my_index'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$user_name = ($row) ? $row['i_name'] : "Docteur";

// 4. استدعاء الملفات الأساسية كما في المثال
include_once('head_med.php'); 
include_once('../clinic/header_med.php'); 
include_once('sidebar_med.php'); 
include_once('alert_med.php'); 
?>

<style>
.form-control-feedback { pointer-events: auto; }
.set-width-tooltip + .tooltip > .tooltip-inner { min-width:180px; }
.msk-fade { -webkit-animation-name: animatetop; -webkit-animation-duration: 0.5s; animation-name: animatetop; animation-duration: 0.5s; }
.modal-content1 { height: auto; min-height: 100%; border-radius: 0; position: absolute; left: 25%; }
@-webkit-keyframes animatetop { from {top:-300px; opacity:0} to {top:0; opacity:1} }
@keyframes animatetop { from {top:-300px; opacity:0} to {top:0; opacity:1} }

/* ستايل التقويم */
.cal-table{ width:100%; padding:0; margin:0; }
#calendar_dates{ padding:10px; margin-left:10px; width:95%; }
.tHead{ height:40px; background-color:#2c3e50; color:#FFF; text-align:center; border:1px solid #FFF; width:70px; }
.cal-tr{ height:50px; }
.td_no_number{ border:1px solid white; width:70px; background-color:#ecf0f1; padding:0; }
.cal-number-td{ border:1px solid white; width:70px; background-color:#3498db; color:white; }
.h5{ color:#FFF; display: inline-block; background:#2980b9; width:20px; height:20px; font-size:11px; font-weight:bold; text-align:center; float:right; padding-top:3px; }
.div-event-c{ margin-top:65%; height:17px; }
</style>

<div class="content-wrapper">
    <section class="content-header">
        <h1>Tableau de bord <small>Aperçu Médical</small></h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> Accueil</a></li>
            <li class="active">Tableau de bord</li>
        </ol>
    </section>

    <section class="content">
        
        <h4>
            Dr. <?php echo $user_name; ?>, 
            <strong><span style="color:#3c8dbc;"> Bienvenue dans votre espace médical! </span></strong>
        </h4>

        <div class="row">
            <?php
            // دالة لجلب الأرقام الحقيقية
            function getCount($conn, $table, $extra = "") {
                $res = mysqli_query($conn, "SELECT COUNT(*) as total FROM $table $extra");
                $data = mysqli_fetch_assoc($res);
                return ($data) ? $data['total'] : 0;
            }
            ?>
            <div class="col-md-3 col-sm-6 col-xs-12">
                <div class="small-box bg-aqua">
                    <div class="inner"><h3><?php echo getCount($conn, "clinic_appointments", "WHERE date=CURDATE()"); ?></h3><p>Rendez-vous Aujourd'hui</p></div>
                    <div class="icon"><i class="fa fa-calendar"></i></div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6 col-xs-12">
                <div class="small-box bg-green">
                    <div class="inner"><h3><?php echo getCount($conn, "clinic_pharmacy", "WHERE quantity < 10"); ?></h3><p>Alertes Stock</p></div>
                    <div class="icon"><i class="fa fa-medkit"></i></div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6 col-xs-12">
                <div class="small-box bg-purple">
                    <div class="inner"><h3><?php echo getCount($conn, "clinic_consultations"); ?></h3><p>Total Consultations</p></div>
                    <div class="icon"><i class="fa fa-user-md"></i></div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6 col-xs-12">
                <div class="small-box bg-orange">
                    <div class="inner"><h3><?php echo getCount($conn, "clinic_certificates"); ?></h3><p>Certificats Délivrés</p></div>
                    <div class="icon"><i class="fa fa-file-text"></i></div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-8">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title" id="calendar_month_year">Calendrier des Événements</h3>
                    </div>
                    <div class="box-body no-padding">
                        <div id="calendar_dates"></div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="box box-warning">
                    <div class="box-header"><h3 class="box-title">Actions Rapides</h3></div>
                    <div class="box-body">
                        <a href="add_consultation.php" class="btn btn-block btn-primary">Nouvelle Consultation</a>
                        <a href="clinic_pharmacy.php" class="btn btn-block btn-default">Inventaire Médicaments</a>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <script>
    function ShowEvents(status, my_index, my_type) {
        var d = new Date();
        var month_name = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        var m3 = d.getMonth();
        var y1 = d.getFullYear();
        var current_date = d.getDate();

        // هنا يتم استدعاء ملف الأجندة (تأكد من وجود all_events1.php)
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var days = new Date(y1, m3 + 1, 0).getDate();
                var first_day = new Date(y1, m3, 1).getDay();
                var calendar = get_calendar(first_day, days);
                document.getElementById("calendar_dates").appendChild(calendar);
                document.getElementById("calendar_month_year").innerHTML = month_name[m3] + " " + y1;
                $("#td_" + current_date).css("background-color", "#27ae60");
            }
        };
        xhttp.open("GET", "all_events1.php?year=" + y1 + "&month=" + m3 + "&my_type=" + my_type + "&my_index=" + my_index, true);
        xhttp.send();
    }

    function get_calendar(day_no, days) {
        var table = document.createElement('table');
        var tr = document.createElement('tr');
        table.className = 'cal-table';
        var days_arr = ['S','M','T','W','T','F','S'];
        for(var c=0; c<=6; c++){
            var th = document.createElement('th');
            th.innerHTML = days_arr[c];
            th.className = "tHead";
            tr.appendChild(th);
        }
        table.appendChild(tr);
        tr = document.createElement('tr');
        var c;
        for(c=0; c<day_no; c++){
            var td = document.createElement('td');
            td.className = "td_no_number";
            tr.appendChild(td);
        }
        var count = 1;
        for(; c<=6; c++){
            var td = document.createElement('td');
            td.id = "td_" + count;
            td.className = 'cal-number-td';
            var h5 = document.createElement('h5');
            h5.className = 'h5';
            h5.innerHTML = count;
            td.appendChild(h5);
            tr.appendChild(td);
            count++;
        }
        table.appendChild(tr);
        for(var r=3; r<=7; r++){
            tr = document.createElement('tr');
            for(var c=0; c<=6; c++){
                if(count > days) break;
                var td = document.createElement('td');
                td.id = "td_" + count;
                td.className = 'cal-number-td';
                var h5 = document.createElement('h5');
                h5.className = 'h5';
                h5.innerHTML = count;
                td.appendChild(h5);
                tr.appendChild(td);
                count++;
            }
            table.appendChild(tr);
        }
        return table;
    }

    // تشغيل التقويم عند تحميل الصفحة
    window.onload = function() {
        ShowEvents("K", "<?php echo $my_index; ?>", "<?php echo $my_type; ?>");
    };
    </script>

    <script>
    (function(window, location) {
        history.replaceState(null, document.title, location.pathname+"#!/history");
        history.pushState(null, document.title, location.pathname);
        window.addEventListener("popstate", function() {
          if(location.hash === "#!/history") {
            history.replaceState(null, document.title, location.pathname);
            setTimeout(function(){ location.replace("../index.php"); },0);
          }
        }, false);
    }(window, location));
    </script>
</div>

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