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

class Video_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    /**
     * Add a like for a video by a user
     */
    public function add_like($video_id, $user_id) {
        // Check if already liked
        $exists = $this->db->where('video_id', $video_id)
                           ->where('user_id', $user_id)
                           ->get('video_likes')
                           ->row();
        if ($exists) {
            return false; // Already liked
        }
        $this->db->insert('video_likes', [
            'video_id' => $video_id,
            'user_id' => $user_id,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        // Increment likes count in videos table
        $this->db->set('likes', 'likes+1', FALSE)
                 ->where('id', $video_id)
                 ->update('videos');
        return true;
    }

    /**
     * Remove a like for a video by a user
     */
    public function remove_like($video_id, $user_id) {
        $deleted = $this->db->where('video_id', $video_id)
                            ->where('user_id', $user_id)
                            ->delete('video_likes');
        if ($deleted) {
            // Decrement likes count in videos table
            $this->db->set('likes', 'GREATEST(likes-1, 0)', FALSE)
                     ->where('id', $video_id)
                     ->update('videos');
            return true;
        }
        return false;
    }

    /**
     * Check if a user liked a video
     */
    public function user_liked_video($video_id, $user_id) {
        $like = $this->db->where('video_id', $video_id)
                         ->where('user_id', $user_id)
                         ->get('video_likes')
                         ->row();
        return $like ? true : false;
    }

    /**
     * Get total likes count for a video
     */
    public function get_likes_count($video_id) {
        $this->db->select('likes');
        $this->db->where('id', $video_id);
        $video = $this->db->get('videos')->row();
        return $video ? (int)$video->likes : 0;
    }

    /**
     * Get published videos with categories and tags
     */
    public function get_published_videos_with_categories_tags($limit = 10, $offset = 0) {
        $this->db->where('status', 'published');
        $this->db->order_by('created_at', 'DESC');
        $videos = $this->db->get('videos', $limit, $offset)->result();
        foreach ($videos as $video) {
            $video->categories = $this->get_video_categories($video->id);
            $video->tags = $this->get_video_tags($video->id);
        }
        return $videos;
    }

    /**
     * Insert new video record with categories and tags
     */
    public function insert_video($data, $category_ids = [], $tag_ids = []) {
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->db->insert('videos', $data);
        $video_id = $this->db->insert_id();

        // Insert categories
        if (!empty($category_ids)) {
            $cat_data = [];
            foreach ($category_ids as $cat_id) {
                $cat_data[] = ['video_id' => $video_id, 'category_id' => $cat_id];
            }
            $this->db->insert_batch('video_categories', $cat_data);
        }

        // Insert tags
        if (!empty($tag_ids)) {
            $tag_data = [];
            foreach ($tag_ids as $tag_id) {
                $tag_data[] = ['video_id' => $video_id, 'tag_id' => $tag_id];
            }
            $this->db->insert_batch('video_tags', $tag_data);
        }

        return $video_id;
    }

    /**
     * Update video record with categories and tags
     */
    public function update_video($id, $data, $category_ids = [], $tag_ids = []) {
        $data['updated_at'] = date('Y-m-d H:i:s');
        $this->db->where('id', $id)->update('videos', $data);

        // Update categories
        $this->db->where('video_id', $id)->delete('video_categories');
        if (!empty($category_ids)) {
            $cat_data = [];
            foreach ($category_ids as $cat_id) {
                $cat_data[] = ['video_id' => $id, 'category_id' => $cat_id];
            }
            $this->db->insert_batch('video_categories', $cat_data);
        }

        // Update tags
        $this->db->where('video_id', $id)->delete('video_tags');
        if (!empty($tag_ids)) {
            $tag_data = [];
            foreach ($tag_ids as $tag_id) {
                $tag_data[] = ['video_id' => $id, 'tag_id' => $tag_id];
            }
            $this->db->insert_batch('video_tags', $tag_data);
        }

        return $this->db->affected_rows() > 0;
    }

    /**
     * Get video by ID with categories and tags
     */
    public function get_video($id) {
        $video = $this->db->where('id', $id)->get('videos')->row();
        if ($video) {
            $video->categories = $this->get_video_categories($id);
            $video->tags = $this->get_video_tags($id);
        }
        return $video;
    }

    /**
     * Get video by ID with categories and tags (alias)
     */
    public function get_video_by_id($id) {
        return $this->get_video($id);
    }

    /**
     * Get related videos by category excluding current video
     */
    public function get_related_videos($category_id, $exclude_id, $limit = 12) {
        $this->db->select('v.*');
        $this->db->from('videos v');
        $this->db->join('video_categories vc', 'vc.video_id = v.id');
        $this->db->where('v.status', 'published');
        $this->db->where('vc.category_id', $category_id);
        $this->db->where('v.id !=', $exclude_id);
        $this->db->order_by('v.created_at', 'DESC');
        $this->db->limit($limit);
        $videos = $this->db->get()->result();
        foreach ($videos as $video) {
            $video->categories = $this->get_video_categories($video->id);
            $video->tags = $this->get_video_tags($video->id);
        }
        return $videos;
    }

    /**
     * Get related videos excluding current video without category filter
     */
    public function get_related_videos_without_category($exclude_id, $limit = 12) {
        $this->db->select('*');
        $this->db->from('videos');
        $this->db->where('status', 'published');
        $this->db->where('id !=', $exclude_id);
        $this->db->order_by('created_at', 'DESC');
        $this->db->limit($limit);
        $videos = $this->db->get()->result();
        foreach ($videos as $video) {
            $video->categories = $this->get_video_categories($video->id);
            $video->tags = $this->get_video_tags($video->id);
        }
        return $videos;
    }

    /**
     * Get all videos with pagination, including categories and tags
     */
    public function get_videos($limit = 10, $offset = 0) {
        $this->db->where('status', 'published');
        $this->db->order_by('created_at', 'DESC');
        $videos = $this->db->get('videos', $limit, $offset)->result();
        foreach ($videos as $video) {
            $video->categories = $this->get_video_categories($video->id);
            $video->tags = $this->get_video_tags($video->id);
        }
        return $videos;
    }

    /**
     * Get all videos regardless of status with pagination, including categories and tags
     */
    public function get_all_videos($limit = 10, $offset = 0) {
        $this->db->order_by('created_at', 'DESC');
        $videos = $this->db->get('videos', $limit, $offset)->result();
        foreach ($videos as $video) {
            $video->categories = $this->get_video_categories($video->id);
            $video->tags = $this->get_video_tags($video->id);
        }
        return $videos;
    }

    /**
     * Delete video by ID
     */
    public function delete_video($id) {
        $this->db->where('video_id', $id)->delete('video_categories');
        $this->db->where('video_id', $id)->delete('video_tags');
        return $this->db->where('id', $id)->delete('videos');
    }

    /**
     * Get categories for a video
     */
    public function get_video_categories($video_id) {
        $this->db->select('c.*');
        $this->db->from('categories c');
        $this->db->join('video_categories vc', 'vc.category_id = c.id');
        $this->db->where('vc.video_id', $video_id);
        return $this->db->get()->result();
    }

    /**
     * Get tags for a video
     */
    public function get_video_tags($video_id) {
        $this->db->select('t.*');
        $this->db->from('tags t');
        $this->db->join('video_tags vt', 'vt.tag_id = t.id');
        $this->db->where('vt.video_id', $video_id);
        return $this->db->get()->result();
    }

    /**
     * Get video statistics with total views, likes, and comments
     */
    public function get_video_statistics($limit = 10, $offset = 0) {
        $this->db->select('v.id, v.title, v.views, v.likes');
        $this->db->select('(SELECT COUNT(*) FROM comments c WHERE c.video_id = v.id AND c.status = "approved") as total_comments', FALSE);
        $this->db->from('videos v');
        $this->db->where('v.status', 'published');
        $this->db->order_by('v.views', 'DESC');
        $this->db->limit($limit, $offset);
        
        $videos = $this->db->get()->result();
        
        // Get comments for each video
        foreach ($videos as $video) {
            $video->comments = $this->get_video_comments($video->id);
        }
        
        return $videos;
    }

    /**
     * Get videos grouped by category for mobile dashboard
     */
    public function get_videos_grouped_by_category($limit_per_category = 10) {
        $categories = $this->db->where('is_active', TRUE)->get('categories')->result();
        $grouped_videos = [];
        
        foreach ($categories as $category) {
            $this->db->select('v.*');
            $this->db->from('videos v');
            $this->db->join('video_categories vc', 'vc.video_id = v.id');
            $this->db->where('v.status', 'published');
            $this->db->where('vc.category_id', $category->id);
            $this->db->order_by('v.created_at', 'DESC');
            $this->db->limit($limit_per_category);
            
            $videos = $this->db->get()->result();
            
            // Add categories and tags to each video
            foreach ($videos as $video) {
                $video->categories = $this->get_video_categories($video->id);
                $video->tags = $this->get_video_tags($video->id);
            }
            
            if (!empty($videos)) {
                $grouped_videos[] = [
                    'category' => $category,
                    'videos' => $videos
                ];
            }
        }
        
        return $grouped_videos;
    }

    /**
     * Get total count of published videos for pagination
     */
    public function count_published_videos() {
        return $this->db->where('status', 'published')->count_all_results('videos');
    }

    /**
     * Get comments for a specific video
     */
    public function get_video_comments($video_id) {
        $this->db->select('c.*, u.username');
        $this->db->from('comments c');
        $this->db->join('users u', 'u.id = c.user_id');
        $this->db->where('c.video_id', $video_id);
        $this->db->where('c.status', 'approved');
        $this->db->order_by('c.created_at', 'DESC');
        return $this->db->get()->result();
    }
}
