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

class Home extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper(['url', 'language', 'function_helper', 'bootstrap_table_helper', 'file']);
        $this->load->model(['Home_model', 'Order_model', 'Cart_model']);
    }
    public function index()
    {
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
            $this->data['main_page'] = FORMS . 'home';
            $settings = get_settings('system_settings', true);
            $this->data['title'] = 'Admin Panel | ' . $settings['app_name'];
            $this->data['meta_description'] = 'Admin Panel | ' . $settings['app_name'];
            $this->data['curreny'] = get_settings('currency');
            $this->data['order_counter'] = $this->Home_model->count_new_orders();
            $this->data['user_counter'] = $this->Home_model->count_new_users();
            $this->data['delivery_boy_counter'] = $this->Home_model->count_delivery_boys();
            $this->data['product_counter'] = $this->Home_model->count_products();
            $this->data['count_products_low_status'] = $this->Home_model->count_products_stock_low_status();
            $this->data['count_products_availability_status'] = $this->Home_model->count_products_availability_status();

            // send admin notification
            $this->data['notifications'] = fetch_details('system_notification',  NULL,  '*',  '3', '0',  'read_by', 'ASC',  '',  '');
            $this->data['count_noti'] = fetch_details('system_notification',  ["read_by" => 0],  'count(id) as total');

            $orders_count['awaiting'] = orders_count("awaiting");
            $orders_count['received'] = orders_count("received");
            $orders_count['processed'] = orders_count("processed");
            $orders_count['shipped'] = orders_count("shipped");
            $orders_count['delivered'] = orders_count("delivered");
            $orders_count['cancelled'] = orders_count("cancelled");
            $orders_count['returned'] = orders_count("returned");
            $orders_count['draft'] = orders_count("draft");
            $orders_count['return_request_pending'] = orders_count("return_request_pending");
            $orders_count['ready_to_pickup'] = orders_count("ready_to_pickup");

            $this->data['status_counts'] = $orders_count;
            $this->data['delivery_res'] = $this->db->where(['ug.group_id' => '3'])->join('users_groups ug', 'ug.user_id = u.id')->get('users u')->result_array();
            $this->load->view('admin/template', $this->data);
        } else {
            redirect('admin/login', 'refresh');
        }
    }

    public function category_wise_product_sales()
    {
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
            $res = $this->db->select('c.name as category,count(oi.product_variant_id) as sales')
                ->join(' `product_variants` `pv` ', 'oi.`product_variant_id`=pv.`id`')
                ->join(' `products` p  ', ' pv.`product_id`=p.`id` ')
                ->join(' categories c ', ' p.category_id=c.id ')
                ->group_by('p.category_id')->get('`order_items` oi')->result_array();
            $response['category'] = array_column($res, 'category');
            $response['sales'] = array_column($res, 'sales');
            echo json_encode($response);
        } else {
            redirect('admin/login', 'refresh');
        }
    }

    public function fetch_sales()
    {
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
            $sales[] = array();

            $month_res = $this->db->select('SUM(final_total) AS total_sale,DATE_FORMAT(date_added,"%b") AS month_name ')
                ->group_by('year(CURDATE()),MONTH(date_added)')
                ->order_by('year(CURDATE()),MONTH(date_added)')
                ->get('`orders`')->result_array();

            $month_wise_sales['total_sale'] = array_map('intval', array_column($month_res, 'total_sale'));
            $month_wise_sales['month_name'] = array_column($month_res, 'month_name');

            $sales[0] = $month_wise_sales;
            $d = strtotime("today");
            $start_week = strtotime("last sunday midnight", $d);
            $end_week = strtotime("next saturday", $d);
            $start = date("Y-m-d", $start_week);
            $end = date("Y-m-d", $end_week);
            $week_res = $this->db->select("DATE_FORMAT(date_added, '%d-%b') as date, SUM(final_total) as total_sale")
                ->where("date(date_added) >='$start' and date(date_added) <= '$end' ")
                ->group_by('day(date_added)')->get('`orders`')->result_array();

            $week_wise_sales['total_sale'] = array_map('intval', array_column($week_res, 'total_sale'));
            $week_wise_sales['week'] = array_column($week_res, 'date');

            $sales[1] = $week_wise_sales;
            $day_res = $this->db->select("DAY(date_added) as date, SUM(final_total) as total_sale")
                ->where('date_added >= DATE_SUB(CURDATE(), INTERVAL 29 DAY)')
                ->group_by('day(date_added)')->get('`orders`')->result_array();
            $day_wise_sales['total_sale'] = array_map('intval', array_column($day_res, 'total_sale'));
            $day_wise_sales['day'] = array_column($day_res, 'date');

            $sales[2] = $day_wise_sales;
            print_r(json_encode($sales));
        } else {
            redirect('admin/login', 'refresh');
        }
    }

    public function category_wise_product_count()
    {
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
            $res = $this->db->select('c.name as name,count(c.id) as counter')->where(['p.status' => '1', 'c.status' => '1'])->join('products p', 'p.category_id=c.id')->group_by('c.id')->get('categories c')->result_array();
            $result = array();
            $result[0][] = 'Task';
            $result[0][] = 'Hours per Day';
            array_walk($res, function ($v, $k) use (&$result) {
                $result[$k + 1][] = $v['name'];
                $result[$k + 1][] = intval($v['counter']);
            });
            echo json_encode(array_values($result));
        } else {
            redirect('admin/login', 'refresh');
        }
    }


    public function delete_image()
    {
        $this->response['is_deleted'] = delete_image($this->input->post('id', true), $this->input->post('path', true), $this->input->post('field', true), $this->input->post('img_name', true), $this->input->post('table_name', true), $this->input->post('isjson', true));
        $this->response['csrfName'] = $this->security->get_csrf_token_name();
        $this->response['csrfHash'] = $this->security->get_csrf_hash();
        print_r(json_encode($this->response));
    }
    public function logout()
    {
        $this->ion_auth->logout();
        redirect('admin/login', 'refresh');
    }

    public function profile()
    {
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
            $identity_column = $this->config->item('identity', 'ion_auth');
            $this->data['users'] = $this->ion_auth->user()->row();
            $settings = get_settings('system_settings', true);
            $this->data['identity_column'] = $identity_column;
            $this->data['main_page'] = FORMS . 'profile';
            $this->data['title'] = 'Change Password | ' . $settings['app_name'];
            $this->data['meta_description'] = 'Change Password | ' . $settings['app_name'];
            $this->load->view('admin/template', $this->data);
        } else {
            redirect('admin/home', 'refresh');
        }
    }

    public function update_status()
    {

        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
            if (defined('ALLOW_MODIFICATION') && ALLOW_MODIFICATION == 0) {
                $this->response['error'] = true;
                $this->response['message'] = DEMO_VERSION_MSG;
                echo json_encode($this->response);
                return false;
            }
            if ($_GET['table'] == 'products') {
                if (!has_permissions('update', 'product')) {
                    $this->response['error'] = true;
                    $this->response['message'] = PERMISSION_ERROR_MSG;
                    echo json_encode($this->response);
                    return false;
                }
            }
            if ($_GET['table'] == 'categories') {
                if (!has_permissions('update', 'category')) {
                    $this->response['error'] = true;
                    $this->response['message'] = PERMISSION_ERROR_MSG;
                    echo json_encode($this->response);
                    return false;
                }
            }
            if ($_GET['table'] == 'brands') {
                if (!has_permissions('update', 'brand')) {
                    $this->response['error'] = true;
                    $this->response['message'] = PERMISSION_ERROR_MSG;
                    echo json_encode($this->response);
                    return false;
                }
            }
            if ($_GET['table'] == 'users') {
                if (!has_permissions('update', 'customers')) {
                    $this->response['error'] = true;
                    $this->response['message'] = PERMISSION_ERROR_MSG;
                    echo json_encode($this->response);
                    return false;
                }
            }
            if ($_GET['table'] == 'attribute_values') {
                if (!has_permissions('update', 'attribute_value')) {
                    $this->response['error'] = true;
                    $this->response['message'] = PERMISSION_ERROR_MSG;
                    echo json_encode($this->response);
                    return false;
                }
            }
            if ($_GET['table'] == 'attribute_set') {
                if (!has_permissions('update', 'attribute_set')) {
                    $this->response['error'] = true;
                    $this->response['message'] = PERMISSION_ERROR_MSG;
                    echo json_encode($this->response);
                    return false;
                }
            }
            $_GET['status'] = ($_GET['status'] == '1') ? 0 : 1;
            if ($_GET['table'] == 'categories' && $_GET['status'] == 0) {
                $this->db->where('category_id', $_GET['id']);
                $query = $this->db->get('products');
                if ($query->num_rows() > 0) {
                    $response['error'] = true;
                    $response['csrfName'] = $this->security->get_csrf_token_name();
                    $response['csrfHash'] = $this->security->get_csrf_hash();
                    $response['message'] = "This category contains products that cannot be disabled.";
                    return print_r(json_encode($response));
                }
                $this->load->model('category_model');
                if ($this->category_model->check_subcategories_have_products_public($_GET['id'])) {
                    $response['error'] = true;
                    $response['csrfName'] = $this->security->get_csrf_token_name();
                    $response['csrfHash'] = $this->security->get_csrf_hash();
                    $response['message'] = "This category has subcategories with products and cannot be disabled.";
                    return print_r(json_encode($response));
                }
            }

            if ($_GET['table'] == 'brands' && $_GET['status'] == 0) {
                $this->db->select('name');
                $this->db->from('brands');
                $this->db->where('id', $_GET['id']);
                $brand_query = $this->db->get()->result_array();
                if (isset($brand_query[0]['name']) && !empty($brand_query[0]['name'])) {
                    $this->db->where('brand', $brand_query[0]['name']);
                    $query = $this->db->get('products');
                }
                if (null !== $query->num_rows() && $query->num_rows() > 0) {
                    $response['error'] = true;
                    $response['csrfName'] = $this->security->get_csrf_token_name();
                    $response['csrfHash'] = $this->security->get_csrf_hash();
                    $response['message'] = "This brand contains products and cannot be disabled.";
                    return print_r(json_encode($response));
                }
            }

            if ($_GET['table'] == 'attribute_values' && $_GET['status'] == 0) {
                $this->db->select('COUNT(pa.id) as total');
                $this->db->from('product_attributes pa');
                $this->db->where('FIND_IN_SET(' . $_GET['id'] . ', pa.attribute_value_ids) > 0', null, false);
                $query = $this->db->get()->result_array();
                if (isset($query[0]['total']) && $query[0]['total'] > 0) {
                    $response['error'] = true;
                    $response['csrfName'] = $this->security->get_csrf_token_name();
                    $response['csrfHash'] = $this->security->get_csrf_hash();
                    $response['message'] = "This attribute value is assigned to products and cannot be deactivated.";
                    return print_r(json_encode($response));
                }
            }

            if ($_GET['table'] == 'attributes' && $_GET['status'] == 0) {
                $this->db->select('COUNT(DISTINCT pa.id) as count');
                $this->db->from('product_attributes pa');
                $this->db->join('attribute_values av', 'av.attribute_id = ' . $_GET['id'], 'left', false);
                $this->db->where('FIND_IN_SET(av.id, pa.attribute_value_ids) > 0', null, false);
                $query = $this->db->get()->result_array();
                if (isset($query[0]['count']) && $query[0]['count'] > 0) {
                    $response['error'] = true;
                    $response['csrfName'] = $this->security->get_csrf_token_name();
                    $response['csrfHash'] = $this->security->get_csrf_hash();
                    $response['message'] = "This attribute is assigned to products and cannot be deactivated.";
                    return print_r(json_encode($response));
                }
            }

            if ($_GET['table'] == 'attribute_set' && $_GET['status'] == 0) {
                $this->db->select('pa.id');
                $this->db->from('product_attributes pa');
                $this->db->join('attribute_values av', 'FIND_IN_SET(av.id, pa.attribute_value_ids) > 0', 'inner');
                $this->db->join('attributes a', 'a.id=av.attribute_id', 'inner');
                $this->db->where('a.attribute_set_id', $_GET['id']);
                $query = $this->db->get()->result_array();
                if (count($query) > 0) {
                    $response['error'] = true;
                    $response['csrfName'] = $this->security->get_csrf_token_name();
                    $response['csrfHash'] = $this->security->get_csrf_hash();
                    $response['message'] = "This attribute set is assigned to products and cannot be deactivated.";
                    return print_r(json_encode($response));
                }
            }

            if ($_GET['table'] == 'themes' && $_GET['status'] == 0) {
                $this->db->select('COUNT(id) as active_count');
                $this->db->from('themes');
                $this->db->where('status', 1);
                $this->db->where('id !=', $_GET['id']);
                $query = $this->db->get()->result_array();
                if (isset($query[0]['active_count']) && $query[0]['active_count'] == 0) {
                    $response['error'] = true;
                    $response['csrfName'] = $this->security->get_csrf_token_name();
                    $response['csrfHash'] = $this->security->get_csrf_hash();
                    $response['message'] = "At least one theme must remain active. Cannot disable all themes.";
                    return print_r(json_encode($response));
                }
            }

            $this->db->trans_start();
            if ($_GET['table'] == 'users') {
                $this->db->set('active', $this->db->escape($_GET['status']));
            } else {
                $this->db->set('status', $this->db->escape($_GET['status']));
            }

            $this->db->where('id', $_GET['id'])->update($_GET['table']);
            $this->db->trans_complete();
            $error = true;
            $message = str_replace('_', ' ', $_GET['table']);
            if ($this->db->trans_status() === true) {
                $error = false;
            }
            $response['error'] = $error;
            $response['csrfName'] = $this->security->get_csrf_token_name();
            $response['csrfHash'] = $this->security->get_csrf_hash();
            $response['message'] = $message;
            print_r(json_encode($response));
        } else {
            redirect('admin/login', 'refresh');
        }
    }

    // send admin notification
    public function get_notification()
    {
        if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
            $count_noti = fetch_details('system_notification',  ["read_by" => 0],  'count(id) as total');

            $response['error'] = false;
            $response['count_notifications'] = $count_noti[0]['total'];

            print_r(json_encode($response));
        }
    }

    public function new_notification_list()
    {

        $notifications = fetch_details('system_notification', ["read_by" => 0],  '*',  '3', '0',  'id', 'DESC',  '',  '');

        $response['error'] = false;
        $response['notifications'] = $notifications;

        print_r(json_encode($response));
    }

    public function test_notification()
    {
        return $this->Cart_model->cart_item_remainder();
    }
}
