<?php
//index.php

$appName = 'mondialisa';
session_name($appName);
session_start();
define("APP_LOADED", true);
define('APP_STARTED', true);
require_once 'config.inc.php';
require_once 'iatools.php';

/* teste de l ia prompt 
var_dump(getenv('OPENAI_API_KEY'));
$result = aiAnalyze("je cherche un appartement à rabat moins de 3000 dh");
echo '<pre>';
print_r($result);
echo '</pre>';
exit;
*/



?>

<script>
    document.cookie = "user_tz=" + 
        Intl.DateTimeFormat().resolvedOptions().timeZone + 
        "; path=/";
</script>

<?php
try{


  //country

    // Si country est passé en GET, on met à jour la session
    if (isset($_GET['country']) && !empty($_GET['country'])) {
        $lang = $_SESSION['ln'] ?? 'en';
        $field = "nom_" . $lang;

        $sql = "SELECT code, alpha2, $field AS nom_pays, lang  
                FROM mondialisa_pays 
                WHERE (code = :code OR alpha2 = :code OR alpha3 = :code) AND statut = 1 
                LIMIT 1";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':code', $_GET['country']);
        $stmt->execute();

        $pays = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($pays) {
            $_SESSION['COUNTRY'] = $pays;
            // Enregistrer un cookie pour 30 jours
            setcookie('country', $pays['alpha2'], time() + 30*24*60*60, "/");

//set lang
$_SESSION['LANGUAGE'] = $pays['lang'];
        }
    }

    // Si le cookie existe mais la session est vide, on initialise la session depuis le cookie
    if (!isset($_SESSION['COUNTRY']) && isset($_COOKIE['country'])) {
        $lang = $_SESSION['ln'] ?? 'en';
        $field = "nom_" . $lang;
        $sql = "SELECT code, alpha2, $field AS nom_pays FROM mondialisa_pays WHERE alpha2 = :alpha2 AND statut = 1 LIMIT 1";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':alpha2', $_COOKIE['country']);
        $stmt->execute();
        $pays = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($pays) {
            $_SESSION['COUNTRY'] = $pays;
        }
    }


    
 // Vérifier si le cookie et  la session country non défini alors goto selectcountry
    if (
        (!isset($_SESSION['COUNTRY']) || empty($_SESSION['COUNTRY']))
         && !isset($_COOKIE['country'])
         ) {
        // Redirection vers la page de sélection de pays
        if($_GET['p'] != 'selectcountry'){
        header("Location: index.php?p=selectcountry");
        exit;
        }
     
    }

    //end country

//timezone-----------------------------------------------------------------------------
      
      // Code ISO2 du pays sélectionné
$countryCode = $_SESSION['COUNTRY']['alpha2'] ?? null;

// Fuseau détecté par JS
$userTimezone = $_COOKIE['user_tz'] ?? null;

// Fuseau par défaut
$timezone = 'UTC';

// Si un code pays est défini
if ($countryCode) {
    // Récupérer tous les fuseaux possibles pour ce pays
    $countryTimezones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, strtoupper($countryCode));
    if (!empty($countryTimezones)) {
        // Choisir le premier fuseau comme valeur par défaut
        $timezone = $countryTimezones[0];
    }
}

// Si le fuseau détecté par JS est valide et correspond au pays, l'utiliser
if ($userTimezone && in_array($userTimezone, timezone_identifiers_list())) {
    // Optionnel : vérifier qu'il appartient au pays sélectionné
    if (empty($countryTimezones) || in_array($userTimezone, $countryTimezones)) {
        $timezone = $userTimezone;
    }
}

// Stocker en session et appliquer
$_SESSION['TIMEZONE'] = $timezone;
date_default_timezone_set($_SESSION['TIMEZONE']);




//language--------------------------------------------------------------------------------
    
// Si le GET ln est présent, mettre à jour session et cookie
if (!empty($_GET['ln'])) {
    $lang = $_GET['ln'];
    $_SESSION['LANGUAGE'] = strtoupper($lang);
    addMsg('debug','ln select='. $_SESSION['LANGUAGE']);
    setcookie("language", $_SESSION['LANGUAGE'], time() + 60*60*24*30, "/"); // 30 jours
}

// Définir la direction du texte
$_SESSION['texte_direction'] = (strtolower($_SESSION['LANGUAGE']) === 'ar') ? 'rtl' : 'ltr';

