<?php 

defined('BASEPATH') or exit ('Direct script access not allowed');

require_once APPPATH . "core/My_Admin.php";

class Likes extends My_Admin{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('LikesDataTable');
    }

    public $table = 'admin_videos';

    // * manage admin videos
    public function index(){

        $this->load->view('admin/includes/header');
        $this->load->view('admin/likes/view');
        $this->load->view('admin/includes/footer');

    }


    // * create new video 
    public function create() {
        if ($this->input->post()) {
            $data = $_POST;
    
            // Calculate buffer and initialize counts
            $buffer_percentage = 10; 
            $buffered_count = ceil($data['target'] + ($data['target'] * $buffer_percentage / 100));
            $remaining_count = $buffered_count; 
    
            $request_data = array(
                'link' => $data['link'],
                'target' => $data['target'],
                // 'type' => $data['type'], // Add type to request data
                'type' => 'like', 
                'buffered_count' => $buffered_count,
                'remaining_count' => $remaining_count,
                'completed_count' => 0,
                'created_at' => date('Y-m-d H:i:s'),
            );

            if (!empty($_FILES['thumbnail']['name'])) {
                $request_data['thumbnail'] = upload_media($_FILES['thumbnail']);
            }
    
            $this->cm->save_data($request_data, 'admin_videos');
            $this->session->set_flashdata('success', 'New video added.');
            redirect(site_url('/admin/likes'));
        }
    
        $this->load->view('admin/includes/header');
        $this->load->view('admin/likes/create');
        $this->load->view('admin/includes/footer');
    }


    // * datatable
    public function datatable(){
        $datas = $this->LikesDataTable->get_data_table(['remove' => '0']);
        // print_r($this->db->last_query());
        // exit;

        $final = [];
        $sno = $_POST['start'];
        foreach ($datas as $data) {
            $row = [];
            $row[] = ++$sno;
            $row[] = $data['link'];
            $row[] = $data['target'];
            $row[] = $data['buffered_count'];
            $row[] = $data['remaining_count'];
            $row[] = $data['completed_count'];
            $row[] = $data['created_at'];
            $row[] = "<div class='btn-group' role='group'>
                <a href='" . site_url('admin/likes/edit/' . $data['id']) . "' class='btn btn-warning' title='Edit'><i class='fa-solid fa-edit'></i></a>
                <button type='button' class='btn btn-danger delete-video' data-id='" . $data['id'] . "' title='Delete'><i class='fa-solid fa-trash'></i></button>
            </div>";

            $final[] = $row;
        }

        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->LikesDataTable->count_all_data(['remove' => '0']),
            "recordsFiltered" => $this->LikesDataTable->count_filtered_data(['remove' => '0']),
            "data" => $final,
        );

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

  
    }


    public function delete_video() {
        $id = $this->input->post('id');
        if (!$id) {
            echo json_encode(['status' => false, 'message' => 'Invalid Request']);
            return;
        }

        $success = $this->LikesDataTable->delete_video($id);

        if ($success) {
            echo json_encode(['status' => true, 'message' => 'Video deleted successfully']);
        } else {
            echo json_encode(['status' => false, 'message' => 'Error deleting video']);
        }
    }


    // * edit video
    public function edit($id) {
        $data['video'] = $this->LikesDataTable->get_video_by_id($id);
    
        if (!$data['video']) {
            show_404();
        }
    
        if ($this->input->post()) {
            $postData = $_POST;
    
            // Recalculate buffer count
            $buffer_percentage = 10; 
            $buffered_count = ceil($postData['target'] + ($postData['target'] * $buffer_percentage / 100));
            $remaining_count = $buffered_count - $data['video']['completed_count'];
    
            // Prepare update data
            $updateData = [
                'link' => $postData['link'],
                'target' => $postData['target'],
                // 'type' => $postData['type'], // Add type to update data
                'type' => 'like',
                'buffered_count' => $buffered_count,
                'remaining_count' => $remaining_count
            ];

            // Check if a new thumbnail file is uploaded
            if (!empty($_FILES['thumbnail']['name'])) {
                $updateData['thumbnail'] = upload_media($_FILES['thumbnail']);
            }
    
            // Update video record
            $this->LikesDataTable->update_video($id, $updateData);
            $this->session->set_flashdata('success', 'Video updated successfully.');
            redirect(site_url('/admin/likes'));
        }
    
        $this->load->view('admin/includes/header');
        $this->load->view('admin/likes/edit', $data);
        $this->load->view('admin/includes/footer');
    }


}