<?php

class SessionsModel {
  private $db;

  public function __construct() {
    $this->db = new PDO('mysql:host=localhost;dbname=dykqnvjf_gespes360', 'dykqnvjf_gespes360', 'dykqnvjf_gespes360');
  }

  public function create($id_utilisateur, $ip, $navigateur, $localisation, $type_appareil) {
    $stmt = $this->db->prepare("
      INSERT INTO sessions (
        id_utilisateur, date_connexion, heure_connexion,
        adresse_ip, localisation, type_appareil,
        infos_navigateur, statut_session
      ) VALUES (
        ?, CURDATE(), CURTIME(), ?, ?, ?, ?, 'active'
      )
    ");
    $stmt->execute([
      $id_utilisateur,
      $ip,
      $localisation,
      $type_appareil,
      $navigateur
    ]);
    return $this->db->lastInsertId();
  }

  public function close($id_session) {
    $stmt = $this->db->prepare("
      UPDATE sessions SET
        date_deconnexion = CURDATE(),
        heure_deconnexion = CURTIME(),
        duree_session = SEC_TO_TIME(TIMESTAMPDIFF(SECOND,
          CONCAT(date_connexion, ' ', heure_connexion),
          CONCAT(CURDATE(), ' ', CURTIME())
        )),
        statut_session = 'fermee'
      WHERE id_session = ?
    ");
    $stmt->execute([$id_session]);
  }

  public function listerSessions($id_utilisateur) {
    $stmt = $this->db->prepare("
      SELECT * FROM sessions
      WHERE id_utilisateur = ?
      ORDER BY id_session DESC
    ");
    $stmt->execute([$id_utilisateur]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
  }

  public function totaliserSessions($id_utilisateur) {
    $stmt = $this->db->prepare("
      SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(duree_session))) AS total_duree
      FROM sessions
      WHERE id_utilisateur = ? AND statut_session = 'fermée'
    ");
    $stmt->execute([$id_utilisateur]);
    return $stmt->fetchColumn();
  }
}
?>