<?php
namespace Thirty\controllers;

use Thirty\services\Notifications;

/**
 * Convert datetime to "time ago" format
 * 
 * @param string $datetime
 * @return string
 */
function time_ago($datetime) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    if ($diff->y > 0) {
        return $diff->y . ' año' . ($diff->y > 1 ? 's' : '');
    }
    if ($diff->m > 0) {
        return $diff->m . ' mes' . ($diff->m > 1 ? 'es' : '');
    }
    if ($diff->d > 0) {
        return $diff->d . ' día' . ($diff->d > 1 ? 's' : '');
    }
    if ($diff->h > 0) {
        return $diff->h . ' hora' . ($diff->h > 1 ? 's' : '');
    }
    if ($diff->i > 0) {
        return $diff->i . ' minuto' . ($diff->i > 1 ? 's' : '');
    }
    return 'unos segundos';
}

class FriendsController {

    public static function index(){
        require_auth(); global $DB; $uid=user()['id'];

        // Obtener lista de amigos con avatares
        $st=$DB->prepare('SELECT u.id,u.nick,u.first_name,u.last_name,p.avatar_url as avatar
                          FROM friendships f
                          JOIN users u ON u.id=f.friend_id
                          LEFT JOIN profiles p ON p.user_id=u.id
                          WHERE f.user_id=?
                          ORDER BY u.nick');
        $st->execute([$uid]); $friends=$st->fetchAll();

        // Solicitudes recibidas con avatares
        $in=$DB->prepare('SELECT fr.id,u.id AS user_id,u.nick,u.first_name,u.last_name,p.avatar_url as avatar,fr.created_at
                          FROM friend_requests fr
                          JOIN users u ON u.id=fr.sender_id
                          LEFT JOIN profiles p ON p.user_id=u.id
                          WHERE fr.receiver_id=? AND fr.status="pending"
                          ORDER BY fr.created_at DESC');
        $in->execute([$uid]); $incoming=$in->fetchAll();

        // Solicitudes enviadas con avatares
        $out=$DB->prepare('SELECT fr.id,u.id AS user_id,u.nick,u.first_name,u.last_name,p.avatar_url as avatar,fr.created_at
                           FROM friend_requests fr
                           JOIN users u ON u.id=fr.receiver_id
                           LEFT JOIN profiles p ON p.user_id=u.id
                           WHERE fr.sender_id=? AND fr.status="pending"
                           ORDER BY fr.created_at DESC');
        $out->execute([$uid]); $outgoing=$out->fetchAll();

        view('friends/index', compact('friends','incoming','outgoing'));
    }

    public static function search(){
        require_auth(); global $DB; $uid=user()['id'];
        $q=trim($_GET['q']??''); $results=[];
        if($q!==''){
            $like='%'.$q.'%';
            $st=$DB->prepare('SELECT u.id,u.nick,u.first_name,u.last_name,p.avatar_url as avatar
                              FROM users u
                              LEFT JOIN profiles p ON p.user_id=u.id
                              WHERE u.id<>?
                                AND (u.nick LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)
                              ORDER BY u.nick
                              LIMIT 50');
            $st->execute([$uid,$like,$like,$like]); $rows=$st->fetchAll();

            $f=$DB->prepare('SELECT friend_id FROM friendships WHERE user_id=?');
            $f->execute([$uid]); $friendIds=array_column($f->fetchAll(),'friend_id');

            $req=$DB->prepare('SELECT sender_id,receiver_id,status
                               FROM friend_requests
                               WHERE (sender_id=? OR receiver_id=?)');
            $req->execute([$uid,$uid]); $map=[];
            foreach($req->fetchAll() as $r){ $map[$r['sender_id'].'-'.$r['receiver_id']]=$r['status']; }

            foreach($rows as $r){
                $state='none';
                if(in_array($r['id'],$friendIds)) $state='friend';
                else{
                    $k1=$uid.'-'.$r['id']; $k2=$r['id'].'-'.$uid;
                    if(($map[$k1]??'')==='pending') $state='outgoing';
                    elseif(($map[$k2]??'')==='pending') $state='incoming';
                }
                $r['state']=$state; $results[]=$r;
            }
        }
        view('friends/search',['q'=>$q,'results'=>$results]);
    }

    public static function searchSuggestions() {
        require_auth(); 
        global $DB; 
        $uid = user()['id'];
        $q = trim($_GET['q'] ?? '');
        $results = [];

        if ($q !== '' && strlen($q) >= 2) {
            $like = '%' . $q . '%';
            $st = $DB->prepare('SELECT u.id, u.nick, u.first_name, u.last_name, p.avatar_url as avatar
                              FROM users u
                              LEFT JOIN profiles p ON p.user_id=u.id
                              WHERE u.id <> ?
                                AND (u.nick LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)
                              ORDER BY 
                                CASE 
                                    WHEN u.nick LIKE ? THEN 1
                                    WHEN u.first_name LIKE ? THEN 2
                                    WHEN u.last_name LIKE ? THEN 3
                                    ELSE 4
                                END,
                                u.nick
                              LIMIT 8');
            $st->execute([$uid, $like, $like, $like, $q.'%', $q.'%', $q.'%']);
            $rows = $st->fetchAll();

            $f = $DB->prepare('SELECT friend_id FROM friendships WHERE user_id = ?');
            $f->execute([$uid]);
            $friendIds = array_column($f->fetchAll(), 'friend_id');

            $req = $DB->prepare('SELECT sender_id, receiver_id, status
                               FROM friend_requests
                               WHERE (sender_id = ? OR receiver_id = ?)');
            $req->execute([$uid, $uid]);
            $map = [];
            foreach ($req->fetchAll() as $r) {
                $map[$r['sender_id'] . '-' . $r['receiver_id']] = $r['status'];
            }

            foreach ($rows as $r) {
                $state = 'none';
                if (in_array($r['id'], $friendIds)) {
                    $state = 'friend';
                } else {
                    $k1 = $uid . '-' . $r['id'];
                    $k2 = $r['id'] . '-' . $uid;
                    if (($map[$k1] ?? '') === 'pending') {
                        $state = 'outgoing';
                    } elseif (($map[$k2] ?? '') === 'pending') {
                        $state = 'incoming';
                    }
                }
                $results[] = [
                    'id' => $r['id'],
                    'nick' => $r['nick'],
                    'first_name' => $r['first_name'],
                    'last_name' => $r['last_name'],
                    'avatar' => $r['avatar'],
                    'state' => $state
                ];
            }
        }

        header('Content-Type: application/json');
        echo json_encode($results);
        exit;
    }

    public static function request(){
        require_auth(); verify_csrf(); global $DB;
        $uid=user()['id']; $target=(int)($_POST['user_id']??0);

        if($target<=0 || $target===$uid){
            set_flash('Usuario no válido.'); redirect(base_url('/friends/search'));
        }

        $chk=$DB->prepare('SELECT 1 FROM friendships WHERE user_id=? AND friend_id=?');
        $chk->execute([$uid,$target]);
        if($chk->fetchColumn()){
            set_flash('Ya sois amigos.'); redirect(base_url('/friends'));
        }

        $dup=$DB->prepare('SELECT id,status
                           FROM friend_requests
                           WHERE (sender_id=? AND receiver_id=?)
                              OR (sender_id=? AND receiver_id=?)');
        $dup->execute([$uid,$target,$target,$uid]);
        $row=$dup->fetch();
        $DB->beginTransaction();
        try{
            if($row){
                $DB->prepare('UPDATE friend_requests
                              SET status="pending", created_at=NOW(), responded_at=NULL
                              WHERE id=?')->execute([$row['id']]);
            } else {
                $DB->prepare('INSERT INTO friend_requests (sender_id,receiver_id,status)
                              VALUES (?,?, "pending")')->execute([$uid,$target]);
            }
            // 🔔 Notificación para el receptor - CORREGIDO
            Notifications::create($DB, $target, 'friend_request', ['from_user_id' => $uid]);

            $DB->commit();
            set_flash('Solicitud enviada.');
        } catch(\Throwable $e){
            $DB->rollBack();
            set_flash('No se pudo enviar la solicitud.');
        }
        redirect(base_url('/friends'));
    }

    public static function accept(){
        require_auth(); verify_csrf(); global $DB;
        $uid=user()['id']; $rid=(int)($_POST['request_id']??0);

        $sel=$DB->prepare('SELECT id,sender_id,receiver_id,status
                           FROM friend_requests
                           WHERE id=? AND receiver_id=?');
        $sel->execute([$rid,$uid]); $req=$sel->fetch();
        if(!$req || $req['status']!=='pending'){
            set_flash('Solicitud no encontrada.'); redirect(base_url('/friends'));
        }

        $DB->beginTransaction();
        try{
            $DB->prepare('UPDATE friend_requests
                          SET status="accepted", responded_at=NOW()
                          WHERE id=?')->execute([$rid]);

            $DB->prepare('INSERT IGNORE INTO friendships (user_id,friend_id)
                          VALUES (?,?),(?,?)')
               ->execute([$req['sender_id'],$req['receiver_id'],$req['receiver_id'],$req['sender_id']]);

            // 🔔 Notificación para el emisor original - CORREGIDO
            Notifications::create($DB, (int)$req['sender_id'], 'friend_accept', ['by_user_id' => $uid]);

            $DB->commit();
            set_flash('Solicitud aceptada.');
        } catch(\Throwable $e){
            $DB->rollBack();
            set_flash('Error al aceptar.');
        }
        redirect(base_url('/friends'));
    }

    public static function reject(){
        require_auth(); verify_csrf(); global $DB; $uid=user()['id'];
        $rid=(int)($_POST['request_id']??0);
        $DB->prepare('UPDATE friend_requests
                      SET status="rejected", responded_at=NOW()
                      WHERE id=? AND receiver_id=? AND status="pending"')
           ->execute([$rid,$uid]);
        set_flash('Solicitud rechazada.');
        redirect(base_url('/friends'));
    }

    public static function cancel(){
        require_auth(); verify_csrf(); global $DB; $uid=user()['id'];
        $rid=(int)($_POST['request_id']??0);
        $DB->prepare('DELETE FROM friend_requests
                      WHERE id=? AND sender_id=? AND status="pending"')
           ->execute([$rid,$uid]);
        set_flash('Solicitud cancelada.');
        redirect(base_url('/friends'));
    }

    public static function unfriend(){
        require_auth(); verify_csrf(); global $DB; $uid=user()['id'];
        $fid=(int)($_POST['friend_id']??0);
        $DB->prepare('DELETE FROM friendships
                      WHERE (user_id=? AND friend_id=?)
                         OR (user_id=? AND friend_id=?)')
           ->execute([$uid,$fid,$fid,$uid]);
        set_flash('Amistad eliminada.');
        redirect(base_url('/friends'));
    }
}