// Vérifier la langue dans la session ou le cookie
if (empty($_SESSION['LANGUAGE'])) {
    if(!empty($_COOKIE['language']))
    {
      $_SESSION['LANGUAGE'] = $_COOKIE['language'];
    }else{
    $_SESSION['LANGUAGE'] = 'en';
    }    
}

//end language





if ($_GET['devise']) {
    $_SESSION['DEVISE'] = $_GET['devise'];
    addMsg('debug', 'Devise changed to : ' . $_SESSION['DEVISE']);
}

if ($_GET['debug'] == 1) {
    $_SESSION['debug'] = true;
}
if ($_GET['debug'] == 2) {
    $_SESSION['debug'] = false;
}
if($_SESSION['debug'] == true){
    showDebugPanel();
}
if ($_GET['readmsgauto'] == true) {
    $_SESSION['readmsgauto'] = true;
}
if ($_GET['readmsgauto'] == false) {
    $_SESSION['readmsgauto'] = false;
}


//products per ligne
 if($_GET['card_ligne']){
    if($_GET['card_ligne'] == "plus" && $_SESSION['card_ligne'] < 6){
        
        $_SESSION['card_ligne'] += 1;
   

    }
    if($_GET['card_ligne'] == "min" && $_SESSION['card_ligne'] > 1){
        
        $_SESSION['card_ligne'] -= 1;
      

    }
    addMsg('debug','card_ligne ='.$_SESSION['card_ligne']);
 }

$categories = $dbh->query("SELECT * FROM ".$dbprefix ."categories ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['categories']=$categories;

 $stmt = $dbh->prepare("SELECT * FROM {$dbprefix}cities WHERE alpha2_country = :country ");
  $stmt->bindParam(':country', $_SESSION['country']['alpha2'], PDO::PARAM_STR); 
  $stmt->execute();
  $cities = $stmt->fetch(PDO::FETCH_ASSOC);



            

}catch(Exception $e){
    catcherror('Error was occured',$e);
    gotoHomepage();
}


