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

class Admin extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        // Load necessary models, helpers, libraries here
        $this->load->model('User_model');
        $this->load->model('Video_model');
        $this->load->model('Category_model');
        $this->load->model('Tag_model');
        $this->load->model('Banner_model');
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        // TODO: Add authentication check for admin role
    }

    public function index()
    {
        // Admin dashboard with user data table
        $this->load->library('pagination');
        
        // Get search parameter
        $search = $this->input->get('search');
        
        // Pagination config for users
        $config = array();
        $config['base_url'] = site_url('admin/index');
        $config['total_rows'] = $this->User_model->count_users_with_search($search);
        $config['per_page'] = 10;
        $config['uri_segment'] = 3;
        $config['use_page_numbers'] = TRUE;
        
        // Add query string for search
        $search_param = $search ?? '';
        $config['suffix'] = '?search=' . urlencode($search_param);
        $config['first_url'] = site_url('admin/index') . '?search=' . urlencode($search_param);
        
        $this->pagination->initialize($config);
        
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $offset = $page * $config['per_page'];
        
        // Get users with login history
        $data['users'] = $this->User_model->get_users_with_login_history($config['per_page'], $offset, $search);
        $data['pagination_links'] = $this->pagination->create_links();
        
        $this->load->view('admin/dashboard', $data);
    }

    public function upload_video()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('description', 'Description', 'required');
        $this->form_validation->set_rules('status', 'Status', 'required');
        $this->form_validation->set_rules('visibility', 'Visibility', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('admin/upload_video');
        } else {
            $config['upload_path'] = './uploads/videos/';
            $config['allowed_types'] = 'mp4|avi|mov|wmv';
            $config['max_size'] = 1002400; // 100MB
            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('video_file')) {
                $data['error'] = $this->upload->display_errors();
                $this->load->view('admin/upload_video', $data);
            } else {
                $upload_data = $this->upload->data();

                $video_data = array(
                    'user_id' => $this->session->userdata('user_id') ?? 1,
                    'title' => $this->input->post('title'),
                    'description' => $this->input->post('description'),
                    'filename' => $upload_data['file_name'],
                    'thumbnail' => $thumbnail_filename ?? null,
                    'status' => $this->input->post('status') ?? 'published',
                    'visibility' => $this->input->post('visibility') ?? 'public',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                );

                $this->load->model('Video_model');
                $this->Video_model->insert_video($video_data);

                $this->session->set_flashdata('success', 'Video uploaded successfully.');
                redirect('admin/upload_video');
            }
        }
    }

    public function users()
    {
        $this->load->model('User_model');
        $data['users'] = $this->User_model->get_users(100, 0);
        $this->load->view('admin/users', $data);
    }

    public function user_ban($id)
    {
        $this->load->model('User_model');
        $this->load->helper('form');
        $this->load->library('form_validation');

        // Ban durations in days
        $ban_durations = [
            '7' => '7 Days',
            '30' => '1 Month',
            '90' => '3 Months',
            'permanent' => 'Permanent'
        ];

        if ($this->input->method() === 'post') {
            $this->form_validation->set_rules('ban_duration', 'Ban Duration', 'required');

            if ($this->form_validation->run() === FALSE) {
                $data['ban_durations'] = $ban_durations;
                $data['user_id'] = $id;
                $this->load->view('admin/user_ban', $data);
            } else {
                $ban_duration = $this->input->post('ban_duration');
                $ban_expires_at = null;

                if ($ban_duration !== 'permanent') {
                    $ban_expires_at = date('Y-m-d H:i:s', strtotime("+$ban_duration days"));
                }

                $update_data = [
                    'is_banned' => true,
                    'ban_expires_at' => $ban_expires_at
                ];

                $this->User_model->update_user($id, $update_data);

                $this->session->set_flashdata('success', 'User has been banned successfully.');
                redirect('admin/users');
            }
        } else {
            $data['ban_durations'] = $ban_durations;
            $data['user_id'] = $id;
            $this->load->view('admin/user_ban', $data);
        }
    }

    public function tags()
    {
        $this->load->model('Tag_model');
        $data['tags'] = $this->Tag_model->get_all();
        $this->load->view('admin/tags', $data);
    }

    // Video CRUD

    public function videos()
    {
        $this->load->model('Video_model');
        $data['videos'] = $this->Video_model->get_videos(100, 0);
        $this->load->view('admin/videos', $data);
    }

    public function video_create()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $categories = $this->Category_model->get_all();
        $tags = $this->Tag_model->get_all();

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('description', 'Description', 'required');
        $this->form_validation->set_rules('drive_link', 'Google Drive Link', 'required|callback_validate_drive_link');
        $this->form_validation->set_message('validate_drive_link', 'Please provide a valid Google Drive share link. Make sure the file is shared with "Anyone with the link can view".');
        $this->form_validation->set_rules('status', 'Status', 'required');
        $this->form_validation->set_rules('visibility', 'Visibility', 'required');

        if ($this->form_validation->run() === FALSE) {
            $data['categories'] = $categories;
            $data['tags'] = $tags;
            $this->load->view('admin/video_form_drive', $data);
        } else {
            // Process Google Drive link
            $drive_link = $this->input->post('drive_link');
            $direct_link = $this->convert_drive_link_to_direct($drive_link);

            // Upload thumbnail (optional)
            $thumbnail_filename = null;
            if (!empty($_FILES['thumbnail']['name'])) {
                $thumb_upload_path = FCPATH . 'uploads/thumbnails/';
                if (!is_dir($thumb_upload_path)) {
                    mkdir($thumb_upload_path, 0777, true);
                }

                $thumb_config['upload_path'] = $thumb_upload_path;
                $thumb_config['allowed_types'] = 'jpg|jpeg|png|gif';
                $thumb_config['max_size'] = 2048; // 2MB
                $thumb_config['overwrite'] = FALSE;
                $thumb_config['remove_spaces'] = TRUE;
                $thumb_config['detect_mime'] = TRUE;
                $thumb_config['max_filename'] = 255;
                $thumb_config['encrypt_name'] = TRUE;

                $this->load->library('upload', $thumb_config);

                if ($this->upload->do_upload('thumbnail')) {
                    $thumb_data = $this->upload->data();
                    $thumbnail_filename = $thumb_data['file_name'];
                } else {
                    $data['error'] = $this->upload->display_errors();
                    $data['categories'] = $categories;
                    $data['tags'] = $tags;
                    $this->load->view('admin/video_form_drive', $data);
                    return;
                }
            }

            // Process categories
            $category_ids = $this->input->post('categories') ?: [];

            // Process tags
            $tags_input = $this->input->post('tags') ?: '';
            $tag_names = array_filter(array_map('trim', explode(',', $tags_input)));
            $tag_ids = [];
            foreach ($tag_names as $tag_name) {
                $tag = $this->Tag_model->get_by_name($tag_name);
                if (!$tag) {
                    $this->Tag_model->insert(['name' => $tag_name, 'slug' => url_title($tag_name, '-', TRUE)]);
                    $tag = $this->Tag_model->get_by_name($tag_name);
                }
                if ($tag) {
                    $tag_ids[] = $tag->id;
                }
            }

            // Save video data
            $video_data = array(
                'user_id' => 1, // TODO: Replace with logged in admin user id
                'title' => $this->input->post('title'),
                'description' => $this->input->post('description'),
                'drive_link' => $direct_link,
                'thumbnail' => $thumbnail_filename,
                'status' => $this->input->post('status'),
                'visibility' => $this->input->post('visibility'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            );

            $this->Video_model->insert_video($video_data, $category_ids, $tag_ids);

            $this->session->set_flashdata('success', 'Video created successfully with Google Drive link.');
            redirect('admin/videos');
        }
    }

    /**
     * Validate Google Drive link format
     */
    public function validate_drive_link($link) {
        // Check if it's a valid Google Drive share link format
        if (preg_match('/^https:\/\/drive\.google\.com\/file\/d\/([a-zA-Z0-9-_]+)\/view.*/', $link, $matches)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('validate_drive_link', 'Please provide a valid Google Drive share link.');
            return FALSE;
        }
    }

    /**
     * Convert Google Drive share link to direct download link
     */
    private function convert_drive_link_to_direct($link) {
        // Extract file ID from Google Drive share link
        if (preg_match('/\/file\/d\/([a-zA-Z0-9-_]+)/', $link, $matches)) {
            $file_id = $matches[1];
            return 'https://drive.google.com/uc?export=download&id=' . $file_id;
        }
        return $link;
    }

    public function video_edit($id)
    {
        $this->load->model('Video_model');
        $this->load->model('Category_model');
        $this->load->model('Tag_model');

        $video = $this->Video_model->get_video($id);
        if (!$video) {
            show_404();
        }

        $categories = $this->Category_model->get_all();
        $tags = $this->Tag_model->get_all();

        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('description', 'Description', 'required');
        $this->form_validation->set_rules('status', 'Status', 'required');
        $this->form_validation->set_rules('visibility', 'Visibility', 'required');

        if ($this->form_validation->run() === FALSE) {
            $data['video'] = $video;
            $data['categories'] = $categories;
            $data['tags'] = $tags;
            $this->load->view('admin/video_form', $data);
        } else {
            $category_ids = $this->input->post('categories') ?: [];

            $tags_input = $this->input->post('tags') ?: '';
            $tag_names = array_filter(array_map('trim', explode(',', $tags_input)));
            $tag_ids = [];
            foreach ($tag_names as $tag_name) {
                $tag = $this->Tag_model->get_by_name($tag_name);
                if (!$tag) {
                    $this->Tag_model->insert(['name' => $tag_name, 'slug' => url_title($tag_name, '-', TRUE)]);
                    $tag = $this->Tag_model->get_by_name($tag_name);
                }
                if ($tag) {
                    $tag_ids[] = $tag->id;
                }
            }

            $video_data = array(
                'title' => $this->input->post('title'),
                'description' => $this->input->post('description'),
                'status' => $this->input->post('status'),
                'visibility' => $this->input->post('visibility'),
                'updated_at' => date('Y-m-d H:i:s')
            );

            $this->Video_model->update_video($id, $video_data, $category_ids, $tag_ids);

            $this->session->set_flashdata('success', 'Video updated successfully.');
            redirect('admin/videos');
        }
    }

    public function video_delete($id)
    {
        $this->load->model('Video_model');
        $this->Video_model->delete_video($id);
        $this->session->set_flashdata('success', 'Video deleted successfully.');
        redirect('admin/videos');
    }

    // Category CRUD

    public function categories()
    {
        $this->load->model('Category_model');
        $data['categories'] = $this->Category_model->get_all();
        $this->load->view('admin/categories', $data);
    }

    public function category_create()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('name', 'Name', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('admin/category_form');
        } else {
            $category_data = array(
                'name' => $this->input->post('name'),
                'parent_id' => $this->input->post('parent_id') ?: NULL,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            );

            $this->Category_model->insert($category_data);

            $this->session->set_flashdata('success', 'Category created successfully.');
            redirect('admin/categories');
        }
    }

    public function category_edit($id)
    {
        $this->load->model('Category_model');
        $category = $this->Category_model->get($id);
        if (!$category) {
            show_404();
        }

        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('name', 'Name', 'required');

        if ($this->form_validation->run() === FALSE) {
            $data['category'] = $category;
            $this->load->view('admin/category_form', $data);
        } else {
            $category_data = array(
                'name' => $this->input->post('name'),
                'parent_id' => $this->input->post('parent_id') ?: NULL,
                'updated_at' => date('Y-m-d H:i:s')
            );

            $this->Category_model->update($id, $category_data);

            $this->session->set_flashdata('success', 'Category updated successfully.');
            redirect('admin/categories');
        }
    }

    public function category_delete($id)
    {
        $this->load->model('Category_model');
        $this->Category_model->delete($id);
        $this->session->set_flashdata('success', 'Category deleted successfully.');
        redirect('admin/categories');
    }

    /**
     * Get video comments for AJAX request
     */
    public function get_video_comments($video_id)
    {
        $this->load->model('Video_model');
        $comments = $this->Video_model->get_video_comments($video_id);
        
        // Format comments for JSON response
        $formatted_comments = [];
        foreach ($comments as $comment) {
            $formatted_comments[] = [
                'username' => $comment->username,
                'content' => $comment->content,
                'created_at' => date('M j, Y H:i', strtotime($comment->created_at))
            ];
        }
        
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'comments' => $formatted_comments
            ]));
    }

    /**
     * Get user login history for AJAX request
     */
    public function get_user_login_history($user_id)
    {
        $this->load->model('User_model');
        $logins = $this->User_model->get_login_history($user_id);
        
        // Format login history for JSON response
        $formatted_logins = [];
        foreach ($logins as $login) {
            $formatted_logins[] = [
                'login_time' => date('M j, Y H:i', strtotime($login->login_time)),
                'ip_address' => $login->ip_address,
                'user_agent' => $login->user_agent,
                'session_id' => $login->session_id
            ];
        }
        
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'success' => true,
                'logins' => $formatted_logins
            ]));
    }

    // TODO: Add methods for video upload, user management, category management, etc.

    /**
     * Delete user by ID
     */
    public function user_delete($id)
    {
        $this->load->model('User_model');
        $deleted = $this->User_model->delete_user($id);
        if ($deleted) {
            $this->session->set_flashdata('success', 'User deleted successfully.');
        } else {
            $this->session->set_flashdata('error', 'Failed to delete user.');
        }
        redirect('admin/users');
    }

    // Banner CRUD

    public function banners()
    {
        $this->load->library('pagination');

        // Update expired banners status before fetching
        $this->Banner_model->update_expired_banners_status();
        
        // Get search parameter
        $search = $this->input->get('search');
        
        // Pagination config for banners
        $config = array();
        $config['base_url'] = site_url('admin/banners');
        $config['total_rows'] = $this->Banner_model->count_banners($search);
        $config['per_page'] = 10;
        $config['uri_segment'] = 3;
        $config['use_page_numbers'] = TRUE;
        
        // Add query string for search
        $search_param = $search ?? '';
        $config['suffix'] = '?search=' . urlencode($search_param);
        $config['first_url'] = site_url('admin/banners') . '?search=' . urlencode($search_param);
        
        $this->pagination->initialize($config);
        
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $offset = $page * $config['per_page'];
        
        $data['banners'] = $this->Banner_model->get_all_banners_with_clicks($config['per_page'], $offset, $search);
        $data['pagination_links'] = $this->pagination->create_links();
        
        $this->load->view('admin/banners', $data);
    }

    public function banner_create()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('link_url', 'Link URL', 'valid_url');
        $this->form_validation->set_rules('status', 'Status', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('admin/banner_form');
        } else {
            // Create upload directory if it doesn't exist
            $banner_upload_path = FCPATH . 'uploads/banners/';
            if (!is_dir($banner_upload_path)) {
                mkdir($banner_upload_path, 0777, true);
            }

            // Configure upload
            $config['upload_path'] = $banner_upload_path;
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['max_size'] = 2048; // 2MB
            // Removed max_width and max_height to handle manually
            $config['overwrite'] = FALSE;
            $config['remove_spaces'] = TRUE;
            $config['encrypt_name'] = TRUE;

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('banner_image')) {
                $data['error'] = $this->upload->display_errors();
                $this->load->view('admin/banner_form', $data);
                return;
            }

            $upload_data = $this->upload->data();

            // Check image dimensions manually
            $image_path = $banner_upload_path . $upload_data['file_name'];
            list($width, $height) = getimagesize($image_path);
            // Removed dimension check to allow any size banner upload
            /*
            if ($width != 728 || $height != 90) {
                // Delete uploaded file
                unlink($image_path);
                $data['error'] = 'The image you are attempting to upload does not meet the required dimensions of 728x90 pixels.';
                $this->load->view('admin/banner_form', $data);
                return;
            }
            */

            $banner_data = array(
                'title' => $this->input->post('title'),
                'image_path' => $upload_data['file_name'],
                'link_url' => $this->input->post('link_url') ?: null,
                'status' => $this->input->post('status'),
                'sort_order' => $this->input->post('sort_order') ?: 0,
                'expires_at' => $this->input->post('expires_at') ?: null
            );

            $this->Banner_model->insert_banner($banner_data);

            $this->session->set_flashdata('success', 'Banner created successfully.');
            redirect('admin/banners');
        }
    }

    public function banner_edit($id)
    {
        $banner = $this->Banner_model->get_banner($id);
        if (!$banner) {
            show_404();
        }

        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('link_url', 'Link URL', 'valid_url');
        $this->form_validation->set_rules('status', 'Status', 'required');

        if ($this->form_validation->run() === FALSE) {
            $data['banner'] = $banner;
            $this->load->view('admin/banner_form', $data);
        } else {
            $banner_data = array(
                'title' => $this->input->post('title'),
                'link_url' => $this->input->post('link_url') ?: null,
                'status' => $this->input->post('status'),
                'sort_order' => $this->input->post('sort_order') ?: 0,
                'expires_at' => $this->input->post('expires_at') ?: null
            );

            // Handle new image upload if provided
            if (!empty($_FILES['banner_image']['name'])) {
                $banner_upload_path = FCPATH . 'uploads/banners/';
                if (!is_dir($banner_upload_path)) {
                    mkdir($banner_upload_path, 0777, true);
                }

                $config['upload_path'] = $banner_upload_path;
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                $config['max_size'] = 2048;
                // Removed max_width and max_height to allow any size banner upload
                // $config['max_width'] = 728;
                // $config['max_height'] = 90;
                $config['overwrite'] = FALSE;
                $config['remove_spaces'] = TRUE;
                $config['encrypt_name'] = TRUE;

                $this->upload->initialize($config);

                if ($this->upload->do_upload('banner_image')) {
                    // Delete old image
                    $old_image = FCPATH . 'uploads/banners/' . $banner->image_path;
                    if (file_exists($old_image)) {
                        unlink($old_image);
                    }

                    $upload_data = $this->upload->data();
                    $banner_data['image_path'] = $upload_data['file_name'];
                } else {
                    $data['error'] = $this->upload->display_errors();
                    $data['banner'] = $banner;
                    $this->load->view('admin/banner_form', $data);
                    return;
                }
            }

            $this->Banner_model->update_banner($id, $banner_data);

            $this->session->set_flashdata('success', 'Banner updated successfully.');
            redirect('admin/banners');
        }
    }

    public function banner_delete($id)
    {
        $banner = $this->Banner_model->get_banner($id);
        if (!$banner) {
            show_404();
        }

        // Delete image file
        $image_path = FCPATH . 'uploads/banners/' . $banner->image_path;
        if (file_exists($image_path)) {
            unlink($image_path);
        }

        $this->Banner_model->delete_banner($id);
        $this->session->set_flashdata('success', 'Banner deleted successfully.');
        redirect('admin/banners');
    }
}
