<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use Config\Database;

class ProfileViewController extends BaseController
{
    /**
     * Lists who viewed the current user's public profile — grouped by
     * viewer with their most recent visit and total view count, plus
     * enough info (name, role, company name if an agency, and their own
     * username so the frontend can link to their live public profile) for
     * the candidate to actually act on it: click through, and reach out
     * via that agency's public profile "Contact via Email" / apply flow.
     */
    public function myViewers()
    {
        $userId = $this->currentUser()->id;
        $db = Database::connect();

        $rows = $db->table('profile_views pv')
            ->select('pv.viewer_user_id, u.name, u.username, r.slug as role_slug, a.company_name, a.logo_path, a.verification_status, owner.username as agency_owner_username,
                      MAX(pv.created_at) as last_viewed_at, COUNT(*) as view_count')
            ->join('users u', 'u.id = pv.viewer_user_id')
            ->join('roles r', 'r.id = u.role_id')
            ->join('agencies a', 'a.id = u.agency_id', 'left')
            ->join('users as owner', 'owner.id = a.owner_user_id', 'left')
            ->where('pv.viewed_user_id', $userId)
            ->groupBy('pv.viewer_user_id')
            ->orderBy('last_viewed_at', 'DESC')
            ->limit(50)
            ->get()->getResultArray();

        foreach ($rows as &$row) {
            // Recruiters don't have their own public profile page (only
            // candidates and agency owners do) — link to their agency's
            // profile instead, since that's what's actually reachable.
            $linkUsername = $row['role_slug'] === 'recruiter' ? $row['agency_owner_username'] : $row['username'];
            $row['profile_url'] = $linkUsername ? base_url('profile/' . $linkUsername) : null;
            unset($row['agency_owner_username']);
        }

        $totalViews = $db->table('profile_views')->where('viewed_user_id', $userId)->countAllResults();

        return $this->jsonSuccess(['viewers' => $rows, 'total_views' => $totalViews]);
    }
}
