<?php session_start(); 
require_once('config.php');
require_once(BASE_PATH . '/db/idl_connect.php');
if (isset($_POST['zipval'])) {
    $error = '';
    $file_folder = 'seqfichiers/' . $prefix . '/';
    if (!extension_loaded('zip')) {
        $error .= ZIPNOEXT;
    } elseif (empty($_POST['files']) || !is_array($_POST['files'])) {
        $error .= ZIPSELECT;
    } else {
        ini_set('memory_limit', '512M');
        set_time_limit(300);
        $zip = new ZipArchive();
        $zip_name = sys_get_temp_dir() . '/idlog_files_' . date('Ymd_His') . '.zip';
        if (
            $zip->open(
                $zip_name,
                ZipArchive::CREATE | ZipArchive::OVERWRITE
            ) !== true
        ) {
            $error .= ZIPECHEC;
        } else {
            $stmt = $pdo->prepare(
                "SELECT docname
                 FROM {$prefix}_seqdocs
                 WHERE docurl = :docurl
                 LIMIT 1"
            );
            foreach ($_POST['files'] as $file) {
                /*
                |--------------------------------------------------------------------------
                | Sécurisation du nom
                |--------------------------------------------------------------------------
                */
                $file = basename($file);
                $fullpath = $file_folder . $file;
                if (!is_file($fullpath)) {
                    continue;
                }
                /*
                |--------------------------------------------------------------------------
                | Recherche nom document
                |--------------------------------------------------------------------------
                */
                $stmt->execute([
                    ':docurl' => $file
                ]);
                $check = $stmt->fetch(PDO::FETCH_ASSOC);
                $zip_internal_name =
                    !empty($check['docname'])
                    ? $check['docname']
                    : $file;
                /*
                |--------------------------------------------------------------------------
                | Ajout ZIP
                |--------------------------------------------------------------------------
                */
                $zip->addFile(
                    $fullpath,
                    $zip_internal_name
                );
            }
            $zip->close();
            if (is_file($zip_name)) {
                /*
                |--------------------------------------------------------------------------
                | Nettoyage buffer
                |--------------------------------------------------------------------------
                */
                if (ob_get_length()) {
                    ob_end_clean();
                }
                header('Content-Type: application/zip');
                header(
                    'Content-Disposition: attachment; filename="' .
                    basename($zip_name) .
                    '"'
                );
                header('Content-Length: ' . filesize($zip_name));
                header('Pragma: no-cache');
                header('Expires: 0');

                readfile($zip_name);

                unlink($zip_name);

                exit;
            }
        }
    }
}
?>
<!doctype html>
<?php 
if(isset($_SESSION['user_droits_arr'])) {
	$droits = (string)($_SESSION['user_droits_arr'] ?? '');
	$_SESSION['user_droits'] = trim($droits);
	if (($_SESSION['user_droits'][1] ?? 0) < 2) {
		echo '<link rel="stylesheet" type="text/css" href="css/idl_solo.css" />
		<link rel="stylesheet" type="text/css" href="css/idl_print.css" media="print" />';
		$page_header = 'edit'; 
		include('include/header.php');
		echo '<p class="noaccess">'.NOMODULE.'<br><a href="index.php">'.ACCUEIL.'</a></p>';
	}
else { $error=""; ?>
<html>
<head>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Séquences - InfodocLog</title>
	<link rel="stylesheet" href="css/jquery-ui.css">
	<link rel="stylesheet" type="text/css" href="css/idl_solo.css" />
	<link rel="stylesheet" type="text/css" href="css/idl_solo_resp.css" />
	<link rel="stylesheet" type="text/css" href="css/idl_print.css" media="print" />
	<link rel="stylesheet" href="include/fontawesome/css/all.css">
	<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
	<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
	<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
	<script type="text/javascript" src="js/jquery-3.7.1.js"></script>
	<script type="text/javascript" src="js/jquery-ui.js"></script>
	<?php 
	include('js/idl/seq_ajax_niveau.php'); 
	include('include/suggest_notions.php');
	?>
	<script language="javascript">
		function toggleDiv(divid){
			var element = document.getElementById(divid);
		    if (element.style.display === 'none') {
		        element.style.display = 'block';
		    } else {
		        element.style.display = 'none';
		    }
		}
		function toggleModu(divid,aplus,aminus,amin2){
			if(document.getElementById(divid).style.display == "none"){
				document.getElementById(divid).style.display = "block";
				document.getElementById(aplus).style.display = "none";
				document.getElementById(aminus).style.display = "inline-block";
				document.getElementById(amin2).style.display = "none";
			}else{
				document.getElementById(divid).style.display = "none";
				document.getElementById(aplus).style.display = "inline-block";
				document.getElementById(aminus).style.display = "none";
				document.getElementById(amin2).style.display = "inline-block";
			}
		}
	</script>
	<script type="text/javascript" src="include/tinymce/tinymce.min.js"></script>
	<?php include('js/idl/chat_box.php'); ?>
</head>

<body>
	
	<?php $page_header = 'edit'; ?>
	<?php include('include/header.php'); 
	if (isset($_SESSION['user_droits']) && isset($pdo)) {
	    $user_id = (int)($_SESSION['user_id'] ?? 0);
	    if ($user_id > 0) {
	        // Vérifie si l'utilisateur existe déjà
	        $stmt = $pdo->prepare(
	            "SELECT COUNT(user_id)
	             FROM {$prefix}_userconnect
	             WHERE user_id = :user_id"
	        );
	        $stmt->execute([
	            ':user_id' => $user_id
	        ]);
	        $exists = (int)$stmt->fetchColumn();
	        if ($exists > 0) {
	            // UPDATE last connection
	            $stmt = $pdo->prepare(
	                "UPDATE {$prefix}_userconnect
	                 SET connected = :connected
	                 WHERE user_id = :user_id"
	            );
	            $stmt->execute([
	                ':connected' => time(),
	                ':user_id' => $user_id
	            ]);
	        } else {
	            // INSERT new record
	            $stmt = $pdo->prepare(
	                "INSERT INTO {$prefix}_userconnect (user_id, connected)
	                 VALUES (:user_id, :connected)"
	            );
	            $stmt->execute([
	                ':user_id' => $user_id,
	                ':connected' => time()
	            ]);
	        }
	    }
	    include('include/chat_div.php');
	}?>
	
	<section>
		<?php include('include/nav/nav_edit.php'); ?>
		<article id="art_edit">
			<?php 
			if(!isset($_GET['page'])) {
				$stmt = $pdo->query(
				    "SELECT COUNT(*) 
				     FROM {$prefix}_sequences"
				);
				$nb_seq = (int)$stmt->fetchColumn();
				if ($nb_seq === 0) {
				    echo '<h1>' . SEQUT . '</h1>
				          <h2>' . SEQNO . ' 
				          <a href="edit.php?page=creation">' . SEQCREA . '</a>.</h2>';
				} else {
					include('./contenu/edit_consult.php');
				}
			}
			else {
				switch($_GET['page']) {
					case'creation':
						include('./contenu/edit_crea.php');
						break;
					case'consult':
						include('./contenu/edit_consult.php');
						break;
					case'docs':
						include('./contenu/edit_documents.php');
						break;
					case'impexp':
						include('./contenu/edit_impexp.php');
						break;
				}
			}
			?>
		</article>
	
	</section>

	<footer id="foot_edit">
	<?php include('include/footer.php'); ?>
	</footer>
</body>
</html>
<?php
}
}
else {
	echo '<link rel="stylesheet" type="text/css" href="css/idl_solo.css" />';
	$page_header = 'edit'; 
	include('include/header.php');
	include('include/noaccess.php');
	echo '<br><a href="index.php">'.ACCUEIL.'</a></p>';
}
?>
