<?php

use Http\Discovery\Strategy\PuliBetaStrategy;

defined('BASEPATH') or exit('No direct script access allowed');
set_time_limit(0);

class Zapier extends ClientsController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->model('Authentication_model');
        
    }
    //login
    public function login()
    {
        file_put_contents('zapier.json', "file_get_contents('php://input')");

        file_put_contents('zapier.json', $_REQUEST['url'] . $_REQUEST['username'] . $_REQUEST['password']);
        if ($_REQUEST) {
            if ($this->validate_user($_REQUEST['username'], $_REQUEST['password'])) {
                $response = array(
                    'status' => is_staff_logged_in()
                );
                print_r(json_encode($response));
            } else {
                $response = array(
                    'Error' => "Invalid username or password"
                );
                print_r(($response));
            }
        } else {
            redirect(admin_url());
        }
    }
    // Validate the user
    public function validate_user($username, $password)
    {
        return $this->Authentication_model->login($username, $password, 1, true);
    }
    // Add new Task
    public function new_task()
    {


        $posted_data = json_decode(file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {
                $this->load->model('tasks_model');
                $data = [];

                file_put_contents('zapier.json', $posted_data->username);

                $data["billable"] = "on";
                $data["name"] = $posted_data->name;
                $data["hourly_rate"] = 0;
                $data["milestone"] = null;
                $data["startdate"] = date('Y-m-d');
                $data["duedate"] = null;
                $data["priority"] = 2;
                $data["repeat_every"] = null;
                $data["repeat_every_custom"] = 1;
                $data["repeat_type_custom"] = "day";
                $data["rel_type"] = null;
                $data["rel_id"] = null;
                $data["tags"] = "";
                $data["description"] = $posted_data->description;


                $id = $this->tasks_model->add($data);
                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    // create a new lead
    public function new_lead()
    {
        $posted_data = json_decode(file_get_contents('php://input'));
        file_put_contents('zapier.json', file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {
                $this->load->model('tasks_model');
                $data = [];

                file_put_contents('zapier.json', $posted_data->username);


                $data["name"] = $posted_data->name;
                $data['address'] = $posted_data->address;
                $data['title'] = $posted_data->title;
                $data['city'] = $posted_data->city;
                $data['email'] = $posted_data->email;
                $data['state'] = $posted_data->state;
                $data['website'] = $posted_data->website;
                $data['is_public'] = 0;
                $data['country'] = get_country_by_name($posted_data->country);
                $data['phonenumber'] = $posted_data->phonenumber;
                $data['zip'] = $posted_data->zip;
                $data['company'] = $posted_data->company;
                $data['default_language'] = $posted_data->default_language;
                $data['description'] = $posted_data->description;
                $data['dateadded']   = date('Y-m-d H:i:s');
                $data['addedfrom']   = get_staff_user_id();
                $data['assigned'] = $posted_data->assigned;
                $data['source'] = $posted_data->source;
                $data['status'] =  $posted_data->status;


                $this->db->insert(db_prefix() . 'leads', $data);
                $id = $this->db->insert_id();
                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    public function updateFields()
    {
        $id = $_POST['id'];
        $view_assigned = $_POST['view_assigned'];
        $view_source = $_POST['view_source'];
        $view_status = $_POST['view_status'];
        $ticket_view_assigned = $_POST['ticket_view_assigned'];
        $ticket_department = $_POST['ticket_department'];
        $project_view_assigned = $_POST['project_view_assigned'];
        $projects_billing_type = $_POST['projects_billing_type'];

        if ($id == 1) {
            update_option('zapier_lead_assigned', $view_assigned);
        } elseif ($id == 2) {
            update_option('zapier_lead_source', $view_source);
        } elseif ($id == 3) {
            update_option('zapier_lead_status', $view_status);
        } elseif ($id == 4) {
            update_option('ticket_lead_assigned', $ticket_view_assigned);
        } elseif ($id == 5) {
            update_option('ticket_department', $ticket_department);
        } elseif ($id == 6) {
            update_option('project_view_assigned', serialize($project_view_assigned));
        } elseif ($id == 7) {
            update_option('projects_billing_type', $projects_billing_type);
        }
    }

    public function updateClientSecret()
    {
        $client_secret = bin2hex(random_bytes(32));
        update_option('zapier_client_secret_key', $client_secret);
        echo $client_secret;
        die;
    }

    // returns array of customers objects
    public function customers()
    {
        $obj1 = (object) array('id' => 1, 'name' => 'foo');
        $obj2 = (object) array('id' => 2, 'name' => 'shoo');
        print_r(json_encode($data = array($obj1, $obj2)));
    }
    // returns array of Countries objects
    public function countries()
    {
        if ($_REQUEST) {
            $all_countries = get_all_countries();
            // $counries=[];
            $counries = [];
            foreach ($all_countries as $country) {
                $country_obj = (object) array('id' => $country['country_id'], 'name' => $country['short_name']);
                array_push($counries, $country_obj);
            }

            print_r(json_encode($counries));
        } else {
            redirect(admin_url());
        }
    }
    // returns array of Statuses objects
    public function statuses()
    {
        if ($_REQUEST) {
            $this->load->model('leads_model');
            $all_statuses = $this->leads_model->get_status();

            $statuses = [];
            foreach ($all_statuses as $statuse) {
                $country_obj = (object) array('id' => $statuse['id'], 'name' => $statuse['name']);
                array_push($statuses, $country_obj);
            }

            print_r(json_encode($statuses));
        } else {
            redirect(admin_url());
        }
    }
    // returns array of Statuses objects
    public function source()
    {
        if ($_REQUEST) {
            $this->load->model('leads_model');
            $all_source = $this->leads_model->get_source();
            $sources = [];
            foreach ($all_source as $source) {
                $source_obj = (object) array('id' => $source['id'], 'name' => $source['name']);
                array_push($sources, $source_obj);
            }

            print_r(json_encode($sources));
        } else {
            redirect(admin_url());
        }
    }
    // returns array of Statuses objects
    public function staff()
    {

        if ($_REQUEST) {
            $this->load->model('staff_model');
            $all_staff = $this->staff_model->get('', ['active' => 1]);
            $staff = [];
            foreach ($all_staff as $member) {
                $staff_obj = (object) array('id' => $member['staffid'], 'name' => $member['firstname'] . " " . $member['lastname']);
                array_push($staff, $staff_obj);
            }

            print_r(json_encode($staff));
        } else {
            redirect(admin_url());
        }
    }
    // returns array of Default Language objects
    public function defaultLanguage()
    {
        if ($_REQUEST) {
            $languages = [];
            foreach ($this->app->get_available_languages() as $language) {
                $language_obj = (object) array('id' => $language, 'name' => $language);
                array_push($languages, $language_obj);
            }

            print_r(json_encode($languages));
        } else {
            redirect(admin_url());
        }
    }
    // returns array of departments objects
    public function departments()
    {

        if ($_REQUEST) {

            $departments = [];
            foreach (departments() as $language) {
                $department_obj = (object) array('id' => $language->departmentid, 'name' => $language->name);
                array_push($departments, $department_obj);
            }

            print_r(json_encode($departments));
        } else {
            redirect(admin_url());
        }
    }
    // add new invoice
    public function invoice()
    {

        $posted_data = json_decode(file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {
                $email = explode(",", $posted_data->email);

                $item_quantities = explode(",", $posted_data->item_quantity);
                $item_names = explode(",", $posted_data->item_name);
                $rates = explode(",", $posted_data->rate);



                $client_id = get_company($email[0]);
                $companyinfo    = get_client($client_id);

                $data['cancel_merged_invoices'] = "on";
                $data['clientid']        = $client_id;
                $data['project_id']      = NULL;
                $data['billing_street']  = $companyinfo->billing_street;
                $data['billing_city']    = $companyinfo->billing_city;
                $data['billing_state']   = $companyinfo->billing_state;
                $data['billing_zip']     = $companyinfo->billing_zip;
                $data['show_shipping_on_invoice']  = "on";
                $data['shipping_street'] = $companyinfo->shipping_street;
                $data['shipping_city']   = $companyinfo->shipping_city;
                $data['shipping_state']  = $companyinfo->shipping_state;
                $data['shipping_zip']    = $companyinfo->shipping_zip;
                $data['number']          = get_option('next_invoice_number');
                $data['date']            = date("Y-m-d");
                $data['duedate']         = date('Y-m-d', strtotime(date("Y-m-d") . ' + 1 month'));
                $data['tags'] = '';
                $data['allowed_payment_modes'] = array(1, 'stripe_ach', 'authorize_aim', 'stripe');
                $data['currency'] = 1;
                $data['sale_agent'] = '';

                $data['discount_type'] = NULL;
                $data['repeat_every_custom'] = 1;
                $data['repeat_type_custom'] = 'day';
                $data['adminnote'] = NULL;

                $data['show_quantity_as'] = 1;

                $data['quantity'] = 1;



                $strsubtotal = 0;


                foreach ($item_quantities as $key => $item_quantity) {



                    $data['newitems'][$key]['order'] = 1;
                    $data['newitems'][$key]['description'] = $item_names[$key];
                    $data['newitems'][$key]['long_description'] = NULL;
                    $data['newitems'][$key]['qty'] = $item_quantity;
                    $data['newitems'][$key]['unit'] = null;
                    $data['newitems'][$key]['rate'] = $rates[$key];


                    $strsubtotal += $item_quantity * $rates[$key];
                }


                $data['subtotal'] = $strsubtotal;
                $data['discount_percent'] = 0;
                $data['discount_total'] = 0.00;
                $data['adjustment'] = 0.0;
                $data['total'] = $strsubtotal;



                $this->load->model('invoices_model');
                $id = $this->invoices_model->add($data);


                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    // add a new customer
    public function customer()

    {

        $posted_data = json_decode(file_get_contents('php://input'));
        file_put_contents('zapier.json', file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {



                $data["company"] = $posted_data->company;
                $data["vat"] = "";
                $data["phonenumber"] = $posted_data->phone;
                $data["website"] = $posted_data->website;
                $data["default_currency"] = "";
                $data["default_language"] = "";
                $data["address"] = $posted_data->address;
                $data["city"] = "";
                $data["state"] = "";
                $data["zip"] = "";
                $data["country"] = "";
                $data["billing_street"] = "";
                $data["billing_city"] = "";
                $data["billing_state"] = "";
                $data["billing_zip"] = "";
                $data["billing_country"] = "";
                $data["shipping_street"] = "";
                $data["shipping_city"] = "";
                $data["shipping_state"] = "";
                $data["shipping_zip"] = "";
                $data["shipping_country"] = "";
                //Add new customer
                $this->load->model('clients_model');
                $customer_id = $this->clients_model->add($data);
                $assign['customer_admins']   = [];
                //Assign admin
                $assign['customer_admins'][] = get_staff_user_id();
                $this->clients_model->assign_admins($assign, $customer_id);




                $data['customer_id'] = $customer_id;
                $contact = [];
                $contact["firstname"] = $posted_data->company;
                $contact["lastname"] = " ";
                $contact["title"] = "";
                $contact["email"] = $posted_data->email;
                $contact["phonenumber"] = $posted_data->phone;
                $contact["direction"] = "";


                $contact["fakeusernameremembered"] = $posted_data->username;
                $contact["fakepasswordremembered"] = $posted_data->password;
                $contact["password"] = $posted_data->password;
                $contact["is_primary"] = "on";
                $contact["permissions"] = array("1", "2", "3", "4", "5", "6");

                $contact["invoice_emails"] = "invoice_emails";
                $contact["estimate_emails"] = "estimate_emails";
                $contact["credit_note_emails"] = "credit_note_emails";
                $contact["project_emails"] = "project_emails";
                $contact["ticket_emails"] = "ticket_emails";
                $contact["task_emails"] = "task_emails";
                $contact["contract_emails"] = "contract_emails";
                // Add compnay primary contact
                $id      = $this->clients_model->add_contact($contact, $customer_id);

                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    //create a new event 
    public function event()
    {

        $posted_data = json_decode(file_get_contents('php://input'));
        file_put_contents('zapier.json', file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {

                $data["title"] = $posted_data->title;
                $data["description"] = $posted_data->description;
                $data["start"] = date('Y-m-d H:i');
                $data["end"] = "";
                $data["reminder_before"] = 30;
                $data["reminder_before_type"] = "minutes";
                $data["color"] = "#28B8DA";
                $this->load->model('utilities_model');
                $this->utilities_model->event($data);
                $id = $this->db->insert_id();
                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    // create a new item
    public function item()
    {
        $posted_data = json_decode(file_get_contents('php://input'));
        file_put_contents('zapier.json', file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {

                $data["itemid"] = "";
                $data["description"] = $posted_data->description;
                $data["long_description"] = $posted_data->long_description;
                $data["rate"] = $posted_data->rate;
                $data["tax"] = "";
                $data["unit"] = "";
                $data["custom_fields"] = array();
                $data["group_id"] = "";
                $this->load->model('invoice_items_model');
                $imagename = "";
                $id = $this->invoice_items_model->add($data, $imagename);


                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    // Add new announcement
    public function announcement()
    {
        $posted_data = json_decode(file_get_contents('php://input'));
        file_put_contents('zapier.json', file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {



                $data["name"] = $posted_data->subject;
                $data["message"] = $posted_data->message;
                $data["showtostaff"] = "on";

                $this->load->model('announcements_model');

                $id = $this->announcements_model->add($data);





                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    // Add new ticket
    public function ticket()
    {
        $posted_data = json_decode(file_get_contents('php://input'));
        file_put_contents('zapier.json', file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {


                $data["subject"] = $posted_data->subject;
                $data["contactid"] = get_primery_contact_id($posted_data->email);
                $data["userid"] = get_company($posted_data->email);
                $data["department"] = get_option("ticket_department");
                $data["cc"] = "";
                $data["tags"] = "";
                $data["assigned"] = get_option("ticket_lead_assigned");
                $data["priority"] = 2;
                $data["service"] = "";
                $data["project_id"] = "";
                $data["message"] = "";


                $id = $this->add_ticket($data, 1);
                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
    /**
     * Add new ticket to database
     * @param mixed $data  ticket $_POST data
     * @param mixed $admin If admin adding the ticket passed staff id
     */
    public function add_ticket($data, $admin = null, $pipe_attachments = false)
    {
        $this->load->model('tickets_model');
        if ($admin !== null) {
            $data['admin'] = $admin;
            unset($data['ticket_client_search']);
        }

        if (isset($data['assigned']) && $data['assigned'] == '') {
            $data['assigned'] = 0;
        }

        if (isset($data['project_id']) && $data['project_id'] == '') {
            $data['project_id'] = 0;
        }

        if ($admin == null) {
            if (isset($data['email'])) {
                $data['userid']    = 0;
                $data['contactid'] = 0;
            } else {
                // Opened from customer portal otherwise is passed from pipe or admin area
                if (!isset($data['userid']) && !isset($data['contactid'])) {
                    $data['userid']    = get_client_user_id();
                    $data['contactid'] = get_contact_user_id();
                }
            }
            $data['status'] = 1;
        }

        if (isset($data['custom_fields'])) {
            $custom_fields = $data['custom_fields'];
            unset($data['custom_fields']);
        }

        // CC is only from admin area
        $cc = '';
        if (isset($data['cc'])) {
            $cc = $data['cc'];
            unset($data['cc']);
        }

        $data['date']      = date('Y-m-d H:i:s');
        $data['ticketkey'] = md5(uniqid(time(), true));
        $data['status']    = 1;
        $data['message']   = trim($data['message']);
        $data['subject']   = trim($data['subject']);
        $data['message'] = preg_replace('/\v+/u', '<br>', $data['message']);
        // Admin can have html
        if ($admin == null) {
            $data['message'] = _strip_tags($data['message']);
            $data['subject'] = _strip_tags($data['subject']);
            $data['message'] = nl2br_save_html($data['message']);
        }
        if (!isset($data['userid'])) {
            $data['userid'] = 0;
        }
        if (isset($data['priority']) && $data['priority'] == '' || !isset($data['priority'])) {
            $data['priority'] = 0;
        }

        $tags = '';
        if (isset($data['tags'])) {
            $tags = $data['tags'];
            unset($data['tags']);
        }

        $data = hooks()->apply_filters('before_ticket_created', $data, $admin);

        $this->db->insert(db_prefix() . 'tickets', $data);
        $ticketid = $this->db->insert_id();
        if ($ticketid) {
            handle_tags_save($tags, $ticketid, 'ticket');

            if (isset($custom_fields)) {
                handle_custom_fields_post($ticketid, $custom_fields);
            }

            if (isset($data['assigned']) && $data['assigned'] != 0) {
                if ($data['assigned'] != get_staff_user_id()) {
                    $notified = add_notification([
                        'description'     => 'not_ticket_assigned_to_you',
                        'touserid'        => $data['assigned'],
                        'fromcompany'     => 1,
                        'fromuserid'      => null,
                        'link'            => 'tickets/ticket/' . $ticketid,
                        'additional_data' => serialize([
                            $data['subject'],
                        ]),
                    ]);

                    if ($notified) {
                        pusher_trigger_notification([$data['assigned']]);
                    }

                    $this->db->where('staffid', $data['assigned']);
                    $assignedEmail = $this->db->get(db_prefix() . 'staff')->row()->email;
                    send_mail_template('ticket_assigned_to_staff', $assignedEmail, $data['assigned'], $ticketid, $data['userid'], $data['contactid']);
                }
            }
            if ($pipe_attachments != false) {
                $this->tickets_model->process_pipe_attachments($pipe_attachments, $ticketid);
            } else {
                $attachments = handle_ticket_attachments($ticketid);
                if ($attachments) {
                    $this->tickets_model->insert_ticket_attachments_to_database($attachments, $ticketid);
                }
            }

            $_attachments = $this->tickets_model->get_ticket_attachments($ticketid);


            $isContact = false;
            if (isset($data['userid']) && $data['userid'] != false) {
                $email     = $this->clients_model->get_contact($data['contactid'])->email;
                $isContact = true;
            } else {
                $email = $data['email'];
            }

            $template = 'ticket_created_to_customer';
            if ($admin == null) {
                $template = 'ticket_autoresponse';

                $this->load->model('departments_model');
                $this->load->model('staff_model');
                $staff = $this->staff_model->get('', ['active' => 1]);

                $notifiedUsers                              = [];
                $notificationForStaffMemberOnTicketCreation = get_option('receive_notification_on_new_ticket') == 1;

                foreach ($staff as $member) {
                    if (
                        get_option('access_tickets_to_none_staff_members') == 0
                        && !is_staff_member($member['staffid'])
                    ) {
                        continue;
                    }
                    $staff_departments = $this->departments_model->get_staff_departments($member['staffid'], true);

                    if (in_array($data['department'], $staff_departments)) {
                        send_mail_template('ticket_created_to_staff', $ticketid, $data['userid'], $data['contactid'], $member, $_attachments);

                        if ($notificationForStaffMemberOnTicketCreation) {
                            $notified = add_notification([
                                'description'     => 'not_new_ticket_created',
                                'touserid'        => $member['staffid'],
                                'fromcompany'     => 1,
                                'fromuserid'      => null,
                                'link'            => 'tickets/ticket/' . $ticketid,
                                'additional_data' => serialize([
                                    $data['subject'],
                                ]),
                            ]);
                            if ($notified) {
                                array_push($notifiedUsers, $member['staffid']);
                            }
                        }
                    }
                }
                pusher_trigger_notification($notifiedUsers);
            }

            $sendEmail = true;

            if ($isContact && total_rows(db_prefix() . 'contacts', ['ticket_emails' => 1, 'id' => $data['contactid']]) == 0) {
                $sendEmail = false;
            }

            if ($sendEmail) {
                $ticket = $this->tickets_model->get_ticket_by_id($ticketid);
                // $admin == null ? [] : $_attachments - Admin opened ticket from admin area add the attachments to the email
                send_mail_template($template, $ticket, $email, $admin == null ? [] : $_attachments, $cc);
            }

            hooks()->do_action('ticket_created', $ticketid);
            log_activity('New Ticket Created [ID: ' . $ticketid . ']');

            return $ticketid;
        }

        return false;
    }
    // Create a new project
    public function project()
    {

        $posted_data = json_decode(file_get_contents('php://input'));
        file_put_contents('zapier.json', file_get_contents('php://input'));

        if ($posted_data) {
            if ($this->validate_user($posted_data->username, $posted_data->password)) {

                $data["name"] = $posted_data->name;
                $data["clientid"] = get_company($posted_data->email);
                $data["progress_from_tasks"] = "on";
                $data["progress"] = 0;
                $data["billing_type"] = get_option('projects_billing_type');
                $data["status"] = 2;
                $data["project_cost"] = "";
                $data["project_rate_per_hour"] = "";
                $data["estimated_hours"] = "";
                $data["project_members"] = unserialize(get_option("project_view_assigned"));

                $data["start_date"] = date('Y-m-d');
                $data["deadline"] = "";
                $data["tags"] = "";
                $data["description"] = "";
                $data["settings"] = array(
                    "available_features" => array(
                        "project_overview", "project_tasks", "project_timesheets", "project_milestones", "project_files", "project_discussions", "project_gantt", "project_tickets",                   "project_invoices", "project_estimates", "project_expenses", "project_credit_notes",          "project_subscriptions", "project_notes", "project_activity"
                    ),

                    "view_tasks" => "on",
                    "create_tasks" => "on",
                    "edit_tasks" => "on",
                    "comment_on_tasks" => "on",
                    "view_task_comments" => "on",
                    "view_task_attachments" => "on",
                    "view_task_checklist_items" => "on",
                    "upload_on_tasks" => "on",
                    "view_task_total_logged_time" => "on",
                    "view_finance_overview" => "on",
                    "upload_files" => "on",
                    "open_discussions" => "on",
                    "view_milestones" => "on",
                    "view_gantt" => "on",
                    "view_timesheets" => "on",
                    "view_activity_log" => "on",
                    "view_team_members" => "on",
                );
                $this->load->model('projects_model');
                $id = $this->projects_model->add($data);
                $posted_data->id = $id;
                unset($posted_data->username);
                unset($posted_data->password);
                print_r(json_encode($posted_data));
            } else {
                redirect(admin_url());
            }
        } else {
            redirect(admin_url());
        }
    }
}
