<?php
defined('BASEPATH') or exit('No direct script access allowed');
require './vendor/autoload.php';

use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

class Product extends Admin_Core_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('products_model', 'product');
        $this->load->model('Product_model');
        $this->load->model('Product_section_model');
        $this->load->model('Product_slider_model');
    }

    function product_category()
    {
        $data['title'] = 'Product Category';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['all_category'] = $this->product->get_all_prd_category();
        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/product_category', $data);
        $this->load->view('admin/include/footer', $data);
    }

    public function view_all_product()
    {
        $data['title'] = 'All Products';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['view_all_product'] = $this->product->get_all_products();
        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/view_all_product', $data);
        $this->load->view('admin/include/footer', $data);
    }

    function add_new_product()
    {
        $data['title'] = 'Add Products';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['all_category'] = $this->product->get_all_prd_category();
        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/add_new_product_new', $data);
        $this->load->view('admin/include/footer', $data);
    }

    function add_product()
    {
        // if ($this->product->add_product()) {
        //     $this->session->set_userdata('success', "Product Successfully Added");
        //     redirect($this->agent->referrer());
        // } else {
        //     $this->session->set_userdata('error', "Product Added Faild");
        //     redirect($this->agent->referrer());
        // }

        if ($this->input->post()) {
            $post = $this->input->post();
            $slug = url_title($post['prd_title'], '-', true);
            $prd_id = $this->Product_model->create([
                'prd_title' => $post['prd_title'],
                'prd_category' => $post['prd_category'],
                'prd_theme' => $post['prd_theme'],
                'prd_slug' => $slug,
                'prd_status' => 1
            ]);
            // Optionally insert default empty sections for the product
            $this->_create_default_sections($prd_id);
            redirect('admin/product/edit/' . $prd_id);
        }
    }

    protected function _create_default_sections($prd_id)
    {
        $keys = [
            'hero_section',
            'section_1',
            'section_2',
            'section_3',
            'section_4',
            'section_5',
            'section_6',
            'section_7',
            'pricing_section',
            'faq',
        ];
        foreach ($keys as $i => $k) {
            $this->Product_section_model->upsert_section($prd_id, $k, ['title' => '', 'body' => ''], null, $i);
        }
    }

    function edit($prd_id)
    {
        // error_reporting(0);
        // $data['title'] = 'Edit Products';
        // $data['app_setting'] = $this->setting_model->get_all_app_setting();
        // $data['product'] = $this->product->get_product_by_id($id);
        // $data['all_category'] = $this->product->get_all_prd_category();
        // $this->load->view('admin/include/header', $data);
        // $this->load->view('admin/product/edit_product', $data);
        // $this->load->view('admin/include/footer', $data);

        $product = $this->Product_model->get($prd_id);
        if (!$product) show_404();


        // sections
        $sections = $this->Product_section_model->get_sections($prd_id);
        $slides = $this->Product_slider_model->get_slides($prd_id);



        $data = [
            'product' => $product,
            'sections' => $sections,
            'slides' => $slides
        ];

        $data['title'] = 'Edit Products';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();

        // echo '<pre>';
        // print_r($data['sections']);


        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product_new/edit');
        $this->load->view('admin/include/footer');
    }

    function update_prd_basic()
    {
        $prd_id = $this->input->post('prd_id');

        $content = [
            'prd_title'        => $this->input->post('prd_title'),
            'prd_meta_title'     => $this->input->post('prd_meta_title'),
            'prd_meta_description'  => $this->input->post('prd_meta_description'),
            'prd_meta_keywords'  => $this->input->post('prd_meta_keywords'),
        ];

        if (!empty($_FILES['prd_meta_og_image']['name'])) {

            $_FILES['file']['name']     = $_FILES['prd_meta_og_image']['name'];
            $_FILES['file']['type']     = $_FILES['prd_meta_og_image']['type'];
            $_FILES['file']['tmp_name'] = $_FILES['prd_meta_og_image']['tmp_name'];
            $_FILES['file']['error']    = $_FILES['prd_meta_og_image']['error'];
            $_FILES['file']['size']     = $_FILES['prd_meta_og_image']['size'];

            // Upload configuration
            $config['upload_path']   = 'uploads/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['max_size']      = 20000; // 20 MB
            $config['file_name']     = uniqid() . '_' . $_FILES['prd_meta_og_image']['name'];

            // Load & initialize upload library
            $this->load->library('upload');
            $this->upload->initialize($config);

            // Upload file
            if ($this->upload->do_upload('file')) {

                $uploadData = $this->upload->data();
                $filename   = $uploadData['file_name'];

                if (!empty($filename)) {
                    $content['prd_meta_og_image'] = 'uploads/' . $filename;
                }
            } else {
                // Optional: handle upload error
                $error = $this->upload->display_errors();
                echo $error;
                exit;
            }
        }

        $this->Product_model->update($prd_id, $content);

        $this->session->set_userdata('success', "Data Successfully Saved");

        redirect($this->agent->referrer());
    }

    public function save_section()
    {
        $prd_id = $this->input->post('prd_id');
        $section_key = $this->input->post('section_key');

        $content = [];  // JSON object to store

        /* ------------------------------
       HERO SECTION
    -------------------------------*/
        if ($section_key == 'hero_section') {

            $content = [
                'title'        => $this->input->post('title'),
                'subtitle'     => $this->input->post('subtitle'),
                'description'  => $this->input->post('description'),
                'button_text'  => $this->input->post('button_text'),
                'button_url'   => $this->input->post('button_url'),
            ];

            if (!empty($_FILES['image']['name'])) {

                $_FILES['file']['name']     = $_FILES['image']['name'];
                $_FILES['file']['type']     = $_FILES['image']['type'];
                $_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'];
                $_FILES['file']['error']    = $_FILES['image']['error'];
                $_FILES['file']['size']     = $_FILES['image']['size'];

                // Upload configuration
                $config['upload_path']   = 'uploads/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                $config['max_size']      = 20000; // 20 MB
                $config['file_name']     = uniqid() . '_' . $_FILES['image']['name'];

                // Load & initialize upload library
                $this->load->library('upload');
                $this->upload->initialize($config);

                // Upload file
                if ($this->upload->do_upload('file')) {

                    $uploadData = $this->upload->data();
                    $filename   = $uploadData['file_name'];

                    if (!empty($filename)) {
                        $content['image'] = 'uploads/' . $filename;
                    }
                } else {
                    // Optional: handle upload error
                    $error = $this->upload->display_errors();
                    echo $error;
                    exit;
                }
            }
        }

        /* ------------------------------
       SECTION 1 (Title + Bullet Points)
    -------------------------------*/ elseif ($section_key == 'section_1' || $section_key == 'section_3' || $section_key == 'section_4' || $section_key == 'section_5' || $section_key == 'section_7') {

            $content['title'] = $this->input->post('title');

            $points_raw = $this->input->post('points');
            $content['points'] = array_filter(array_map('trim', explode("\n", $points_raw)));

            if (!empty($_FILES['image']['name'])) {

                $_FILES['file']['name']     = $_FILES['image']['name'];
                $_FILES['file']['type']     = $_FILES['image']['type'];
                $_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'];
                $_FILES['file']['error']    = $_FILES['image']['error'];
                $_FILES['file']['size']     = $_FILES['image']['size'];

                // Upload configuration
                $config['upload_path']   = 'uploads/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                $config['max_size']      = 20000; // 20 MB
                $config['file_name']     = uniqid() . '_' . $_FILES['image']['name'];

                // Load & initialize upload library
                $this->load->library('upload');
                $this->upload->initialize($config);

                // Upload file
                if ($this->upload->do_upload('file')) {

                    $uploadData = $this->upload->data();
                    $filename   = $uploadData['file_name'];

                    if (!empty($filename)) {
                        $content['image'] = 'uploads/' . $filename;
                    }
                } else {
                    // Optional: handle upload error
                    $error = $this->upload->display_errors();
                    echo $error;
                    exit;
                }
            }
        }

        /* ------------------------------
       SECTION 2 – Device Manage
    -------------------------------*/ elseif ($section_key == 'section_2') {

            $content['main_title'] = $this->input->post('main_title');

            $items = $this->input->post('items') ?? [];
            $old_feature_images = $this->input->post('old_feature_image') ?? [];

            foreach ($items as $i => &$item) {

                // ✅ Keep old feature image by default
                if (!empty($old_feature_images[$i])) {
                    $item['image'] = $old_feature_images[$i];
                }

                // ✅ Upload new feature image (if selected)
                if (!empty($_FILES['feature_image']['name'][$i])) {

                    $_FILES['file']['name']     = $_FILES['feature_image']['name'][$i];
                    $_FILES['file']['type']     = $_FILES['feature_image']['type'][$i];
                    $_FILES['file']['tmp_name'] = $_FILES['feature_image']['tmp_name'][$i];
                    $_FILES['file']['error']    = $_FILES['feature_image']['error'][$i];
                    $_FILES['file']['size']     = $_FILES['feature_image']['size'][$i];

                    $config['upload_path']   = 'uploads/';
                    $config['allowed_types'] = 'jpg|jpeg|png|webp';
                    $config['max_size']      = 20000;
                    $config['file_name']     = uniqid() . '_feature';

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

                    if ($this->upload->do_upload('file')) {
                        $up = $this->upload->data();
                        $item['image'] = 'uploads/' . $up['file_name'];
                    }
                }
            }

            $content['items'] = $items;

            // ✅ Keep OLD main image by default
            $old_main = $this->input->post('old_main_image');
            if (!empty($old_main)) {
                $content['image'] = $old_main;
            }

            // ✅ Upload NEW main image only if selected
            if (!empty($_FILES['main_image']['name'])) {

                $_FILES['file']['name']     = $_FILES['main_image']['name'];
                $_FILES['file']['type']     = $_FILES['main_image']['type'];
                $_FILES['file']['tmp_name'] = $_FILES['main_image']['tmp_name'];
                $_FILES['file']['error']    = $_FILES['main_image']['error'];
                $_FILES['file']['size']     = $_FILES['main_image']['size'];

                $config['upload_path']   = 'uploads/';
                $config['allowed_types'] = 'jpg|jpeg|png|webp';
                $config['max_size']      = 20000;
                $config['file_name']     = uniqid() . '_main';

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

                if ($this->upload->do_upload('file')) {
                    $up = $this->upload->data();
                    $content['image'] = 'uploads/' . $up['file_name'];
                }
            }
        }


        /* ------------------------------
       SECTION 6 – Video Section
    -------------------------------*/ elseif ($section_key == 'section_6') {

            $content = [
                'title'      => $this->input->post('title'),
                'video_link' => $this->input->post('video_link'),
            ];
        }

        /* ------------------------------
       PRICING SECTION
    -------------------------------*/ elseif ($section_key == 'pricing_section') {

            $content['title'] = $this->input->post('title');

            $content['plans'] = [
                [
                    'name'     => $this->input->post('plan1_name'),
                    'price'    => $this->input->post('plan1_price'),
                    'features' => array_filter(array_map('trim', explode("\n", $this->input->post('plan1_features'))))
                ],
                [
                    'name'     => $this->input->post('plan2_name'),
                    'price'    => $this->input->post('plan2_price'),
                    'features' => array_filter(array_map('trim', explode("\n", $this->input->post('plan2_features'))))
                ],
                [
                    'name'     => $this->input->post('plan3_name'),
                    'price'    => $this->input->post('plan3_price'),
                    'features' => array_filter(array_map('trim', explode("\n", $this->input->post('plan3_features'))))
                ],
            ];
        }

        /* ------------------------------
       FAQ SECTION
    -------------------------------*/ elseif ($section_key == 'faq_section') {

            $content['heading'] = $this->input->post('heading');
            $content['items']   = $this->input->post('items');
        }

        /* ------------------------------
       SAVE INTO DATABASE
    -------------------------------*/
        // $this->load->model('Product_section_model');
        $this->Product_section_model->upsert_section($prd_id, $section_key, $content);
        $this->session->set_userdata('success', "Data Successfully Saved");
        redirect($this->agent->referrer());
    }

    private function _do_upload($field_name)
    {
        $path = "uploads/sections/";
        if (!is_dir($path)) mkdir($path, 0755, true);

        // Move uploaded file to "file" index
        $_FILES['file']['name']     = $_FILES[$field_name]['name'];
        $_FILES['file']['type']     = $_FILES[$field_name]['type'];
        $_FILES['file']['tmp_name'] = $_FILES[$field_name]['tmp_name'];
        $_FILES['file']['error']    = $_FILES[$field_name]['error'];
        $_FILES['file']['size']     = $_FILES[$field_name]['size'];

        // Upload config
        $config = [
            'upload_path'   => $path,
            'allowed_types' => 'jpg|jpeg|png|svg|webp',
            'max_size'      => '5000', // KB
            'file_name'     => uniqid() . "_" . $_FILES[$field_name]['name'],
        ];

        // Load & initialize upload library
        $this->load->library('upload');
        $this->upload->initialize($config);

        // Do upload
        if (!$this->upload->do_upload('file')) {

            return [
                'status' => false,
                'error'  => $this->upload->display_errors()
            ];
        }

        // Get uploaded file data
        $uploadData = $this->upload->data();
        $filename   = $uploadData['file_name'];

        return [
            'status'    => true,
            'file_name' => $path . $filename
        ];
    }






    function update_product($id)
    {
        if ($this->product->update_product($id)) {
            $this->session->set_userdata('success', "Product Successfully Updated");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Product Updated Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete($id)
    {
        if ($this->product->delete($id)) {
            $this->session->set_userdata('success', "Product Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Product Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    function product_inquery()
    {
        if (isset($_GET['start_date'])) {
            $start_date = $_GET['start_date'];
            $end_date = $_GET['end_date'];
        } else {
            $start_date = '';
            $end_date = date('Y-m-d');
        }

        $data['title'] = 'All Products';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['product_first_seen'] = $this->product->get_all_product_first_seen($start_date, $end_date);
        $data['product_inquery'] = $this->product->get_all_product_inquery($start_date, $end_date);
        $data['abandoned_product_inquery'] = $this->product->abandoned_product_inquery($start_date, $end_date);
        $data['download_boucher'] = $this->product->get_all_product_download_boucher($start_date, $end_date);
        $data['get_all_product_video_demo'] = $this->product->get_all_product_video_demo($start_date, $end_date);
        $data['demo_inquery'] = $this->product->get_all_product_demo_inquery($start_date, $end_date);
        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/product_inquery', $data);
        $this->load->view('admin/include/footer', $data);
    }

    function delete_inq($id)
    {
        if ($this->product->delete_inq($id)) {
            $this->session->set_userdata('success', "Inquery Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Inquery Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_inq_all()
    {
        echo $this->product->delete_inq_all();
    }

    function delete_inq_first($id)
    {
        if ($this->product->delete_inq_first($id)) {
            $this->session->set_userdata('success', "Inquery Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Inquery Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_inq_first_all()
    {
        echo $this->product->delete_inq_first_all();
    }

    function delete_back_prd_image($id)
    {
        if ($this->product->delete_back_prd_image($id)) {
            $this->session->set_userdata('success', "Image Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Image Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_front_prd_image($id)
    {
        if ($this->product->delete_front_prd_image($id)) {
            $this->session->set_userdata('success', "Image Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Image Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    public function product_faq()
    {
        $data['title'] = 'Product FAQ';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['visual_setting'] = $this->setting_model->get_visual_setting();
        $data['get_all_product'] = $this->product->get_all_products();
        $data['get_all_faq'] = $this->product->get_all_faq();

        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/product_faq');
        $this->load->view('admin/include/footer');
    }


    public function add_new_product_faq()
    {
        if ($this->product->add_new_product_faq()) {
            $this->session->set_userdata('success', "FAQ Successfully Added");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "FAQ Added Faild");
            redirect($this->agent->referrer());
        }
    }

    public function update_product_faq()
    {
        if ($this->product->update_product_faq()) {
            $this->session->set_userdata('success', "FAQ Successfully Updated");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "FAQ Updated Faild");
            redirect($this->agent->referrer());
        }
    }

    public function delete_product_faq($id)
    {
        if ($this->product->delete_product_faq($id)) {
            $this->session->set_userdata('success', "FAQ Successfully delete");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "FAQ delete Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_demo_inq($id)
    {
        if ($this->product->delete_demo_inq($id)) {
            $this->session->set_userdata('success', "Data Successfully delete");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "FAQ delete Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_demo_inq_all()
    {
        echo $this->product->delete_demo_inq_all();
    }

    function delete_boucher_inq($id)
    {
        if ($this->product->delete_boucher_inq($id)) {
            $this->session->set_userdata('success', "Data Successfully delete");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "FAQ delete Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_boucher_inq_all()
    {
        echo $this->product->delete_boucher_inq_all();
    }

    function add_new_category()
    {
        if ($this->product->add_new_category()) {
            $this->session->set_userdata('success', "Category Successfully Added");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Category Added Faild");
            redirect($this->agent->referrer());
        }
    }

    function update_prd_category()
    {
        if ($this->product->update_prd_category()) {
            $this->session->set_userdata('success', "Category Successfully Updated");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Category Updated Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_category($id)
    {
        if ($this->product->delete_category($id)) {
            $this->session->set_userdata('success', "Category Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Category Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    function product_bonus()
    {
        $data['title'] = 'Product Bonus';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['visual_setting'] = $this->setting_model->get_visual_setting();
        $data['get_all_product'] = $this->product->get_all_products();
        $data['all_bonus'] = $this->product->get_all_products_bonus();

        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/product_bonus');
        $this->load->view('admin/include/footer');
    }

    function add_new_product_bonus()
    {
        if ($this->product->add_new_product_bonus()) {
            $this->session->set_userdata('success', "Bonus Successfully Added");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Bonus Added Faild");
            redirect($this->agent->referrer());
        }
    }

    function update_product_bonus($id)
    {
        if ($this->product->update_product_bonus($id)) {
            $this->session->set_userdata('success', "Bonus Successfully Updated");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Bonus Updated Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_product_bonus($id)
    {
        if ($this->product->delete_product_bonus($id)) {
            $this->session->set_userdata('success', "Bonus Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Bonus Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_video_demo($id)
    {
        if ($this->product->delete_video_demo($id)) {
            $this->session->set_userdata('success', "Data Successfully Deleted");
            redirect($this->agent->referrer());
        } else {
            $this->session->set_userdata('error', "Data Deleted Faild");
            redirect($this->agent->referrer());
        }
    }

    function delete_video_demo_all()
    {
        echo $this->product->delete_video_demo_all();
    }

    function my_products()
    {
        $data['title'] = 'My Product';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['visual_setting'] = $this->setting_model->get_visual_setting();
        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/my_products');
        $this->load->view('admin/include/footer');
    }

    function my_billing()
    {
        $data['title'] = 'My Billing';
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $data['visual_setting'] = $this->setting_model->get_visual_setting();
        $this->load->view('admin/include/header', $data);
        $this->load->view('admin/product/my_products');
        $this->load->view('admin/include/footer');
    }

    function pay_due_amount($id, $pack_id)
    {
        $product_id       = user()->product;
        $prd_last_pay_id  = user()->prd_last_pay_id;
        $this->db->select('a.package, a.prd_name, a.prd_image, a.advance_payment, a.main_price, a.disocunt_price, b.*');
        $this->db->from('products a');
        $this->db->join('product_inquery b', 'b.prd_inq_prd_id = a.prd_id', 'left');
        $this->db->where('a.prd_id', $product_id);
        $this->db->where('b.prd_inq_id', $prd_last_pay_id);
        $product = $this->db->get()->row();

        $this->session->set_userdata('prd_last_id',  $id);
        $this->session->set_userdata('last_payment', $product->prd_inq_pay_amount);

        if (json_decode($product->package)[$pack_id]->dis_price > 0) {
            $main_price = json_decode($product->package)[$pack_id]->dis_price;
        } else {
            $main_price = json_decode($product->package)[$pack_id]['price'];
        }

        $amounts = $main_price - $product->prd_inq_pay_amount;

        $app_setting = $this->setting_model->get_all_app_setting();
        $rand = "RAOR" . date("Ymd") . rand(1000, 9999);
        $order_id = $rand;
        $api = new Api($app_setting->rozar_key_id, $app_setting->rozar_key_secret);
        $razorpayOrder = $api->order->create(array(
            'receipt'         => $order_id,
            'amount'          => $amounts * 100,
            'currency'        => 'INR',
            'payment_capture' => 1
        ));
        $amount = $razorpayOrder['amount'];
        $razorpayOrderId = $razorpayOrder['id'];
        $_SESSION['razorpay_order_id'] = $razorpayOrderId;
        $_SESSION['recharge_id'] = $order_id;
        $_SESSION['amount'] = $amount;
        $raz_pay_data = $this->rozr_pay_prepareData_prd_pay($amount, $razorpayOrderId, $order_id);
        $this->load->view('rezorpay_payment_due_prd_payment', array('data' => $raz_pay_data));
    }

    public function rozr_pay_prepareData_prd_pay($amount, $razorpayOrderId, $order_id)
    {
        $app_setting = $this->setting_model->get_all_app_setting();
        $data = array(
            "key" => $app_setting->rozar_key_id,
            "amount" => $amount,
            "name" => $order_id,
            "description" => $app_setting->application_name,
            "image" => base_url() . $app_setting->header_logo,
            "prefill" => array(
                "name"  => user()->name,
                "email"  => user()->email,
                "contact" => user()->mobile,
            ),
            "notes"  => array(
                "address"  => "Hello World",
                "merchant_order_id" => rand(),
            ),
            "theme"  => array(
                "color"  => "#F37254"
            ),
            "order_id" => $razorpayOrderId,
        );
        return $data;
    }

    function rozr_pay_verify_due_product_pay()
    {
        $app_setting = $this->setting_model->get_all_app_setting();
        $success = true;
        $error = "payment_failed";
        if (empty($_POST['razorpay_payment_id']) === false) {
            $api = new Api($app_setting->rozar_key_id, $app_setting->rozar_key_secret);
            try {
                $attributes = array(
                    'razorpay_order_id' => $_SESSION['razorpay_order_id'],
                    'razorpay_payment_id' => $_POST['razorpay_payment_id'],
                    'razorpay_signature' => $_POST['razorpay_signature']
                );
                $api->utility->verifyPaymentSignature($attributes);
            } catch (SignatureVerificationError $e) {
                $success = false;
                $error = 'Razorpay_Error : ' . $e->getMessage();
            }
        }
        if ($success === true) {
            $amt = $_SESSION['amount'] / 100;
            $main_amt = $amt + $this->session->userdata('last_payment');
            $this->load->model('products_model');
            $info['prd_inq_payment']                    = 1;
            $info['prd_inq_pay_id']                     = $_POST['razorpay_payment_id'];
            $info['prd_inq_pay_amount']                 = $main_amt;
            if ($this->products_model->update_request_prd_payment_data($info, $this->session->userdata('prd_last_id'))) {
                $this->session->set_userdata('success_page', 'Yes');
                $this->session->set_userdata('success', 'Wow ! Congrats,Your your order is Confirm with us');
                redirect(base_url() . 'admin/product/my_products');
            } else {
                $this->session->set_userdata('error', 'Transaction Done But System Error. Please Contact Support Team.');
                redirect(base_url() . 'admin/product/my_products');
            }
        } else {
            $this->session->set_userdata('error', 'Transaction Faild');
            redirect(base_url() . 'admin/product/my_products');
        }
    }

    function download_invoice($id, $pack_id)
    {
        $product_id       = user()->product;
        $prd_last_pay_id  = user()->prd_last_pay_id;
        $this->db->select('a.package, a.prd_name, a.prd_image, a.advance_payment, a.main_price, a.disocunt_price, b.*');
        $this->db->from('products a');
        $this->db->join('product_inquery b', 'b.prd_inq_prd_id = a.prd_id', 'left');
        $this->db->where('a.prd_id', $product_id);
        $this->db->where('b.prd_inq_id', $prd_last_pay_id);
        $product = $this->db->get()->row();
        $data['product'] = $product;
        $data['id'] = $id;
        $data['pack_id'] = $pack_id;
        $data['app_setting'] = $this->setting_model->get_all_app_setting();
        $this->load->view('admin/product/download_invoice', $data);
    }

    function download_code()
    {
        $this->load->helper('download');
        $rtr = file_get_contents(base_url() . "code.zip");
        force_download("Code.zip", $rtr);
    }
}
