<?php
require_once __DIR__ . '/../models/post.php';

class PostController {
    private $db;
    private $postModel;

    public function __construct() {
        $this->db = require __DIR__ . '/../config/database.php';
        $this->postModel = new Post($this->db);
    }

    public function getAll() {
        try {
            $posts = $this->postModel->getAll();

            // Check if user is logged in and add like status
            $userId = $this->getUserIdFromToken();
            if ($userId) {
                foreach ($posts as &$post) {
                    $post['is_liked'] = $this->postModel->checkUserLike($post['id'], $userId);
                }
            }

            echo json_encode(['posts' => $posts]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch posts']);
        }
    }

    public function getOne($params) {
        try {
            $id = $params['id'];
            $post = $this->postModel->getOne($id);

            if (!$post) {
                http_response_code(404);
                echo json_encode(['error' => 'Post not found']);
                return;
            }

            // Check if user is logged in and add like status
            $userId = $this->getUserIdFromToken();
            if ($userId) {
                $post['is_liked'] = $this->postModel->checkUserLike($post['id'], $userId);
            }

            echo json_encode(['post' => $post]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch post']);
        }
    }

    public function getComments($params) {
        try {
            $id = $params['id'];
            $comments = $this->postModel->getComments($id);
            echo json_encode(['comments' => $comments]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch comments']);
        }
    }

    public function likePost($params) {
        try {
            $userId = $this->getUserIdFromToken();
            if (!$userId) {
                http_response_code(401);
                echo json_encode(['error' => 'Unauthorized']);
                return;
            }

            $postId = $params['id'];
            $this->postModel->likePost($postId, $userId);
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to like post']);
        }
    }

    public function addComment($params) {
        try {
            $userId = $this->getUserIdFromToken();
            if (!$userId) {
                http_response_code(401);
                echo json_encode(['error' => 'Unauthorized']);
                return;
            }

            $postId = $params['id'];
            $data = json_decode(file_get_contents('php://input'), true);
            $comment = $data['comment'] ?? '';

            if (empty($comment)) {
                http_response_code(400);
                echo json_encode(['error' => 'Comment cannot be empty']);
                return;
            }

            $this->postModel->addComment($postId, $userId, $comment);
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to add comment']);
        }
    }

    private function getUserIdFromToken() {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? '';

        if (empty($authHeader) || !preg_match('/Bearer/s+(.*)$/i', $authHeader, $matches)) {
            return null;
        }

        $token = $matches[1];

        try {
            $payload = json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $token)[1]))), true);
            return $payload['user_id'] ?? null;
        } catch (Exception $e) {
            return null;
        }
    }
}
?>