<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH . '/libraries/BaseController.php';

class Foryou extends BaseController
{
    private const PER_PAGE = 9;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('common');
        $this->load->model('customer_model');
        $this->load->helper(['url']);
    }
public function setallmorderate(){
  //  echo 'setallmorderate';
    $allposts = $this->common->readdatacollection('Posts');
    //var_dump($allposts);
    foreach($allposts as $k=> $post){
        echo $k;
        echo '<br>';
        $this->common->updatedatamodel('Posts', $k, ['moderationStatus' => 'appropriate']);
    }
}
    
    public function index()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
            return;
        }

        $page = (int)$this->input->get('page');
        $page = $page > 0 ? $page : 1;

        $filters = [
            [
                'field'    => 'moderationStatus',
                'operator' => '==',
                'value'    => 'appropriate',
            ],
            [
                'field'    => 'isArchived',
                'operator' => '==',
                'value'    => false,
            ],
        ];

        $paginated = $this->common->readdatafromcollectionWithPagination('Posts', 'createdDate', 'DESC', $page, self::PER_PAGE, $filters);
        

        $rawPosts = [];
        foreach ($paginated['items'] as $item) {
            $postId = $item['id'] ?? null;
            if ($postId === null) {
                continue;
            }
            $rawPosts[$postId] = $item;
        }

        $posts = $this->preparePosts($rawPosts);

        $this->global['pageTitle'] = 'StreamAdmin : For You Feed';
        $pageData = [
            'posts'       => $posts,
            'pagination'  => [
                'current'    => $paginated['page'],
                'perPage'    => $paginated['perPage'],
                'hasMore'    => $paginated['hasMore'],
                'hasPrev'    => $paginated['page'] > 1,
            ],
        ];

        // echo "<pre>";
        // print_r($pageData);
        // echo "</pre>";
        // exit;

        $this->loadViews('foryou/index', $this->global, $pageData, NULL);
    }

    public function loadMore()
    {
        if (!$this->isAdmin() || !$this->input->is_ajax_request()) {
            show_404();
            return;
        }

        $page = (int)$this->input->get('page');
        $page = $page > 1 ? $page : 2;

        $filters = [
            [
                'field'    => 'moderationStatus',
                'operator' => '==',
                'value'    => 'appropriate',
            ],
            [
                'field'    => 'isArchived',
                'operator' => '==',
                'value'    => false,
            ],
        ];

        $paginated = $this->common->readdatafromcollectionWithPagination('Posts', 'createdDate', 'DESC', $page, self::PER_PAGE, $filters);
        $rawPosts = [];
        foreach ($paginated['items'] as $item) {
            $postId = $item['id'] ?? null;
            if ($postId === null) {
                continue;
            }
            $rawPosts[$postId] = $item;
        }
        $posts = $this->preparePosts($rawPosts);

        $html = $this->load->view('foryou/_posts', ['posts' => $posts, 'context' => 'feed'], true);

        $response = [
            'success' => true,
            'html'    => $html,
            'page'    => $paginated['page'],
            'hasMore' => $paginated['hasMore'],
        ];

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    public function markAppropriate()
    {
        if (!$this->isAdmin() || !$this->input->is_ajax_request()) {
            show_404();
            return;
        }

        $postId = trim($this->input->post('postId'));
        if (empty($postId)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['success' => false, 'message' => 'Invalid post id']));
            return;
        }

        try {
            $postData = $this->common->readdatadocument('Posts', $postId);
            if (empty($postData)) {
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode(['success' => false, 'message' => 'Post not found']));
                return;
            }

            $postData['markedAt'] = time() * 1000;
            $this->common->adddatamodel('AppropriatePosts', $postId, $postData);
            $this->common->updatedatamodel('Posts', $postId, [
                'moderationStatus'    => 'inappropriate',
                'moderationUpdatedAt' => time() * 1000,
            ]);

            $response = ['success' => true];
        } catch (\Exception $e) {
            $response = ['success' => false, 'message' => $e->getMessage()];
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    public function deletePost()
    {
        if (!$this->isAdmin() || !$this->input->is_ajax_request()) {
            show_404();
            return;
        }

        $postId = trim($this->input->post('postId'));
        if (empty($postId)) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['success' => false, 'message' => 'Invalid post id']));
            return;
        }

        try {
            $this->common->deletedatamodel('Posts', $postId);
            $response = ['success' => true];
        } catch (\Exception $e) {
            $response = ['success' => false, 'message' => $e->getMessage()];
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    }

    private function preparePosts(array $rawPosts): array
    {
        if (empty($rawPosts)) {
            return [];
        }
       
        $posts = [];
        $userCache = [];
       
        foreach ($rawPosts as $postId => $post) {
            $status = strtolower($post['moderationStatus'] ?? '');
            $isArchived = isset($post['isArchived']) ? (bool)$post['isArchived'] : false;
           
            $post['id'] = $postId;
            $post['createdDate'] = isset($post['createdDate']) ? (int)$post['createdDate'] : 0;
            $posts[] = $post;
        }

        usort($posts, function ($a, $b) {
            return ($b['createdDate'] ?? 0) <=> ($a['createdDate'] ?? 0);
        });
        // echo "<pre>";
        // print_r($posts);
        // echo "</pre>";
        

        foreach ($posts as &$post) {
            $userId = $post['userId'] ?? '';
            $userSnapshot = null;
            if (!empty($userId)) {
                if (array_key_exists($userId, $userCache)) {
                    $userSnapshot = $userCache[$userId];
                } else {
                    $userSnapshot = $this->customer_model->get_customerdetails($userId);
                    $userCache[$userId] = $userSnapshot;
                }
            }

            $post['author'] = [
                'name'     => $userSnapshot['fullName'] ?? ($userSnapshot['userName'] ?? 'Unknown User'),
                'userName' => $userSnapshot['fullName'] ?? '',
                'avatar'   => $userSnapshot['image'] ?? '',
            ];

            $post['address'] = $post['address'] ?? '';
            $post['city'] = $post['city'] ?? '';
            $post['privacy'] = $post['privacy'] ?? 'Public';
            $post['allowComments'] = isset($post['allowComments']) ? (bool)$post['allowComments'] : true;
            $post['isPin'] = isset($post['isPin']) ? (bool)$post['isPin'] : false;
            $post['isDraft'] = isset($post['isDraft']) ? (bool)$post['isDraft'] : false;
            $post['hashtags'] = isset($post['hashtags']) && is_array($post['hashtags']) ? $post['hashtags'] : [];
            $post['likedUser'] = isset($post['likedUser']) && is_array($post['likedUser']) ? $post['likedUser'] : [];
            $post['keywords'] = isset($post['keywords']) && is_array($post['keywords']) ? $post['keywords'] : [];
            $post['saveVideos'] = isset($post['saveVideos']) && is_array($post['saveVideos']) ? $post['saveVideos'] : [];
            $post['details'] = $post['detials'] ?? ($post['details'] ?? '');
            $post['songDetails'] = $post['songDetails'] ?? '';
            $post['totalViews'] = 0;

            if (!empty($post['totalviews']) && is_array($post['totalviews'])) {
                $post['totalViews'] = array_reduce($post['totalviews'], function ($carry, $value) {
                    return $carry + (int)$value;
                }, 0);
            }
        }

        return $posts;
    }
}


