<?php
class NotificationsController {
  public static function index($db) {
    require_login();
    $user_id = $_SESSION['user']['id'];
    // limpieza automática
    $db->exec("DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 60 DAY)");
    // paginación
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per = max(1, min(30, (int)($_GET['per'] ?? 10)));
    $offset = ($page - 1) * $per;
    /*__PAGINATION__*/
    
    // Obtener notificaciones no leídas primero
    $unread_notifications = $db->prepare("
      SELECT COUNT(*) as count 
      FROM notifications 
      WHERE user_id = ? AND is_read = FALSE
    ");
    $unread_notifications->execute([$user_id]);
    $unread_count = $unread_notifications->fetch()['count'];
    
    // Obtener todas las notificaciones (CONSULTA SIMPLIFICADA Y SEGURA)
    $notifications = $db->prepare("
      SELECT 
        n.*, 
        u.username as related_username,
        u.profile_image as related_user_image
      FROM notifications n 
      LEFT JOIN users u ON n.related_user_id = u.id 
      WHERE n.user_id = ? 
      ORDER BY n.created_at DESC 
      LIMIT 50
    ");
    $notifications->execute([$user_id]);
    $notifications_data = $notifications->fetchAll();
    
    // Procesar mensajes de notificación
    foreach ($notifications_data as &$notification) {
      $notification['notification_message'] = self::generateNotificationMessage($notification);
    }
    
    // Marcar como leídas solo si hay notificaciones no leídas
    if ($unread_count > 0) {
      $db->prepare("UPDATE notifications SET is_read = TRUE WHERE user_id = ? AND is_read = FALSE")
         ->execute([$user_id]);
      
      // Actualizar contador en sesión
      $_SESSION['unread_notifications'] = 0;
    }
    
    view('notifications/index', [
      'notifications' => $notifications_data,
      'unread_count' => $unread_count
    ]);
  }
  
  private static function generateNotificationMessage($notification) {
    $username = $notification['related_username'] ?? 'Usuario';
    
    switch ($notification['type']) {
      case 'like':
        return "{$username} dio like a tu publicación";
      case 'comment':
        return "{$username} comentó tu publicación";
      case 'tag':
        return "{$username} te etiquetó en una publicación";
      case 'friend_request':
        return "{$username} te envió una solicitud de amistad";
      case 'friend_accept':
        return "{$username} aceptó tu solicitud de amistad";
      case 'message':
        return "{$username} te envió un mensaje";
      default:
        return $notification['message'] ?? 'Nueva notificación';
    }
  }
  
  public static function count($db) {
    require_login();
    $user_id = $_SESSION['user']['id'];
    // limpieza automática
    $db->exec("DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 60 DAY)");
    // paginación
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per = max(1, min(30, (int)($_GET['per'] ?? 10)));
    $offset = ($page - 1) * $per;
    /*__PAGINATION__*/
    
    $stmt = $db->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = FALSE");
    $stmt->execute([$user_id]);
    $count = $stmt->fetch()['count'];
    
    // Guardar en sesión para acceso rápido
    $_SESSION['unread_notifications'] = $count;
    
    return $count;
  }

  public static function delete($db) {
    require_login();
    $user_id = $_SESSION['user']['id'];
    // limpieza automática
    $db->exec("DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 60 DAY)");
    // paginación
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per = max(1, min(30, (int)($_GET['per'] ?? 10)));
    $offset = ($page - 1) * $per;
    /*__PAGINATION__*/
    $id = $_POST['id'] ?? ($_GET['id'] ?? '');
    if (!$id) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'missing id']); return; }
    $stmt = $db->prepare("DELETE FROM notifications WHERE id = ? AND user_id = ?");
    $stmt->execute([$id, $user_id]);
    header('Content-Type: application/json'); echo json_encode(['ok'=>true]);
  }

  public static function markRead($db) {
    require_login();
    $user_id = $_SESSION['user']['id'];
    // limpieza automática
    $db->exec("DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 60 DAY)");
    // paginación
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per = max(1, min(30, (int)($_GET['per'] ?? 10)));
    $offset = ($page - 1) * $per;
    /*__PAGINATION__*/
    $id = $_POST['id'] ?? ($_GET['id'] ?? '');
    if (!$id) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'missing id']); return; }
    $stmt = $db->prepare("UPDATE notifications SET is_read = TRUE WHERE id = ? AND user_id = ?");
    $stmt->execute([$id, $user_id]);
    self::count($db);
    header('Content-Type: application/json'); echo json_encode(['ok'=>true]);
  }

  public static function markAllRead($db) {
    require_login();
    $user_id = $_SESSION['user']['id'];
    // limpieza automática
    $db->exec("DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL 60 DAY)");
    // paginación
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per = max(1, min(30, (int)($_GET['per'] ?? 10)));
    $offset = ($page - 1) * $per;
    /*__PAGINATION__*/
    $stmt = $db->prepare("UPDATE notifications SET is_read = TRUE WHERE user_id = ?");
    $stmt->execute([$user_id]);
    self::count($db);
    header('Content-Type: application/json'); echo json_encode(['ok'=>true]);
  }

  // API: unread count (JSON)
  public static function countApi($db) {
    require_login();
    $count = self::count($db);
    header('Content-Type: application/json');
    echo json_encode(['count' => (int)$count]);
  }

  // Delete all read notifications for current user
  public static function deleteRead($db) {
    require_login();
    $user_id = $_SESSION['user']['id'];
    $stmt = $db->prepare("DELETE FROM notifications WHERE user_id = ? AND is_read = TRUE");
    $stmt->execute([$user_id]);
    header('Content-Type: application/json');
    echo json_encode(['ok' => true]);
  }


  // API: list notifications (JSON with pagination)
  public static function listApi($db) {
    require_login();
    $user_id = $_SESSION['user']['id'];
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per  = max(1, min(30, (int)($_GET['per'] ?? 10)));
    $offset = ($page - 1) * $per;

    $stmt = $db->prepare("SELECT SQL_CALC_FOUND_ROWS id, user_id, type, related_user_id, related_post_id, message, is_read, created_at
                          FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
    $stmt->execute([$user_id, $per, $offset]);
    $notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $total = (int)$db->query("SELECT FOUND_ROWS()")->fetchColumn();
    $pages = max(1, (int)ceil($total / $per));

    header('Content-Type: application/json');
    echo json_encode(['items' => $notifs, 'page' => $page, 'per' => $per, 'total' => $total, 'pages' => $pages]);
  }

}