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

class Blog extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct();   
        $this->load->library('session');
        $allowed_methods = ['api_blogs'];
        if (!in_array($this->router->fetch_method(), $allowed_methods) && $this->session->userdata('validated') != true)
        {
            redirect('login');
        }     
        $this->load->helper('url');
        $this->load->model('Blog_Model');
        $this->load->model('Blog_Model','blog');  
    }

    public function api_blogs()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json");

        $query = $this->db
            ->where('status', '1')
            ->where('publish', '1')
            ->order_by('blog_date', 'DESC')
            ->get(TBL_BLOG);

        $data = [];

        foreach ($query->result() as $row) {
            $data[] = [
                "id" => $row->id,
                "blog_title" => $row->blog_title,
                "blog_category" => $row->blog_category,
                "blog_date" => $row->blog_date,
                "blog_image_url" => base_url("../assets/images/gallery/large/" . $row->blog_image),
                "blog_banner_url" => base_url("../assets/images/gallery/large/" . $row->blog_banner),
                "blog_description" => $row->blog_description,
                "blog_tags" => $row->blog_tags
            ];
        }

        echo json_encode([
            "status" => "success",
            "data" => $data
        ]);
        exit;
    }

    public function index() 
    {
        $this->load->helper('url');        
        $data["extra_js"] = array("blog");
        $data['controller'] = base_url('blog');
        $data['page_title'] = "Manage Blog | CMS - Vinayak Webtech +91 90336 22526";
        $data['page_heading'] = "Manage Blog";
        $data['main_content'] = 'blog';
        $this->load->view('main_content', $data); 
    }  

    public function submit()
    {
        date_default_timezone_set('Asia/Calcutta'); 
        $get_id = $this->input->post('id'); 
        
        $this->load->library('upload');
        $blog_image = "";
        $blog_banner = "";
         
        // Handle blog_image upload
        $this->upload->initialize($this->set_upload_options()); 
        if($this->upload->do_upload('file'))
        { 
            $photo_Data = $this->upload->data(); 
            $blog_image = $photo_Data['file_name'];
        }

        // Handle blog_banner upload (if needed separately)
        if(!empty($_FILES['blog_banner']['name']))
        {
            $_FILES['file2']['name'] = $_FILES['blog_banner']['name'];
            $_FILES['file2']['type'] = $_FILES['blog_banner']['type'];
            $_FILES['file2']['tmp_name'] = $_FILES['blog_banner']['tmp_name'];
            $_FILES['file2']['error'] = $_FILES['blog_banner']['error'];
            $_FILES['file2']['size'] = $_FILES['blog_banner']['size'];
            
            $this->upload->initialize($this->set_upload_options()); 
            if($this->upload->do_upload('file2'))
            { 
                $banner_Data = $this->upload->data(); 
                $blog_banner = $banner_Data['file_name'];
            }
        }
        
        $get_old_image = $this->input->post('get_old_image'); 
        $get_old_banner = $this->input->post('get_old_banner'); 
      
        // Handle image path logic
        if(!empty($blog_image) && empty($get_id))
        {
            $image_path = $blog_image;
        } 
        else if(empty($blog_image) && $get_id > 0)
        { 
            $image_path = $get_old_image;
        }
        else if(!empty($blog_image) && $get_id > 0)
        {
            if(!empty($get_old_image) && file_exists(BLOG_PATH."/".$get_old_image))
            {
                unlink(BLOG_PATH."/".$get_old_image);
            }
            $image_path = $blog_image;
        }        
        else
        {
            $image_path = $blog_image;
        }
 
        // Handle banner path logic
        if(!empty($blog_banner) && empty($get_id))
        {
            $banner_path = $blog_banner;
        } 
        else if(empty($blog_banner) && $get_id > 0)
        { 
            $banner_path = $get_old_banner;
        }
        else if(!empty($blog_banner) && $get_id > 0)
        {
            if(!empty($get_old_banner) && file_exists(BLOG_PATH."/".$get_old_banner))
            {
                unlink(BLOG_PATH."/".$get_old_banner);
            }
            $banner_path = $blog_banner;
        }        
        else
        {
            $banner_path = $blog_banner;
        }

        if($get_id > 0)
        { 
            $data = array(
                'blog_title' => $this->input->post('blog_title'),  
                'blog_category' => $this->input->post('blog_category'),
                'blog_date' => $this->input->post('blog_date'),
                'blog_description' => $this->input->post('blog_description'),
                'blog_tags' => $this->input->post('blog_tags'),
                'update_uid' => $this->session->userdata('user_id'),
                'update_date' => date("Y-m-d H:i:s"),  
            );
             
            if(!empty($image_path)) {
                $data['blog_image'] = $image_path;
            }

            if(!empty($banner_path)) {
                $data['blog_banner'] = $banner_path;
            }
            
            $this->blog->update(array('id' => $get_id), $data); 
            $response = array("status" => "ok", "heading" => "Updated", "message" => "Blog Updated Successfully.");
        }
        else
        {
            $data = array(
                'blog_title' => $this->input->post('blog_title'), 
                'blog_category' => $this->input->post('blog_category'),
                'blog_date' => $this->input->post('blog_date'),
                'blog_description' => $this->input->post('blog_description'),
                'blog_tags' => $this->input->post('blog_tags'),
                'blog_image' => $image_path,
                'blog_banner' => $banner_path,
                'add_uid' => $this->session->userdata('user_id'),
                'add_date' => date("Y-m-d H:i:s"),
            );
            $insert = $this->blog->save($data);  

            $response = array("status" => "ok", "heading" => "Added", "message" => "Blog Added Successfully.");
        }
         
        echo json_encode($response);
        die;        
    }

    private function set_upload_options()
    {   
        $config = array();
        $config['upload_path'] = BLOG_PATH; 
        $config['allowed_types'] = 'jpeg|jpg|png';
        $config['max_width'] = 0;
        $config['max_height'] = 0;
        $config['max_size'] = '2048';  
        $config['encrypt_name'] = TRUE; 
        return $config;
    }

    public function list()
    { 
        $list = $this->blog->get_datatables();
        $data = array();
        $no = $_POST['start'] + 1;
        foreach ($list as $blog) {
            $row = array();
            $row[] = $no++; 
            $row[] = $blog->blog_title;
            $row[] = $blog->blog_category;
            $row[] = date("d-m-Y", strtotime($blog->blog_date));
            $row[] = '<div class="blog-desc" title="'.htmlspecialchars(strip_tags($blog->blog_description)).'">'.strip_tags($blog->blog_description).'</div>';
 
            if (!empty($blog->blog_image)) {
                $img_path = BLOG_PATH . '/' . $blog->blog_image;
                if (file_exists($img_path)) {
                    $img_url = base_url('../assets/images/gallery/large/' . $blog->blog_image);
                    $row[] = '<img src="'.$img_url.'" style="height:50px;width:auto;">';
                } else {
                    $row[] = '<span class="text-danger">File Missing</span>';
                }
            } else {
                $row[] = '<span class="text-muted">No Image</span>';
            }

            if (!empty($blog->blog_banner)) {
                $banner_path = BLOG_PATH . '/' . $blog->blog_banner;
                if (file_exists($banner_path)) {
                    $banner_url = base_url('../assets/images/gallery/large/' . $blog->blog_banner);
                    $row[] = '<img src="'.$banner_url.'" style="height:50px;width:auto;">';
                } else {
                    $row[] = '<span class="text-danger">File Missing</span>';
                }
            } else {
                $row[] = '<span class="text-muted">No Banner</span>';
            }

            $row[] = date("d-m-Y g:i A", strtotime($blog->add_date));
            
            if($blog->status == '1')
                $row[] = '<a class="label orange-bg active-btn" href="javascript:void(0)" title="Active" onclick="deactive('."'".$blog->id."'".')"><span class="badge badge-success">Active</span></a>';   
            else
                $row[] = '<a class="label red-bg deactive-btn" href="javascript:void(0)" title="Deactive" onclick="active('."'".$blog->id."'".')"><span class="badge badge-danger">Deactive</span></a>';

            $row[] = '<a type="button" href="javascript:void(0);" onclick="edit_data('."'".$blog->id."'".')" class="edit_btn btn btn-sm btn-icon" title="Edit Record"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="eva eva-edit-2-outline"><g data-name="Layer 2"><g data-name="edit-2"><rect width="24" height="24" opacity="0"></rect><path d="M19 20H5a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2z"></path><path d="M5 18h.09l4.17-.38a2 2 0 0 0 1.21-.57l9-9a1.92 1.92 0 0 0-.07-2.71L16.66 2.6A2 2 0 0 0 14 2.53l-9 9a2 2 0 0 0-.57 1.21L4 16.91a1 1 0 0 0 .29.8A1 1 0 0 0 5 18zM15.27 4L18 6.73l-2 1.95L13.32 6zm-8.9 8.91L12 7.32l2.7 2.7-5.6 5.6-3 .28z"></path></g></g></svg></a>
                <a type="button" class="delete_btn btn btn-sm btn-icon" href="javascript:" title="Delete Record" data-id="'.$blog->id.'"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="eva eva-trash-2-outline"><g data-name="Layer 2"><g data-name="trash-2"><rect width="24" height="24" opacity="0"></rect><path d="M21 6h-5V4.33A2.42 2.42 0 0 0 13.5 2h-3A2.42 2.42 0 0 0 8 4.33V6H3a1 1 0 0 0 0 2h1v11a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V8h1a1 1 0 0 0 0-2zM10 4.33c0-.16.21-.33.5-.33h3c.29 0 .5.17.5.33V6h-4zM18 19a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V8h12z"></path><path d="M9 17a1 1 0 0 0 1-1v-4a1 1 0 0 0-2 0v4a1 1 0 0 0 1 1z"></path><path d="M15 17a1 1 0 0 0 1-1v-4a1 1 0 0 0-2 0v4a1 1 0 0 0 1 1z"></path></g></g></svg></a>';
            $data[] = $row;
        }
        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->blog->count_all(),
            "recordsFiltered" => $this->blog->count_filtered(),
            "data" => $data,
        ); 
        echo json_encode($output);
    }

    public function edit($id)
    {
        $row = $this->blog->get_by_id($id);

        $data = array(
            'id' => $row->id,
            'blog_title' => $row->blog_title,
            'blog_category' => $row->blog_category,
            'blog_date' => $row->blog_date,
            'blog_description' => $row->blog_description,
            'blog_tags' => $row->blog_tags,
            'blog_image' => $row->blog_image,
            'blog_banner' => $row->blog_banner
        );

        echo json_encode($data);
    }

    public function active($id)
    {
        $data = array();
        $sql = "update ". TBL_BLOG ." set status='1' where id ='".$id."'";       
        $res = $this->db->query($sql);
        $data[] = "sucess";
        die(json_encode($data));
    }

    public function deactive($id)
    {
        $data = array();
        $sql = "update ". TBL_BLOG ." set status='0' where id ='".$id."'";       
        $res = $this->db->query($sql);
        $data[] = "sucess";
        die(json_encode($data));
    }

    public function delete($id)
    {
        $get_id = $id; 
        $sql_query = $this->db->query("select id, blog_image, blog_banner, publish from ". TBL_BLOG ." where id='$get_id' and publish='1'")->row(); 
        if (isset($sql_query))
        {   
            if(!empty($sql_query->blog_image))
            {
                $image_file_path = BLOG_PATH . "/" . $sql_query->blog_image; 
                if(file_exists($image_file_path)) {
                    unlink($image_file_path);
                }
            }

            if(!empty($sql_query->blog_banner))
            {
                $banner_file_path = BLOG_PATH . "/" . $sql_query->blog_banner; 
                if(file_exists($banner_file_path)) {
                    unlink($banner_file_path);
                }
            }
        }
        $response = array("status" => "ok", "heading" => "Deleted", "message" => "Blog Deleted Successfully.", "tbc_name" => "");
        $this->blog->delete_by_id($get_id);  
        echo json_encode($response);  
        die;
    }
}