<?php
class FriendsController {
    public static function index($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        // Inicializar variables
        $search = $_GET['search'] ?? '';
        $search_friends = $_GET['search_friends'] ?? '';
        $filtered_friends = [];
        $search_results = [];
        
        // Obtener amigos (solicitudes aceptadas) - SIEMPRE
        $friends_stmt = $db->prepare("
            SELECT u.id, u.username, u.avatar_url, 
                   CASE WHEN f.user1_id = ? THEN f.user2_id ELSE f.user1_id END as friend_id,
                   f.created_at
            FROM friends f
            JOIN users u ON (f.user1_id = u.id OR f.user2_id = u.id) AND u.id != ?
            WHERE (f.user1_id = ? OR f.user2_id = ?) AND f.status = 'accepted'
            ORDER BY u.username
        ");
        $friends_stmt->execute([$uid, $uid, $uid, $uid]);
        $friends = $friends_stmt->fetchAll();
        
        // Búsqueda entre amigos existentes
        if (!empty($search_friends)) {
            $search_friends_stmt = $db->prepare("
                SELECT u.id, u.username, u.avatar_url, f.created_at
                FROM friends f
                JOIN users u ON (f.user1_id = u.id OR f.user2_id = u.id) AND u.id != ?
                WHERE (f.user1_id = ? OR f.user2_id = ?) 
                AND f.status = 'accepted'
                AND u.username LIKE ?
                ORDER BY u.username
            ");
            $search_friends_stmt->execute([$uid, $uid, $uid, "%$search_friends%"]);
            $filtered_friends = $search_friends_stmt->fetchAll();
        }
        
        // Búsqueda de nuevos usuarios para agregar
        if (!empty($search)) {
            $search_stmt = $db->prepare("
                SELECT u.id, u.username, u.avatar_url 
                FROM users u
                WHERE u.username LIKE ? 
                AND u.id != ?
                AND u.id NOT IN (
                    SELECT CASE 
                        WHEN f.user1_id = ? THEN f.user2_id 
                        ELSE f.user1_id 
                    END as friend_id
                    FROM friends f
                    WHERE (f.user1_id = ? OR f.user2_id = ?) 
                    AND f.status IN ('accepted', 'pending')
                )
                ORDER BY u.username
                LIMIT 10
            ");
            $search_stmt->execute([
                "%$search%", $uid, $uid, $uid, $uid
            ]);
            $search_results = $search_stmt->fetchAll();
        }
        
        // Obtener solicitudes pendientes recibidas
        $requests_received_stmt = $db->prepare("
            SELECT u.id, u.username, u.avatar_url, f.created_at 
            FROM friends f
            JOIN users u ON f.user1_id = u.id
            WHERE f.user2_id = ? AND f.status = 'pending'
            ORDER BY f.created_at DESC
        ");
        $requests_received_stmt->execute([$uid]);
        $requests_received = $requests_received_stmt->fetchAll();
        
        // Obtener solicitudes pendientes enviadas
        $requests_sent_stmt = $db->prepare("
            SELECT u.id, u.username, u.avatar_url, f.created_at 
            FROM friends f
            JOIN users u ON f.user2_id = u.id
            WHERE f.user1_id = ? AND f.status = 'pending'
            ORDER BY f.created_at DESC
        ");
        $requests_sent_stmt->execute([$uid]);
        $requests_sent = $requests_sent_stmt->fetchAll();
        
        view('friends/index', [
            'friends' => $friends,
            'requests_received' => $requests_received,
            'requests_sent' => $requests_sent,
            'search_results' => $search_results,
            'search' => $search,
            'filtered_friends' => $filtered_friends,
            'search_friends' => $search_friends
        ]);
    }

    public static function add($db) {
        require_login();
        $uid = $_SESSION['user']['id'];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            validate_csrf();

            // 1) Intentar obtener el ID directamente con varios nombres de campo
            $friend_id = $_POST['friend_id'] ?? $_POST['id'] ?? $_POST['user_id'] ?? '';

            // 2) Si no llega ID, intentar resolver por username
            if (empty($friend_id)) {
                $username = trim($_POST['username'] ?? '');
                if (!empty($username)) {
                    // Buscar por username exacto
                    $u = $db->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
                    $u->execute([$username]);
                    $row = $u->fetch();
                    if ($row) {
                        $friend_id = $row['id'];
                    } else {
                        flash('error', 'Usuario no encontrado: ' . $username);
                        redirect('friends'); 
                        return;
                    }
                }
            }

            // 3) Validaciones
            if (empty($friend_id)) {
                flash('error', 'No se especificó un usuario válido.');
                redirect('friends'); 
                return;
            }
            
            if ($friend_id == $uid) {
                flash('error', 'No puedes agregarte a ti mismo.');
                redirect('friends'); 
                return;
            }

            // 4) Verificar si el usuario existe
            $user_check = $db->prepare("SELECT id FROM users WHERE id = ?");
            $user_check->execute([$friend_id]);
            if (!$user_check->fetch()) {
                flash('error', 'El usuario no existe.');
                redirect('friends'); 
                return;
            }

            // 5) Evitar duplicados (en cualquier orden)
            $check = $db->prepare("
                SELECT id, status 
                FROM friends 
                WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)
                LIMIT 1
            ");
            $check->execute([$uid, $friend_id, $friend_id, $uid]);
            $exists = $check->fetch();

            if ($exists) {
                if ($exists['status'] === 'pending') {
                    flash('info', 'Ya hay una solicitud pendiente con este usuario.');
                } elseif ($exists['status'] === 'accepted') {
                    flash('info', 'Ya sois amigos.');
                } else {
                    // rejected u otro estado ⇒ creamos nueva solicitud
                    $db->prepare("
                        INSERT INTO friends (id, user1_id, user2_id, status, created_at)
                        VALUES (UUID(), ?, ?, 'pending', NOW())
                    ")->execute([$uid, $friend_id]);

                    $db->prepare("
                        INSERT INTO notifications (id, user_id, type, related_user_id, message, created_at)
                        VALUES (UUID(), ?, 'friend_request', ?, ?, NOW())
                    ")->execute([
                        $friend_id,
                        $uid,
                        "{$_SESSION['user']['username']} te envió una solicitud de amistad"
                    ]);

                    flash('success', 'Solicitud reenviada.');
                }
            } else {
                // 6) Crear nueva solicitud
                $db->prepare("
                    INSERT INTO friends (id, user1_id, user2_id, status, created_at)
                    VALUES (UUID(), ?, ?, 'pending', NOW())
                ")->execute([$uid, $friend_id]);

                $db->prepare("
                    INSERT INTO notifications (id, user_id, type, related_user_id, message, created_at)
                    VALUES (UUID(), ?, 'friend_request', ?, ?, NOW())
                ")->execute([
                    $friend_id,
                    $uid,
                    "{$_SESSION['user']['username']} te envió una solicitud de amistad"
                ]);

                flash('success', 'Solicitud de amistad enviada.');
            }
        }

        redirect('friends');
    }

    public static function accept($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        $friend_id = $_GET['id'] ?? '';
        
        if ($friend_id) {
            // Aceptar solicitud de amistad
            $check = $db->prepare("
                SELECT id FROM friends 
                WHERE user1_id = ? AND user2_id = ? AND status = 'pending'
            ");
            $check->execute([$friend_id, $uid]);
            $request_exists = $check->fetch();
            
            if (!$request_exists) {
                flash('error', 'La solicitud de amistad no existe o ya fue procesada.');
                redirect('friends');
                return;
            }
            
            $stmt = $db->prepare("
                UPDATE friends 
                SET status = 'accepted', updated_at = NOW() 
                WHERE user1_id = ? AND user2_id = ? AND status = 'pending'
            ");
            $stmt->execute([$friend_id, $uid]);
            
            if ($stmt->rowCount() > 0) {
                // Actualizar la notificación original: convertir en "aceptada" para el receptor actual
                $db->prepare("UPDATE notifications 
                              SET type = 'friend_accept', message = CONCAT('Has aceptado la solicitud de ', ?), is_read = TRUE
                              WHERE user_id = ? AND related_user_id = ? AND type = 'friend_request'")
                   ->execute([$username ?? (isset($_POST['username']) ? $_POST['username'] : ''), $uid, $friend_id]);

                // Recalcular contador de no leídas para el receptor
                $cstmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = FALSE");
                $cstmt->execute([$uid]);
                $_SESSION['unread_notifications'] = (int)$cstmt->fetchColumn();
                // Marcar notificación de solicitud como gestionada
                $db->prepare("UPDATE notifications SET is_read = TRUE
                              WHERE user_id = ? AND related_user_id = ? AND type = 'friend_request'")
                   ->execute([$uid, $friend_id]);
                // Crear notificación de aceptación
                $db->prepare("
                    INSERT INTO notifications (id, user_id, type, related_user_id, message, created_at)
                    VALUES (UUID(), ?, 'friend_accept', ?, ?, NOW())
                ")->execute([
                    $friend_id, 
                    $uid,
                    "{$_SESSION['user']['username']} aceptó tu solicitud de amistad"
                ]);
                
                flash('success', 'Solicitud de amistad aceptada.');
            } else {
                flash('error', 'No se pudo aceptar la solicitud. Puede que ya haya sido procesada.');
            }
        } else {
            flash('error', 'ID de amigo no válido.');
        }
        
        redirect('friends');
    }

    public static function reject($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        $friend_id = $_GET['id'] ?? '';
        
        if ($friend_id) {
            // Rechazar solicitud de amistad
            $check = $db->prepare("
                SELECT id FROM friends 
                WHERE user1_id = ? AND user2_id = ? AND status = 'pending'
            ");
            $check->execute([$friend_id, $uid]);
            $request_exists = $check->fetch();
            
            if (!$request_exists) {
                flash('error', 'La solicitud de amistad no existe o ya fue procesada.');
                redirect('friends');
                return;
            }
            
            $stmt = $db->prepare("
                UPDATE friends 
                SET status = 'rejected', updated_at = NOW() 
                WHERE user1_id = ? AND user2_id = ? AND status = 'pending'
            ");
            $stmt->execute([$friend_id, $uid]);
            
            if ($stmt->rowCount() > 0) {
                // Actualizar la notificación original: convertir en "aceptada" para el receptor actual
                $db->prepare("UPDATE notifications 
                              SET type = 'friend_accept', message = CONCAT('Has aceptado la solicitud de ', ?), is_read = TRUE
                              WHERE user_id = ? AND related_user_id = ? AND type = 'friend_request'")
                   ->execute([$username ?? (isset($_POST['username']) ? $_POST['username'] : ''), $uid, $friend_id]);

                // Recalcular contador de no leídas para el receptor
                $cstmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = FALSE");
                $cstmt->execute([$uid]);
                $_SESSION['unread_notifications'] = (int)$cstmt->fetchColumn();
                // Marcar notificación de solicitud como gestionada
                $db->prepare("UPDATE notifications SET is_read = TRUE
                              WHERE user_id = ? AND related_user_id = ? AND type = 'friend_request'")
                   ->execute([$uid, $friend_id]);
                flash('success', 'Solicitud de amistad rechazada.');
            } else {
                flash('error', 'No se pudo rechazar la solicitud.');
            }
        }
        
        redirect('friends');
    }

    public static function remove($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        $friend_id = $_GET['id'] ?? '';
        
        if ($friend_id) {
            // Eliminar amistad
            $check = $db->prepare("
                SELECT id FROM friends 
                WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)
            ");
            $check->execute([$uid, $friend_id, $friend_id, $uid]);
            $friendship_exists = $check->fetch();
            
            if (!$friendship_exists) {
                flash('error', 'La amistad no existe.');
                redirect('friends');
                return;
            }
            
            $stmt = $db->prepare("
                DELETE FROM friends 
                WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)
            ");
            $stmt->execute([$uid, $friend_id, $friend_id, $uid]);
            
            if ($stmt->rowCount() > 0) {
                // Marcar notificación de solicitud como gestionada
                $db->prepare("UPDATE notifications SET is_read = TRUE
                              WHERE user_id = ? AND related_user_id = ? AND type = 'friend_request'")
                   ->execute([$uid, $friend_id]);
                flash('success', 'Amistad eliminada.');
            } else {
                flash('error', 'No se pudo eliminar la amistad.');
            }
        }
        
        redirect('friends');
    }

    public static function search($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        $q = $_GET['q'] ?? '';
        $results = [];
        
        if (!empty($q)) {
            $stmt = $db->prepare("
                SELECT u.id, u.username, u.avatar_url 
                FROM users u
                JOIN friends f ON (f.user1_id = u.id OR f.user2_id = u.id) 
                WHERE (f.user1_id = ? OR f.user2_id = ?) 
                AND f.status = 'accepted'
                AND u.id != ?
                AND u.username LIKE ?
                ORDER BY u.username
                LIMIT 10
            ");
            $stmt->execute([$uid, $uid, $uid, "%$q%"]);
            $results = $stmt->fetchAll();
        }
        
        header('Content-Type: application/json');
        echo json_encode($results);
        exit;
    }
}