<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Models\User;
use App\Models\Post;
use App\Models\Comment;

class UserController extends Controller
{
    public function index(Request $request): Response
    {
        $userModel = new User();
        $page = (int)$request->get('page', 1);
        $limit = 24;
        $offset = ($page - 1) * $limit;
        
        $users = $userModel->getAll($limit, $offset);
        $totalItems = $userModel->countAll();
        $totalPages = ceil($totalItems / $limit);
        
        return $this->render('user.index', compact('users', 'page', 'totalPages', 'totalItems'));
    }

    public function profile(Request $request, string $username): Response
    {
        if ($username === 'current') {
            if (!Session::has('user_id')) return Response::redirect('/login');
            $username = Session::get('username');
            if (!$username) {
                // Fallback if username not in session
                $userModel = new User();
                $user = $userModel->find(Session::get('user_id'));
                $username = $user['username'];
            }
            return Response::redirect('/u/' . $username);
        }

        $userModel = new User();
        $postModel = new Post();
        $commentModel = new Comment();

        $profile = $userModel->findByUsername($username);
        if (!$profile) return new Response('User not found', 404);

        $posts = $postModel->getByUser($profile['id'], 5);
        $comments = $userModel->getRecentComments($profile['id'], 5);
        $stats = [
            'posts' => count($postModel->getByUser($profile['id'], 999)),
            'comments' => $commentModel->countByUser($profile['id']),
            'best_answers' => $commentModel->countBestAnswersByUser($profile['id']),
        ];

        $title = $profile['username'] . "'s Profile";
        return $this->render('user.profile', compact('profile', 'posts', 'comments', 'stats', 'title'));
    }

    public function edit(Request $request): Response
    {
        $userModel = new User();
        $profile = $userModel->find(Session::get('user_id'));
        if (!$profile) return Response::redirect('/login');
        return $this->render('user.edit', compact('profile'));
    }

    public function update(Request $request): Response
    {
        $userModel = new User();
        $userId = Session::get('user_id');
        $data = [];

        $bio = $request->post('bio', '');
        $data['bio'] = $bio;

        if ($request->post('new_password')) {
            $user = $userModel->find($userId);
            if (!password_verify($request->post('current_password', ''), $user['password'])) {
                Session::flash('error', 'Current password is incorrect');
                return Response::redirect('/profile/edit');
            }
            if ($request->post('new_password') !== $request->post('confirm_password')) {
                Session::flash('error', 'Passwords do not match');
                return Response::redirect('/profile/edit');
            }
            $data['password'] = password_hash($request->post('new_password'), PASSWORD_DEFAULT);
        }

        // Handle avatar
        if (!empty($_FILES['avatar_file']['tmp_name'])) {
            $ext = strtolower(pathinfo($_FILES['avatar_file']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
                $filename = 'avatar_' . $userId . '_' . time() . '.' . $ext;
                $dest = __DIR__ . '/../../public/assets/uploads/avatars/' . $filename;
                if (!is_dir(dirname($dest))) mkdir(dirname($dest), 0755, true);
                if (move_uploaded_file($_FILES['avatar_file']['tmp_name'], $dest)) {
                    $data['avatar'] = $filename;
                }
            }
        } elseif ($request->post('avatar')) {
            $data['avatar'] = $request->post('avatar');
        }

        // Handle cover
        if (!empty($_FILES['cover_file']['tmp_name'])) {
            $ext = strtolower(pathinfo($_FILES['cover_file']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
                $filename = 'cover_' . $userId . '_' . time() . '.' . $ext;
                $dest = __DIR__ . '/../../public/assets/uploads/covers/' . $filename;
                if (!is_dir(dirname($dest))) mkdir(dirname($dest), 0755, true);
                if (move_uploaded_file($_FILES['cover_file']['tmp_name'], $dest)) {
                    $data['cover_image'] = $filename;
                }
            }
        } elseif ($request->post('cover_image')) {
            $data['cover_image'] = $request->post('cover_image');
        }

        if ($request->post('cover_offset') !== null) {
            $data['cover_offset'] = (int)$request->post('cover_offset');
        }

        if (!empty($data)) {
            $userModel->update($userId, $data);
        }
        Session::flash('success', 'Profile updated');
        return Response::redirect('/u/' . Session::get('username'));
    }

    public function notifications(Request $request): Response
    {
        $notifModel = new \App\Models\Notification();
        $notifications = $notifModel->getUnread(Session::get('user_id'));
        $notifModel->markAllRead(Session::get('user_id'));
        return $this->render('user.notifications', compact('notifications'));
    }
}
