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

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

use Google\Cloud\Firestore\FirestoreClient;

class Content extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('content_model');
        $this->load->helper('url');
        $this->load->helper('file');
        $this->load->library('upload');
    }

    public function index()
    {
        $this->content();
    }

    /**
     * Main content page - Display both videos and advertisements
     */
    public function content()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            // Get all prioritized videos
            $data['videos'] = $this->content_model->getall_videos();
            
            // Get all advertisements
            $data['advertisements'] = $this->content_model->getall_advertisements();
            
            // Sort by createdDate descending
            if (!empty($data['videos'])) {
                uasort($data['videos'], function($a, $b) {
                    $aDate = isset($a['createdDate']) ? $a['createdDate'] : 0;
                    $bDate = isset($b['createdDate']) ? $b['createdDate'] : 0;
                    return $bDate - $aDate;
                });
            }
            
            if (!empty($data['advertisements'])) {
                uasort($data['advertisements'], function($a, $b) {
                    $aDate = isset($a['createdDate']) ? $a['createdDate'] : 0;
                    $bDate = isset($b['createdDate']) ? $b['createdDate'] : 0;
                    return $bDate - $aDate;
                });
            }

            $this->global['pageTitle'] = 'StreamAdmin : Content Management';
            $this->loadViews("content/content", $this->global, $data, NULL);
        }
    }

    /**
     * Add Prioritized Video Form
     */
    public function addPrioritizedVideo()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->global['pageTitle'] = 'StreamAdmin : Add Prioritized Video';
            $this->loadViews("content/addVideo", $this->global, NULL, NULL);
        }
    }

    /**
     * Save Prioritized Video
     */
    public function savePrioritizedVideo()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');

            $this->form_validation->set_rules('title', 'Title', 'trim|required|max_length[200]');
            $this->form_validation->set_rules('priority', 'Priority', 'required|numeric');

            if ($this->form_validation->run() == FALSE) {
                $this->addPrioritizedVideo();
            } else {
                // Handle Video File Upload
                $videoUrl = '';
                if (!empty($_FILES['videoFile']['name'])) {
                    $videoUrl = $this->uploadFile('videoFile', 'videos');
                    if ($videoUrl === false) {
                        $this->session->set_flashdata('error', 'Video upload failed');
                        redirect('content/addPrioritizedVideo');
                        return;
                    }
                } else {
                    $this->session->set_flashdata('error', 'Video file is required');
                    redirect('content/addPrioritizedVideo');
                    return;
                }

                // Handle Thumbnail Upload
                $thumbnailUrl = '';
                if (!empty($_FILES['thumbnailFile']['name'])) {
                    $thumbnailUrl = $this->uploadFile('thumbnailFile', 'thumbnails');
                }

                $title = $this->security->xss_clean($this->input->post('title'));
                $description = $this->security->xss_clean($this->input->post('description'));
                $priority = intval($this->input->post('priority'));
                $isActive = $this->input->post('isActive') === '1' ? true : false;

                $currentTime = time() * 1000;
                
                $videoData = array(
                    'title' => $title,
                    'description' => $description,
                    'videoUrl' => $videoUrl,
                    'thumbnailUrl' => $thumbnailUrl,
                    'priority' => $priority,
                    'isActive' => $isActive,
                    'views' => 0,
                    'likes' => 0,
                    'createdDate' => $currentTime,
                    'type' => 'prioritized'
                );

                $result = $this->content_model->add_video($videoData);

                if ($result) {
                    $this->session->set_flashdata('success', 'Prioritized video added successfully');
                } else {
                    $this->session->set_flashdata('error', 'Failed to add video');
                }

                redirect('content/content');
            }
        }
    }

    /**
     * Add Advertisement Form
     */
    public function addAdvertisement()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->global['pageTitle'] = 'StreamAdmin : Add Advertisement';
            $this->loadViews("content/addAdvertisement", $this->global, NULL, NULL);
        }
    }

    /**
     * Save Advertisement
     */
    public function saveAdvertisement()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');

            $this->form_validation->set_rules('title', 'Title', 'trim|required|max_length[200]');
            $this->form_validation->set_rules('adType', 'Advertisement Type', 'required|in_list[banner,popup,video]');
            $this->form_validation->set_rules('startDate', 'Start Date', 'required');
            $this->form_validation->set_rules('endDate', 'End Date', 'required');

            if ($this->form_validation->run() == FALSE) {
                $this->addAdvertisement();
            } else {
                // Handle Media File Upload
                $mediaUrl = '';
                if (!empty($_FILES['mediaFile']['name'])) {
                    $adType = $this->input->post('adType');
                    $uploadFolder = $adType === 'video' ? 'ads/videos' : 'ads/images';
                    $mediaUrl = $this->uploadFile('mediaFile', $uploadFolder);
                    
                    if ($mediaUrl === false) {
                        $this->session->set_flashdata('error', 'Media file upload failed');
                        redirect('content/addAdvertisement');
                        return;
                    }
                } else {
                    $this->session->set_flashdata('error', 'Media file is required');
                    redirect('content/addAdvertisement');
                    return;
                }

                $title = $this->security->xss_clean($this->input->post('title'));
                $description = $this->security->xss_clean($this->input->post('description'));
                $adType = $this->security->xss_clean($this->input->post('adType'));
                $clickUrl = $this->security->xss_clean($this->input->post('clickUrl'));
                $duration = intval($this->input->post('duration'));
                $startDate = $this->input->post('startDate');
                $endDate = $this->input->post('endDate');
                $isActive = $this->input->post('isActive') === '1' ? true : false;

                // Convert dates to timestamps (milliseconds)
                $startTimestamp = strtotime($startDate) * 1000;
                $endTimestamp = strtotime($endDate . ' 23:59:59') * 1000;
                $currentTime = time() * 1000;
                
                $adData = array(
                    'title' => $title,
                    'description' => $description,
                    'adType' => $adType,
                    'mediaUrl' => $mediaUrl,
                    'clickUrl' => $clickUrl,
                    'duration' => $duration,
                    'startDate' => $startTimestamp,
                    'endDate' => $endTimestamp,
                    'isActive' => $isActive,
                    'impressions' => 0,
                    'clicks' => 0,
                    'createdDate' => $currentTime,
                    'type' => 'advertisement'
                );

                $result = $this->content_model->add_advertisement($adData);

                if ($result) {
                    $this->session->set_flashdata('success', 'Advertisement added successfully');
                } else {
                    $this->session->set_flashdata('error', 'Failed to add advertisement');
                }

                redirect('content/content');
            }
        }
    }

    /**
     * Handle file upload
     */
    private function uploadFile($fieldName, $folder = 'uploads')
    {
        $config['upload_path'] = './uploads/' . $folder . '/';
        
        // Create directory if it doesn't exist
        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }
        
        $config['allowed_types'] = 'gif|jpg|jpeg|png|mp4|mov|avi|mkv|webm';
        $config['max_size'] = 102400; // 100MB
        $config['encrypt_name'] = TRUE;
        
        $this->upload->initialize($config);
        
        if ($this->upload->do_upload($fieldName)) {
            $uploadData = $this->upload->data();
            return base_url('uploads/' . $folder . '/' . $uploadData['file_name']);
        } else {
            log_message('error', 'Upload error: ' . $this->upload->display_errors());
            return false;
        }
    }

    /**
     * View Video Details
     */
    public function viewVideo($videoId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($videoId == null) {
                redirect('content/content');
            }

            $data['videoInfo'] = $this->content_model->get_video($videoId);
            $data['videoId'] = $videoId;

            $this->global['pageTitle'] = 'StreamAdmin : Video Details';
            $this->loadViews("content/viewVideo", $this->global, $data, NULL);
        }
    }

    /**
     * View Advertisement Details
     */
    public function viewAdvertisement($adId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($adId == null) {
                redirect('content/content');
            }

            $data['adInfo'] = $this->content_model->get_advertisement($adId);
            $data['adId'] = $adId;

            $this->global['pageTitle'] = 'StreamAdmin : Advertisement Details';
            $this->loadViews("content/viewAdvertisement", $this->global, $data, NULL);
        }
    }

    /**
     * Edit Video
     */
    public function editVideo($videoId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($videoId == null) {
                redirect('content/content');
            }

            $data['videoInfo'] = $this->content_model->get_video($videoId);
            $data['videoId'] = $videoId;

            $this->global['pageTitle'] = 'StreamAdmin : Edit Video';
            $this->loadViews("content/editVideo", $this->global, $data, NULL);
        }
    }

    /**
     * Update Video
     */
    public function updateVideo()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');

            $videoId = $this->input->post('videoId');

            $this->form_validation->set_rules('title', 'Title', 'trim|required|max_length[200]');
            $this->form_validation->set_rules('priority', 'Priority', 'required|numeric');

            if ($this->form_validation->run() == FALSE) {
                $this->editVideo($videoId);
            } else {
                // Get existing video data
                $existingVideo = $this->content_model->get_video($videoId);
                
                $title = $this->security->xss_clean($this->input->post('title'));
                $description = $this->security->xss_clean($this->input->post('description'));
                $priority = intval($this->input->post('priority'));
                $isActive = $this->input->post('isActive') === 'true' ? true : false;
                
                // Keep existing URLs
                $videoUrl = isset($existingVideo['videoUrl']) ? $existingVideo['videoUrl'] : '';
                $thumbnailUrl = isset($existingVideo['thumbnailUrl']) ? $existingVideo['thumbnailUrl'] : '';
                
                // Upload new video if provided
                if (!empty($_FILES['videoFile']['name'])) {
                    $newVideoUrl = $this->uploadFile('videoFile', 'videos');
                    if ($newVideoUrl !== false) {
                        $videoUrl = $newVideoUrl;
                    }
                }
                
                // Upload new thumbnail if provided
                if (!empty($_FILES['thumbnailFile']['name'])) {
                    $newThumbnailUrl = $this->uploadFile('thumbnailFile', 'thumbnails');
                    if ($newThumbnailUrl !== false) {
                        $thumbnailUrl = $newThumbnailUrl;
                    }
                }

                $videoData = array(
                    'title' => $title,
                    'description' => $description,
                    'videoUrl' => $videoUrl,
                    'thumbnailUrl' => $thumbnailUrl,
                    'priority' => $priority,
                    'isActive' => $isActive
                );

                $result = $this->content_model->update_video($videoId, $videoData);

                if ($result) {
                    $this->session->set_flashdata('success', 'Video updated successfully');
                } else {
                    $this->session->set_flashdata('error', 'Video update failed');
                }

                redirect('content/content');
            }
        }
    }

    /**
     * Edit Advertisement
     */
    public function editAdvertisement($adId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($adId == null) {
                redirect('content/content');
            }

            $data['adInfo'] = $this->content_model->get_advertisement($adId);
            $data['adId'] = $adId;

            $this->global['pageTitle'] = 'StreamAdmin : Edit Advertisement';
            $this->loadViews("content/editAdvertisement", $this->global, $data, NULL);
        }
    }

    /**
     * Update Advertisement
     */
    public function updateAdvertisement()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');

            $adId = $this->input->post('adId');

            $this->form_validation->set_rules('title', 'Title', 'trim|required|max_length[200]');
            $this->form_validation->set_rules('adType', 'Advertisement Type', 'required|in_list[banner,popup,video]');
            $this->form_validation->set_rules('startDate', 'Start Date', 'required');
            $this->form_validation->set_rules('endDate', 'End Date', 'required');

            if ($this->form_validation->run() == FALSE) {
                $this->editAdvertisement($adId);
            } else {
                // Get existing ad data
                $existingAd = $this->content_model->get_advertisement($adId);
                
                $title = $this->security->xss_clean($this->input->post('title'));
                $description = $this->security->xss_clean($this->input->post('description'));
                $adType = $this->security->xss_clean($this->input->post('adType'));
                $clickUrl = $this->security->xss_clean($this->input->post('clickUrl'));
                $duration = intval($this->input->post('duration'));
                $startDate = $this->input->post('startDate');
                $endDate = $this->input->post('endDate');
                $isActive = $this->input->post('isActive') === 'true' ? true : false;
                
                // Keep existing media URL
                $mediaUrl = isset($existingAd['mediaUrl']) ? $existingAd['mediaUrl'] : '';
                
                // Upload new media if provided
                if (!empty($_FILES['mediaFile']['name'])) {
                    $uploadFolder = $adType === 'video' ? 'ads/videos' : 'ads/images';
                    $newMediaUrl = $this->uploadFile('mediaFile', $uploadFolder);
                    if ($newMediaUrl !== false) {
                        $mediaUrl = $newMediaUrl;
                    }
                }

                // Convert dates to timestamps
                $startTimestamp = strtotime($startDate) * 1000;
                $endTimestamp = strtotime($endDate . ' 23:59:59') * 1000;

                $adData = array(
                    'title' => $title,
                    'description' => $description,
                    'adType' => $adType,
                    'mediaUrl' => $mediaUrl,
                    'clickUrl' => $clickUrl,
                    'duration' => $duration,
                    'startDate' => $startTimestamp,
                    'endDate' => $endTimestamp,
                    'isActive' => $isActive
                );

                $result = $this->content_model->update_advertisement($adId, $adData);

                if ($result) {
                    $this->session->set_flashdata('success', 'Advertisement updated successfully');
                } else {
                    $this->session->set_flashdata('error', 'Advertisement update failed');
                }

                redirect('content/content');
            }
        }
    }

    /**
     * Delete Video
     */
    public function deleteVideo()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $videoId = $this->input->post('videoId');

            if (empty($videoId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Video ID is required')));
                return;
            }

            $result = $this->content_model->delete_video($videoId);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Video deleted successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to delete video')));
            }
        }
    }

    /**
     * Delete Advertisement
     */
    public function deleteAdvertisement()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $adId = $this->input->post('adId');

            if (empty($adId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Advertisement ID is required')));
                return;
            }

            $result = $this->content_model->delete_advertisement($adId);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Advertisement deleted successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to delete advertisement')));
            }
        }
    }

    /**
     * Toggle Video Status
     */
    public function toggleVideoStatus()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $videoId = $this->input->post('videoId');
            $currentStatus = $this->input->post('currentStatus') === 'true' ? true : false;

            if (empty($videoId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Invalid data')));
                return;
            }

            $videoData = array(
                'isActive' => !$currentStatus
            );

            $result = $this->content_model->update_video($videoId, $videoData);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Video status updated successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to update status')));
            }
        }
    }

    /**
     * Toggle Advertisement Status
     */
    public function toggleAdStatus()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $adId = $this->input->post('adId');
            $currentStatus = $this->input->post('currentStatus') === 'true' ? true : false;

            if (empty($adId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Invalid data')));
                return;
            }

            $adData = array(
                'isActive' => !$currentStatus
            );

            $result = $this->content_model->update_advertisement($adId, $adData);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Advertisement status updated successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to update status')));
            }
        }
    }
}