?>
<!doctype html>
<html lang="<?= $_SESSION['LANGUAGE']; ?>" dir="<?=  $_SESSION['texte direction']; ?>">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Mondialisa.com</title>
      <meta http-equiv="Content-Language" content="<?php echo $_SESSION['LANGUAGE'] ?? 'fr'; ?>">
          <!-- Favicon -->
    <link href="img/logo.ico" rel="icon">
  <style>
    :root {--accent:#2b7be4; --muted:#6b7280; --bg:#f6f8fb; --card:#ffffff;}
    *{box-sizing:border-box;margin:0;padding:0;font-family:Inter,Arial,sans-serif;}
    body{background:var(--bg);color:#111;}
    a{text-decoration:none;color:inherit;}
    a {
    text-decoration: none !important;
}
a:hover, a:focus {
    text-decoration: none !important;
}

    header{background:var(--card);padding:16px 24px;box-shadow:0 2px 4px rgba(0,0,0,0.05);position:sticky;top:0;z-index:100;}
    .container{max-width:90%;margin:0 auto;}
    .nav{display:flex;align-items:center;gap:16px;}
    .logo{font-weight:700;color:var(--accent);font-size:22px;}
    .nav-space{margin-left:auto;display:flex;gap:12px;align-items:center;}
    .btn{padding:8px 12px;border-radius:8px;border:1px solid rgba(0,0,0,0.1);cursor:pointer;background:#fff;}
    .primary{background:var(--accent);color:#fff;border:none;}

    /* Hero */
    .hero{padding:36px 24px 28px;}
    .hero h1{font-size:28px;margin-bottom:8px;}
    .hero p{color:var(--muted);margin-bottom:16px;}
    .search-card{background:var(--card);padding:20px;border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,0.05);}
    .search-row{display:flex;gap:8px;margin-bottom:12px;}
    .search-row input, .search-row select{flex:1;padding:10px;border-radius:8px;border:1px solid rgba(0,0,0,0.1);}
    .search-row button{padding:10px 16px;border-radius:8px;border:none;background:var(--accent);color:#fff;font-weight:600;cursor:pointer;}
    .cats{display:flex;flex-wrap:wrap;gap:8px;}
    .cat{padding:6px 12px;background:#f0f4ff;border-radius:8px;font-weight:600;display:inline-block;}

    /* Listings */
    .listings{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;margin-top:24px;}
    .listing{background:var(--card);padding:12px;border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,0.05);}
    .listing .thumb{height:140px;border-radius:8px;background:linear-gradient(180deg,#fff,#f3f6ff);display:flex;align-items:flex-end;padding:10px;font-weight:700;}
    .listing .meta{display:flex;justify-content:space-between;margin-top:8px;color:var(--muted);font-size:14px;}
    .price{color:var(--accent);font-weight:700;}

    /* Featured */
    .featured-section{margin-top:32px;}
    .featured-section h2{margin-bottom:16px;}

    /* CTA */
    .cta{display:flex;flex-wrap:wrap;justify-content:space-between;background:#fff;padding:20px;border-radius:12px;margin-top:24px;box-shadow:0 4px 12px rgba(0,0,0,0.05);}
    .cta p{color:var(--muted);}

    /* Footer */
    footer{margin-top:32px;padding:24px;background:var(--card);text-align:center;color:var(--muted);}
    footer nav{margin-top:12px;display:flex;justify-content:center;gap:12px;}

    @media(max-width:768px){
      .search-row{flex-direction:column;}
      .cta{flex-direction:column;align-items:flex-start;gap:12px;}
    }
    
    /* Preview Image */
    #previewBox {
      margin-top:10px;
      max-width:150px;
      max-height:150px;
      border:1px solid #ccc;
      border-radius:8px;
      display:none;
    }
    .banner-pub {
  background-color: #f8f9fa;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 12px;
  max-height: 200px;
  overflow: hidden;
}

.banner-pub img {
  width: auto;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
}
  </style>
  
<!-- Bootstrap CSS + JS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>


<!-- jQuery (nécessaire pour AJAX + Bootstrap 5 modal) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-17800736517"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'AW-17800736517');
</script>
</head>
<body dir="<?=  $_SESSION['texte_direction']; ?>">
      <div class="preloading" style="display: flex; justify-content: center; align-items: center;">
        <center><a href="index.php"><img src="img/loading.gif" /></a></center>
    </div>

 <?php include 'menu.inc.php'; ?>

<main id="maincontainer" class="container-fluid" style="display:none; padding:0 24px;">




<!-- ======== Bannière publicitaire ======== -->
<div class="container my-4">  
  <div class="banner-pub text-center">
    <a href="#" target="_blank" id="banner-link">
    </a>
  </div>
    <a 
        href="https://wa.me/212626090018?text=Bonjour,%20je%20veux%20plus%20de%20détails%20sur%20la%20pub%20sur%20mondialisa.com" 
  
        target="_blank"
      >Show your ad here</a>
</div>
<!-- ======== /Bannière publicitaire ======== -->
<?php 
//showMsg(); moved to inc pages
        if (empty($_SESSION['bopage'])) {
            showMsg();
        } ?>

 <?php
        
        $_SESSION['gotocase'] = $_GET['p'];
        $_SESSION['lastpage'] = $_GET['lastpage'];

       $page = $_GET['p'] ?? 'home';
switch (strtolower($page)) {
            case null:
            case 'home':
                home:
                 global $dbh;
                  $cat = isset($_SESSION['find']['category']) ? $_SESSION['find']['category'] : '';

                //  showMsg();
                  include 'form_recherche.inc.php'; 

                         
                //if $cat is not null then show top and new annonce in cat
                if(!empty($cat))
                {
                //get topannonces in cat
                    $query = 'SELECT * FROM ' . $dbprefix . 'annonces where pays = :pays AND categorie like :cat 
                    and top >= now() and statut = 1 order by id desc limit 8';
                              

                $stmt = $dbh->prepare($query);
                       $stmt->bindValue(':cat', $cat);
                       $stmt->bindValue(':pays', $_SESSION['COUNTRY']['alpha2']);
             
                $stmt->execute();
                if ($stmt) {
                    $result = $stmt->fetchAll();
                      $_SESSION['topannonces'] = $result;
                }
              

                     include 'topannonces.inc.php';

                //get newannonces in cat
          
                    $query = 'SELECT * FROM ' . $dbprefix . 'annonces where pays = :pays AND categorie like :cat 
                      and statut = 1 order by id desc limit 8 ';
               

                $stmt = $dbh->prepare($query);
                             $stmt->bindValue(':cat', $cat );
                            $stmt->bindValue(':pays', $_SESSION['COUNTRY']['alpha2']);

                $stmt->execute();
                if ($stmt) {
                    $result = $stmt->fetchAll();
                        $_SESSION['newannonces'] = $result;
                }                                           

                  include 'newannonces.inc.php';

                    }else{ // cat is empty
                         //get topannonces 
                    $query = 'SELECT * FROM ' . $dbprefix . 'annonces where pays = :pays  
                    and top >= now() and statut = 1 order by id desc limit 8';
                              

                $stmt = $dbh->prepare($query);
             
                       $stmt->bindValue(':pays', $_SESSION['COUNTRY']['alpha2']);
             
                $stmt->execute();
                if ($stmt) {
                    $result = $stmt->fetchAll();
                      $_SESSION['topannonces'] = $result;
                }
              

                     include 'topannonces.inc.php';

                     //new annoncea
                    $query = 'SELECT * FROM ' . $dbprefix . 'annonces where pays = :pays 
                      and statut = 1 order by id desc limit 8 ';
               

                $stmt = $dbh->prepare($query);
                          
                            $stmt->bindValue(':pays', $_SESSION['COUNTRY']['alpha2']);

                $stmt->execute();
                if ($stmt) {
                    $result = $stmt->fetchAll();
                        $_SESSION['newannonces'] = $result;
                }                                           

                  include 'newannonces.inc.php';
  

            }

                break;

                case "newlisting":
                    newlisting:
                    include("newlisting_form.inc.php");
                break;

                 case 'details':
                    if (!empty($_GET['ref'])) {
                    $_SESSION['annonce']['ref'] = $_GET['ref']; /*garder cette ligne avant le nom de ticket
                     pour ne pas modifier la ref si vient de goto*/
                details:
                 global $dbh;


                 
                  // Récupérer l'annonce
                  $ref = $_GET['ref'];
                  $stmt = $dbh->prepare("SELECT * FROM {$dbprefix}annonces WHERE ref = :ref and statut = 1");
                  $stmt->bindParam(':ref', $ref, PDO::PARAM_STR); 
                  $stmt->execute();
                  $annonce = $stmt->fetch(PDO::FETCH_ASSOC);
                  if (!$annonce) {   addMsg('error',trad('Ad not found').' Ref:'.$ref); goto home; }

                  // Récupérer d'autres annonces de la même catégorie
                  $stmt2 = $dbh->prepare("SELECT * FROM {$dbprefix}annonces 
                                          WHERE categorie = ? AND ref != ? AND statut = 1 AND pays = ?
                                          ORDER BY id DESC LIMIT 4");
                  $stmt2->execute([$annonce['categorie'], $ref, $_SESSION['COUNTRY']['alpha2']]);
                  $related = $stmt2->fetchAll(PDO::FETCH_ASSOC);

                  // Nettoyer numéro pour WhatsApp
                  $telWhatsApp = preg_replace('/[^0-9]/', '', $annonce['tel']);


                   include_once 'details.inc.php';

                  } else {
                    goto home;
                }
                break;

                    case 'user_annonce_delete':
                user_annonce_delete:
              
                
                $cando = false;

            if($_SESSION['user']['connected'] && 
            $_SESSION['user']['role'] == 'user' 
            ){
                $cando = true;
            } 

            if(!$cando){
                goto login;
            }
            $ref = $_GET['ref'];
           
            addMsg('debug','delete annonce ref :'.$ref);

            if (!empty($ref)) {
                
                    $query =
                        'DELETE FROM ' .
                        $dbprefix .
                        'annonces WHERE REF like :ref and 
                         user_ref = :user                       
                        limit 1 
                        ';
            
                    $stmt = $dbh->prepare($query);
                    addMsg('debug', $query);
            
                    $stmt->bindParam(':ref', $ref);                            
                    $stmt->bindParam(':user', $_SESSION['user']['ref']);
                    
                    $stmt->execute();

                    if ($stmt->rowCount() > 0) {
                        addMsg('success', trad('Ad deleted'));
                    } else {
                        addMsg('error', trad('Ad not deleted'));
                    }
                    goto dashboard;
                } else {
                    addMsg('error',trad('Ad not found'));
                    goto dashboard;
                }
            
                break;

                case 'booster_annonce':
                  booster_annonce:
                  
                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

if (!isset($_GET['ref'])) {
    addMsg('error', trad("Ref of ad missing"));
    goto lastpage;
    exit;
}

$ref = htmlspecialchars($_GET['ref']);

include 'booster.inc.php';
break;

case 'find':
find:
    global $dbh;

    // Récupération des critères
    $keyword  = isset($_GET['q'])        ? trim($_GET['q'])        : '';
    $location = isset($_GET['location']) ? trim($_GET['location']) : '';
    $cat      = isset($_GET['cat'])      ? trim($_GET['cat'])      : '';

    // Base SQL
    $sql = "SELECT * FROM {$dbprefix}annonces 
            WHERE pays = :pays 
            AND statut = 1";

    $params = [
        ':pays' => $_SESSION['COUNTRY']['alpha2']
    ];

    // Mot-clé
    if ($keyword !== '') {
        $sql .= " AND (titre LIKE :kw OR description LIKE :kw)";
        $params[':kw'] = '%' . $keyword . '%';
    }

    // Catégorie
    if ($cat !== '') {
        $sql .= " AND categorie = :cat";
        $params[':cat'] = $cat;
    }

    // Localisation
    if ($location !== '' && $location !== 'Localisation') {
        $sql .= " AND ville = :loc";
        $params[':loc'] = $location;
    }

    // Tri + limite
    $sql .= " ORDER BY ajtle DESC LIMIT 50";

    addMsg('debug', "Search of ads " . $location . '/' . $cat . '/' . $keyword);

    // Exécution
    $stmt = $dbh->prepare($sql);
    $stmt->execute($params);

    $_SESSION['annonces'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    include 'form_recherche.inc.php';
    include 'annonces_trouvees.inc.php';
    break;


case 'user_monprofil':
user_monprofil:

                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 
include_once 'user_monprofil.inc.php';

break;

/***************************************************** */
case 'propertymanager':
    propertymanager:
    include_once 'propertymanager.inc.php';
    break;

case 'propertymanager_dashboard':
    propertymanager_dashboard:
     if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 
    include_once 'propertymanager_dashboard.inc.php';
    break;

case 'propertymanager_properties_list_my':
    propertymanager_properties_list_my:
     if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 
    $_SESSION['propertymanager']['bopage'] = 'propertymanager_properties_list_my';
    include_once 'propertymanager_dashboard.inc.php';      
    break;
/***************************************************** */
case 'learn':
    learn:
    include_once 'learn_form_find.inc.php';
    break;

case 'learn_my_formations'://list of formations
learn_my_formations:


            if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

$user = $_SESSION['user'];
$user_ref = $user['ref'];

// Récupérer toutes les formations
    global $dbh;
$stmt = $dbh->query("SELECT * FROM mondialisa_formations where statut = 1");
$formations = $stmt->fetchAll();

include_once 'learn.inc.php';

break;


case 'learn_find':
learn_find:


                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

    global $dbh;

    // Récupération des critères
    $keyword  = isset($_GET['q'])        ? trim($_GET['q'])        : '';
  
    $cat      = isset($_GET['cat'])      ? trim($_GET['cat'])      : '';

    // Base SQL
    $sql = "SELECT * FROM {$dbprefix}formations  
            WHERE statut = 1
             ";

    $params = [
        /*':pays' => $_SESSION['COUNTRY']['alpha2']*/
    ];

    // Mot-clé
    if ($keyword !== '') {
        $sql .= " AND (title LIKE :kw )";
        $params[':kw'] = '%' . $keyword . '%';
    }

    // Catégorie
    if ($cat !== '') {
        $sql .= " AND categorie = :cat";
        $params[':cat'] = $cat;
    }

    // Localisation
    if ($location !== '' && $location !== 'Localisation') {
       // $sql .= " AND ville = :loc";
      //  $params[':loc'] = $location;
    }

    // Tri + limite
    $sql .= " ORDER BY id DESC LIMIT 50";

    addMsg('debug', "Search of formation " . $location . '/' . $cat . '/' . $keyword);

    // Exécution
    $stmt = $dbh->prepare($sql);
    $stmt->execute($params);

    $_SESSION['formations'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    include 'learn_form_find.inc.php';
    include 'learn_formations_trouvees.inc.php';
    break;

case 'learn_formation': //list of modules of a formation
learn_formation:

                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

if (!isset($_GET['ref'])) {

goto learn;


}

  global $dbh;


     
$user = $_SESSION['user'];
$user_ref = $user['ref'];
$formation_ref = $_GET['ref'];

// Formation
$stmt = $dbh->prepare("SELECT * FROM mondialisa_formations WHERE ref=?");
$stmt->execute([$formation_ref]);
$formation = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$formation) {
       addMsg('info', 'formation introuvable');
    goto learn;
   // exit;
}

// Modules of this formation
$stmt = $dbh->prepare("
    SELECT * FROM mondialisa_formation_modules 
    WHERE formation_ref=? 
    and statut = 1 
    ORDER BY position ASC
");
$stmt->execute([$formation_ref]);
$modules = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['modules'] = $modules;

/**
 * Progression des modules
 */
$stmt = $dbh->prepare("
    SELECT module_ref, progress
    FROM mondialisa_formation_user_progress
    WHERE user_ref = ?
");
$stmt->execute([$user_ref]);

$moduleProgress = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $moduleProgress[$row['module_ref']] = (int)$row['progress'];
}

include_once 'learn_formation.inc.php';

break;



case 'learn_formation_module': //list of lessons of a module
learn_formation_module:



                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

if (!isset($_GET['ref'])) {
goto learn;

}

  global $dbh;


     
$user = $_SESSION['user'];
$user_ref = $user['ref'];
$module_ref = $_GET['ref'];

// module
$stmt = $dbh->prepare("SELECT * FROM mondialisa_formation_modules WHERE ref=?");
$stmt->execute([$module_ref]);
$module = $stmt->fetch(PDO::FETCH_ASSOC);


if (!$module) {
       addMsg('info', 'module introuvable');
    goto learn;
   // exit;
}

// lessons of this module
$stmt = $dbh->prepare("
    SELECT * FROM mondialisa_formation_lessons 
    WHERE module_ref=? 
    and statut = 1 
    ORDER BY position ASC
");
$stmt->execute([$module_ref]);
$lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['lessons'] = $lessons;

/**
 * Charger la progression de TOUTES les lessons du module
 */
$stmt = $dbh->prepare("
    SELECT lesson_ref, progress
    FROM mondialisa_formation_user_progress
    WHERE user_ref = ?
");
$stmt->execute([$user_ref]);

$lessonProgress = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $lessonProgress[$row['lesson_ref']] = (int)$row['progress'];
}

include_once 'learn_module.inc.php';

break;

case 'learn_formation_module_lesson': // Affichage d'une lesson
learn_formation_module_lesson:


                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

$user_ref = $_SESSION['user']['ref'];
$lesson_ref = $_GET['ref'] ?? '';

if (!$lesson_ref) {
    addMsg('info', 'Lesson non spécifiée');
    goto learn;
}

try {
    // Charger la lesson
    $stmt = $dbh->prepare("
        SELECT * 
        FROM mondialisa_formation_lessons 
        WHERE ref=? AND statut=1
    ");
    $stmt->execute([$lesson_ref]);
    $lesson = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$lesson) {
        addMsg('info', 'Lesson introuvable');
        goto learn;
    }

    // Charger le module parent
    $stmt = $dbh->prepare("
        SELECT * 
        FROM mondialisa_formation_modules
        WHERE ref=? AND statut=1
    ");
    $stmt->execute([$lesson['module_ref']]);
    $module = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$module) {
        addMsg('info', 'Module parent introuvable');
        goto learn;
    }

    // Charger la progression de l'utilisateur pour cette lesson
    $stmt = $dbh->prepare("
        SELECT progress 
        FROM mondialisa_formation_user_progress
        WHERE user_ref=? AND lesson_ref=?
    ");
    $stmt->execute([$user_ref, $lesson_ref]);
    $progress = (int)$stmt->fetchColumn() ?? 0;

} catch (PDOException $e) {
    error_log("Erreur PDO Lesson: ".$e->getMessage());
    addMsg('error', 'Impossible de charger la lesson. Veuillez contacter l’administrateur.');
    goto learn;
}

// Inclure la vue qui affiche la lesson
include_once 'learn_lesson.inc.php';
break;

case 'learn_get_certified': //run exam
learn_get_certified:
    

                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

$user_ref = $_SESSION['user']['ref'];

$formation_ref = $_GET['ref'] ?? null;
if(!$formation_ref){
    addMsg('info','No course was selected');
     goto learn;
}

// Récupérer les questions
$stmt = $dbh->prepare("SELECT * FROM mondialisa_formation_exam WHERE formation_ref=?");
$stmt->execute([$formation_ref]);
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

if(!$questions){
    addMsg('info',"No questions for this course");
    goto learn;
}

    include 'learn_exam.inc.php';
break;

/*************************** */
case 'user_solde_recharge':
user_solde_recharge:

                    if(!$_SESSION['user'] ||  
            !$_SESSION['user']['connected'] 
            ){
                goto login;
            } 

include_once 'user_solde_recharge.inc.php';

break;
case 'contact':
contact:

include_once 'contact.inc.php';

break;


case 'selectcountry':
selectcountry:

include_once 'selectcountry.inc.php';

break;


case 'selectlanguage':
selectlanguage:

include_once 'selectlanguage.inc.php';

break;

case 'tarifs':
tarifs:

include_once 'tarifs.inc.php';

break;


case 'login':
login:

include_once 'login.inc.php';

break;

case 'dashboard' :
  dashboard:
// Vérifier si l'utilisateur est connecté
if (isset($_SESSION['user']['connected']) || $_SESSION['user']['connected'] == true)
     {

        $name  = $_SESSION['user']['lastname'] ?? 'User';
        $ref = $_SESSION['user']['ref'];
       

  
        try {
                      
            //My last 10 online listing
            $query = "SELECT * 
                                FROM {$dbprefix}annonces 
                                WHERE user_ref = :ref   AND statut = 1 
                               
                                LIMIT 10                            
                               "; 
                   $stmt = $dbh->prepare($query);

                               addMsg('debug', $query); 
            $stmt->bindParam(':ref', $ref); 
            
            $stmt->execute();
            $_SESSION['mesannonces'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

            //My count of online listing
              $query = "SELECT count(ref) as totallisting
                                FROM {$dbprefix}annonces 
                                WHERE user_ref = :ref  AND statut = 1  
                           
                               "; 
                   $stmt = $dbh->prepare($query);

                               addMsg('debug', $query); 
            $stmt->bindParam(':ref', $ref); 
            
            $stmt->execute();           
            $_SESSION['totallisting'] = $stmt->fetchColumn(0);


             //My cunt of properties
            $query = "SELECT count(ref)  as totalproperties
                                FROM {$dbprefix}properties  
                                WHERE user_ref = :ref   AND statut = 1 
                               
                                                          
                               "; 
                   $stmt = $dbh->prepare($query);

                               addMsg('debug', $query); 
            $stmt->bindParam(':ref', $ref); 
            
           $stmt->execute();           
            $_SESSION['totalproperties'] = $stmt->fetchColumn(0);

        } catch (Exception $e) {
            catcherror($e,trad('Database error'));
        }
         include_once 'dashboard.inc.php';
     }else{
      goto login;
     }
   
    break;

    
case 'mes_annonces' :
  mes_annonces:
// Vérifier si l'utilisateur est connecté
if (isset($_SESSION['user']['connected']) || $_SESSION['user']['connected'] == true)
     {

        $name  = $_SESSION['user']['lastname'] ?? 'Utilisateur';
        $ref = $_SESSION['user']['ref'];
        $tel   = $_SESSION['tel'] ?? '';

  
        try {
                      
            // Dernières annonces
            $query = "SELECT * 
                                FROM {$dbprefix}annonces 
                                WHERE user_ref = :ref                               
                               "; 
                   $stmt = $dbh->prepare($query);

                               addMsg('debug', $query); 
            $stmt->bindParam(':ref', $ref); 
            
            $stmt->execute();
            $_SESSION['mesannonces'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

        } catch (Exception $e) {
catcherror($e,trad('Database error'));
        }
         include_once 'dashboard.inc.php';
     }else{
      goto login;
     }
   
    break;


default:
addMsg('debug', $_GET['p'] . ' not found');
goto home;


lastpage:
$lp = strtolower($_SESSION['lastpage']);
addMsg('debug','last page = '.$lp);



switch ($lp)
{
case 'home' :
    goto home;
    break;
case 'details' :
        goto details;
        break;

case 'dashboard' :
    goto dashboard;
    break;
}
 break;

            }
  ?>

 


        <!-- Back to Top -->
        <a href="#" class="btn btn-primary back-to-top">Top</a>
<style>
  
.back-to-top {
  position: fixed;
  display: none;
  right: 30px;
  bottom: 30px;
  z-index: 11;
  animation: action 1s infinite alternate;
}
</style>

<script>
    // Back to top button
    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('.back-to-top').fadeIn('slow');
        } else {
            $('.back-to-top').fadeOut('slow');
        }
    });
    $('.back-to-top').click(function () {
        $('html, body').animate({scrollTop: 0}, 1500, 'easeInOutExpo');
        return false;
    });
</script>
    <section class="cta">
      <div>
        <h3><?= trad('Mondialisa for business'); ?></h3>
        <p><?= trad('Subscriptions for agencies, dealerships, and recruiters — publish in bulk and access advanced tools'); ?></p>
      </div>
      <div style="display:flex;gap:8px;align-items:center">
        <a class="btn" href="index.php?p=tarifs"><?= trad('Details'); ?></a>
        <a class="btn btn-primary" href="index.php?p=pro"><?= trad('For business'); ?></a>
      </div>
    </section>


  </main>





<script>
$(document).ready(function(){

  // Aperçu de l'image
  $("#photoInput").on("change", function(){
    const file = this.files[0];
    if(file){
      let reader = new FileReader();
      reader.onload = function(e){
         $("#previewBox").attr("src", e.target.result).show();
      }
      reader.readAsDataURL(file);
    }
  });



});
</script>

<script>
$(document).ready(function() {
    $("#maincontainer").show();
    $(".preloading").hide();
   $(".country").val("<?= $_COOKIE['country']; ?>");
    
});
$(window).on("load", function(){
    $(".preloading").fadeOut();
    $("#maincontainer").fadeIn();
});

</script>

<!-- Chatbox -->
<div id="chatbot-container">
    <div id="chat-box"></div>
    <form id="chat-form">
        <input type="text" id="chat-input" placeholder="find/insert here" autocomplete="off" required>
        <button type="submit">Send</button>
    </form>
</div>

<style>
#chatbot-container {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 320px;
    max-height: 500px;
    background: #fff;
    border: 1px solid #ccc;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    font-family: sans-serif;
    z-index: 9999;
}

#chat-box {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    background: #f9f9f9;
}

#chat-box .user { text-align: right; color: #fff; background: #007bff; padding: 5px 10px; margin: 5px 0; border-radius: 10px; display: inline-block; }
#chat-box .bot  { text-align: left; color: #000; background: #e2e2e2; padding: 5px 10px; margin: 5px 0; border-radius: 10px; display: inline-block; }

#chat-form {
    display: flex;
    border-top: 1px solid #ccc;
}

#chat-input {
    flex: 1;
    border: none;
    padding: 10px;
    outline: none;
}

#chat-form button {
    border: none;
    background: #007bff;
    color: #fff;
    padding: 0 15px;
    cursor: pointer;
}
</style>
<script>
    const chatForm = document.getElementById('chat-form');
const chatInput = document.getElementById('chat-input');
const chatBox = document.getElementById('chat-box');

chatForm.addEventListener('submit', async e => {
    e.preventDefault();
    const msg = chatInput.value.trim();
    if(!msg) return;

    appendMessage('user', msg);
    chatInput.value = '';

    const res = await fetch('chatbot_backend.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: msg })
    });

    const data = await res.json();
    appendMessage('bot', data.reply);
});

function appendMessage(sender, msg) {
    const div = document.createElement('div');
    div.className = sender;

    if (sender === 'bot') {
        div.innerHTML = msg; // ✅ autorise le HTML (liens cliquables)
    } else {
        div.textContent = msg; // sécurité côté utilisateur
    }

    chatBox.appendChild(div);
    chatBox.scrollTop = chatBox.scrollHeight;
}

    </script>
    <?php include_once('footer.inc.php'); ?>
</body>

<style>
/* Appliquer zoom 70% sur les écrans ≥ 1200px (desktop) */
@media (min-width: 1200px) {
    body {
        zoom: 0.9; /* Chrome, Edge, Safari */
        -moz-transform: scale(0.9); /* Firefox */
        -moz-transform-origin: 0 0;
    }
}
</style>
<!-- Event snippet for Clic sortant conversion page -->
<script>
  gtag('event', 'conversion', {
      'send_to': 'AW-17800736517/Ol5fCL_22tAbEIXehqhC',
      'value': 1.0,
      'currency': 'AED'
  });
</script>

</html>
