<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;


class Post extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'post_type',
        'user_id',
        'background_color',
        'text_color',
        'font_size',
        'privacy_level',
        'post_text',
        'shared_text',
        'location',
        'media_type',
        'external_link',
        'likes_count',
        'comments_count',
        'shares_count',
        'parent_post_id',
        'video_views_count',
        'reactions_count',
        'views_count',
        'appreciations_count',
        'page_id',
        'group_id',
        'product_id',
        'event_id',
        'post_category',
        'feeling_category',
        'feeling_description',
        'offer_id',
        'poll_id',
        'fund_id',
        'youtube_links',
        'vimeo_links',
        'comments_enabled',
        'color_palette_id',
        'status',
        'ip_address',
        'media_width',
        'media_height',
        'video_thumbnail_url',
        'scheduled_at',
        'is_published',
        'is_anonymous',
        'tips_enabled',
        // GIF fields
        'gif_url',
        'gif_title',
        'gif_provider',
        'updated_by',
        'deleted_by',
        'comments_status',
        'shared_at'
    ];

    /**
     * Define the relationship to the User model.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Define the relationship to the Event model.
     */
    public function event()
    {
        return $this->belongsTo(Event::class);
    }

    /**
     * Define the relationship to the Product model.
     */
    public function product()
    {
        return $this->belongsTo(\App\Models\Marketplace\Product::class, 'product_id');
    }

    /**
     * Page the post is associated with (for page posts).
     */
    public function page()
    {
        return $this->belongsTo(Page::class, 'page_id');
    }

    /**
     * Group the post is associated with (for group posts).
     */
    public function group()
    {
        return $this->belongsTo(Group::class, 'group_id');
    }

    /**
     * Define the relationship to the Comment model.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    /**
     * Define the relationship to the Reaction model.
     */


    /**
     * Define the relationship to the PostLike model.
     */
    public function likes()
    {
        return $this->hasMany(PostLike::class);
    }
    public function fund()
    {
        return $this->belongsTo(Funding::class, 'fund_id');
    }
    /**
     * Get all hashtags from the post text.
     */
    public function getHashtagsAttribute()
    {
        // Extract hashtags from text using regex
        preg_match_all('/#([a-zA-Z0-9_]+)/', $this->post_text, $matches);
        return $matches[1] ?? [];
    }

    /**
     * Get all mentions from the post text.
     */
    public function getMentionsAttribute()
    {
        // Extract mentions from text using regex
        preg_match_all('/@([a-zA-Z0-9_]+)/', $this->post_text, $matches);
        return $matches[1] ?? [];
    }

    /**
     * Increment the like count.
     */
    public function incrementLikes()
    {
        $this->increment('likes_count');
    }

    /**
     * Increment the dislike count.
     */
    public function incrementDislikes()
    {
        $this->increment('dislikes_count');
    }

    /**
     * Increment the comment count.
     */
    public function incrementComments()
    {
        $this->increment('comments_count');
    }

    /**
     * Increment the share count.
     */
    public function incrementShares()
    {
        $this->increment('shares_count');
    }

    /**
     * Check if the post is public.
     */
    public function isPublic()
    {
        return $this->privacy_level === 1;
    }

    /**
     * Check if the post is private.
     */
    public function isPrivate()
    {
        return $this->privacy_level === 3;
    }

    /**
     * Check if the post is visible to a given user.
     */
    public function isVisibleTo($user)
    {
        if ($this->isPublic()) {
            return true;
        }

        if ($this->isPrivate() && $this->user_id === $user->id) {
            return true;
        }


        return false;
    }

    public function poll()
    {
        return $this->belongsTo(Poll::class);
    }
    public function media()
    {
        return $this->hasMany(PostMedia::class, 'post_id');
    }

    public function taggedUsers()
    {
        return $this->belongsToMany(User::class, 'posts_tagged', 'post_id', 'user_id')->withTimestamps();
    }

    /**
     * Get the parent post (for shared posts).
     */
    public function parentPost()
    {
        return $this->belongsTo(Post::class, 'parent_post_id');
    }

    /**
     * Get child posts (shares of this post).
     */
    public function childPosts()
    {
        return $this->hasMany(Post::class, 'parent_post_id');
    }
    public function deletePosts($postId)
    {
        $this->where('parent_post_id', $postId)->delete();
        PostMedia::whereIn('post_id', $postId)->delete();
        PostComment::whereIn('post_id', $postId)->delete();
        DB::table('posts_report')
            ->whereIn('post_id', $postId)
            ->delete();
        PostLike::whereIn('post_id', $postId)->delete();
        PostTag::whereIn('post_id', $postId)->delete();
        $this->whereIn('id', $postId)->delete();
        // $polls = Poll::whereIn('post_id', $postId)->first();
        // if ($polls) {
        //     foreach ($polls as $poll) {
        //         PollOption::where('poll_id', $poll->id)->delete();
        //         PollVote::where('poll_id', $poll->id)->delete();
        //     }
        // }
        Notification::whereIn('post_id', $postId)->delete();
    }
}
