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

require(APPPATH.'/libraries/REST_Controller.php');
use Restserver\Libraries\REST_Controller;
require APPPATH . 'libraries/Format.php';

class Admin_Api extends REST_Controller {

    public function __construct() {
        parent::__construct();
        
        $this->load->model('Admin_model');
        $this->load->model('Total_model');
        $this->load->helper('reusable');
    }

    public function dashboard_get() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_id = isset($verify_data['userdata']['id']) ? $verify_data['userdata']['id'] : '';
        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $total_users = $this->Admin_model->get_total_users();
        $total_affiliates = $this->Admin_model->get_total_affiliates();
        $total_vendors = $this->Admin_model->get_total_vendors();
        $pending_users = $this->Admin_model->get_pending_users();

        $pending_withdrawals = $this->Admin_model->get_pending_withdrawals_count();
        $total_withdrawals_amount = $this->Admin_model->get_total_withdrawals_amount();

        $today_clicks = $this->Admin_model->get_today_clicks();
        $today_sales = $this->Admin_model->get_today_sales();

        $recent_users = $this->Admin_model->get_recent_users(5);

        $admin_totals = $this->Total_model->adminTotals();
        $admin_balance = isset($admin_totals['admin_balance']) ? (float)$admin_totals['admin_balance'] : 0;
        $admin_balance_growth = isset($admin_totals['admin_balance_growth']) ? (float)$admin_totals['admin_balance_growth'] : 0;

        $store_sales = number_format((float)($admin_totals['sale_localstore_total'] ?? 0), 2, '.', '');
        $store_commission = number_format((float)($admin_totals['sale_localstore_commission'] ?? 0), 2, '.', '');
        $store_orders = (int)($admin_totals['sale_localstore_count'] ?? 0);

        $vendor_sales = number_format((float)($admin_totals['sale_localstore_vendor_total'] ?? 0), 2, '.', '');
        $vendor_commission = number_format((float)($admin_totals['sale_localstore_vendor_commission'] ?? 0), 2, '.', '');
        $vendor_orders = (int)($admin_totals['sale_localstore_vendor_count'] ?? 0);

        $click_commission = number_format(
            (float)(($admin_totals['click_localstore_commission'] ?? 0) + ($admin_totals['click_integration_commission'] ?? 0) + ($admin_totals['click_form_commission'] ?? 0)),
            2, '.', ''
        );
        $total_clicks = (int)(($admin_totals['click_localstore_total'] ?? 0) + ($admin_totals['click_integration_total'] ?? 0) + ($admin_totals['click_form_total'] ?? 0));

        $data = array_merge(array(
            'total_users' => (int)$total_users,
            'total_affiliates' => (int)$total_affiliates,
            'total_vendors' => (int)$total_vendors,
            'pending_users' => (int)$pending_users,
            'pending_withdrawals' => (int)$pending_withdrawals,
            'total_withdrawals_amount' => number_format((float)$total_withdrawals_amount, 2, '.', ''),
            'admin_balance' => number_format($admin_balance, 2, '.', ''),
            'admin_balance_growth' => $admin_balance_growth,
            'store_sales' => $store_sales,
            'store_commission' => $store_commission,
            'store_orders' => $store_orders,
            'vendor_sales' => $vendor_sales,
            'vendor_commission' => $vendor_commission,
            'vendor_orders' => $vendor_orders,
            'click_commission' => $click_commission,
            'total_clicks' => $total_clicks,
            'today_clicks' => (int)$today_clicks,
            'today_sales' => (int)$today_sales,
            'recent_users' => $recent_users,
        ), get_currency_settings());

        $json = array(
            'status' => TRUE,
            'data' => $data,
        );

        $this->response($json, REST_Controller::HTTP_OK);
    }

    public function users_get() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $start_from = $this->get('start_from') ?? 0;
        $limit = $this->get('limit') ?? 20;
        $search = $this->get('search') ?? '';
        $status_filter = $this->get('status') ?? 'all';

        $where = "type='user'";
        
        if ($status_filter == 'active') {
            $where .= " AND status='1'";
        } elseif ($status_filter == 'pending') {
            $where .= " AND status='0' AND reg_approved='0'";
        } elseif ($status_filter == 'blocked') {
            $where .= " AND status='0'";
        }

        if (!empty($search)) {
            $search_escaped = $this->db->escape_like_str($search);
            $where .= " AND (username LIKE '%{$search_escaped}%' OR email LIKE '%{$search_escaped}%' OR firstname LIKE '%{$search_escaped}%' OR lastname LIKE '%{$search_escaped}%')";
        }

        $total_count = $this->Admin_model->get_users_count($where);
        $users = $this->Admin_model->get_users($where, $start_from, $limit);

        foreach ($users as &$user) {
            $balance = $this->Total_model->getUserBalance($user['id']);
            $user['balance'] = number_format((float)$balance, 2, '.', '');
            
            $user['total_clicks'] = $this->Admin_model->get_user_clicks($user['id']);
            $user['total_sales'] = $this->Admin_model->get_user_sales($user['id']);
            $user['created_date'] = $user['created_at']; // Add for compatibility
        }

        $data = array_merge(array(
            'users' => $users,
            'total_count' => (int)$total_count,
            'start_from' => (int)$start_from,
            'limit' => (int)$limit,
            'has_more' => ($start_from + $limit) < $total_count,
        ), get_currency_settings());

        $json = array(
            'status' => TRUE,
            'data' => $data,
        );

        $this->response($json, REST_Controller::HTTP_OK);
    }

    public function withdrawals_get() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $start_from = $this->get('start_from') ?? 0;
        $limit = $this->get('limit') ?? 20;
        $status_filter = $this->get('status') ?? 'unpaid';

        $where = "1=1";
        
        if ($status_filter == 'unpaid') {
            $where .= " AND wr.status='0'";
        } elseif ($status_filter == 'paid') {
            $where .= " AND wr.status='1'";
        } elseif ($status_filter == 'rejected') {
            $where .= " AND wr.status IN ('3','4')";
        }

        $total_count = $this->Admin_model->get_withdrawals_count($where);
        $requests = $this->Admin_model->get_withdrawals($where, $start_from, $limit);

        $status_labels = array(
            '0' => 'Received',
            '1' => 'Paid',
            '2' => 'Processing',
            '3' => 'Cancelled',
            '4' => 'Declined',
        );

        foreach ($requests as &$row) {
            $row['status_label'] = isset($status_labels[$row['status']]) ? $status_labels[$row['status']] : 'Unknown';

            if (!empty($row['settings'])) {
                $parsed = @json_decode($row['settings'], true);
                if (is_array($parsed)) {
                    $row['payment_details'] = $parsed;
                }
            }
            unset($row['settings']);
        }
        unset($row);

        $data = array_merge(array(
            'requests' => $requests,
            'total_count' => (int)$total_count,
            'start_from' => (int)$start_from,
            'limit' => (int)$limit,
            'has_more' => ($start_from + $limit) < $total_count,
        ), get_currency_settings());

        $json = array(
            'status' => TRUE,
            'data' => $data,
        );

        $this->response($json, REST_Controller::HTTP_OK);
    }

    public function update_withdrawal_status_post() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $request_id = $this->post('request_id');
        $status = $this->post('status'); // 'paid' or 'rejected'
        $admin_note = $this->post('admin_note') ?? '';

        if (empty($request_id) || empty($status)) {
            $response = array(
                'status' => FALSE,
                'message' => 'Request ID and status are required',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $status_code = ($status === 'paid') ? 1 : 4;

        $existing = $this->Admin_model->get_withdrawal_by_id($request_id);
        if (!$existing) {
            $response = array(
                'status' => FALSE,
                'message' => 'Withdrawal request not found',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $this->load->model('Withdrawal_payment_model');
        $this->Withdrawal_payment_model->apiAddWithdrwalRequestHistory((int)$request_id, [
            'status_id'      => $status_code,
            'comment'        => $admin_note,
            'transaction_id' => '',
        ]);

        $message = ($status === 'paid')
            ? 'Withdrawal request approved successfully'
            : 'Withdrawal request rejected successfully';

        $response = array(
            'status' => TRUE,
            'message' => $message,
        );
        $this->response($response, REST_Controller::HTTP_OK);
    }

    public function user_details_get() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_id = $this->get('user_id');

        if (empty($user_id)) {
            $response = array(
                'status' => FALSE,
                'message' => 'User ID is required',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user = $this->Admin_model->get_user_by_id($user_id);

        if (empty($user)) {
            $response = array(
                'status' => FALSE,
                'message' => 'User not found',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $balance = $this->Total_model->getUserBalance($user_id);
        $user['balance'] = number_format((float)$balance, 2, '.', '');

        $total_clicks = $this->db->query("SELECT COUNT(*) as count FROM product_action WHERE user_id='{$user_id}'")->row()->count;
        $user['total_clicks'] = (int)($total_clicks ?? 0);

        $total_sales = $this->db->query("SELECT COUNT(*) as count FROM `order` WHERE user_id='{$user_id}'")->row()->count;
        $user['total_sales'] = (int)($total_sales ?? 0);

        $total_revenue = $this->db->query("SELECT SUM(total) as total FROM `order` WHERE user_id='{$user_id}'")->row()->total ?? 0;
        $user['total_revenue'] = number_format((float)$total_revenue, 2, '.', '');

        $referrals = $this->db->query("SELECT COUNT(*) as count FROM users WHERE refid='{$user_id}'")->row()->count;
        $user['total_referrals'] = (int)($referrals ?? 0);

        $recent_clicks = $this->db->query("SELECT action_id as id, product_id, created_at FROM product_action WHERE user_id='{$user_id}' ORDER BY created_at DESC LIMIT 10")->result_array();
        $user['recent_clicks'] = $recent_clicks;

        $recent_sales = $this->db->query("SELECT id, total, status, created_at FROM `order` WHERE user_id='{$user_id}' ORDER BY created_at DESC LIMIT 10")->result_array();
        $user['recent_sales'] = $recent_sales;

        unset($user['password']);

        $user = array_merge($user, get_currency_settings());

        $json = array(
            'status' => TRUE,
            'data' => $user,
        );

        $this->response($json, REST_Controller::HTTP_OK);
    }

    public function update_user_status_post() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_id = $this->post('user_id');

        if (empty($user_id)) {
            $response = array(
                'status' => FALSE,
                'message' => 'user_id is required',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_id = (int)$user_id;
        $this->db->query("UPDATE users SET status = IF(status=1,0,1) WHERE id={$user_id} AND type='user'");
        $affected = $this->db->affected_rows();

        if ($affected > 0) {
            $new_status = $this->db->query("SELECT status FROM users WHERE id={$user_id}")->row()->status;
            $status_text = ($new_status == 1) ? 'enabled' : 'disabled';
            $json = array(
                'status' => TRUE,
                'message' => "User status {$status_text} successfully",
                'new_status' => (int)$new_status,
            );
        } else {
            $json = array(
                'status' => FALSE,
                'message' => 'User not found or status unchanged',
            );
        }

        $this->response($json, REST_Controller::HTTP_OK);
    }

    public function reports_get() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $date_from = $this->get('date_from') ?? date('Y-m-01');
        $date_to = $this->get('date_to') ?? date('Y-m-d');

        $clicks_by_day = $this->db->query("
            SELECT DATE(created_at) as date, COUNT(*) as count 
            FROM product_action 
            WHERE DATE(created_at) BETWEEN ? AND ?
            GROUP BY DATE(created_at) 
            ORDER BY date ASC
        ", array($date_from, $date_to))->result_array();

        $sales_by_day = $this->db->query("
            SELECT DATE(created_at) as date, COUNT(*) as count, SUM(total) as total 
            FROM `order` 
            WHERE DATE(created_at) BETWEEN ? AND ?
            GROUP BY DATE(created_at) 
            ORDER BY date ASC
        ", array($date_from, $date_to))->result_array();

        $top_affiliates = $this->db->query("
            SELECT users.id, users.firstname, users.lastname, users.username, 
                   COUNT(`order`.id) as total_sales, 
                   SUM(`order`.total) as total_revenue 
            FROM users 
            LEFT JOIN `order` ON users.id = `order`.user_id 
            WHERE users.type='user' AND `order`.created_at BETWEEN ? AND ?
            GROUP BY users.id 
            ORDER BY total_revenue DESC 
            LIMIT 10
        ", array($date_from, $date_to))->result_array();

        $data = array_merge(array(
            'date_from' => $date_from,
            'date_to' => $date_to,
            'clicks_by_day' => $clicks_by_day,
            'sales_by_day' => $sales_by_day,
            'top_affiliates' => $top_affiliates,
        ), get_currency_settings());

        $json = array(
            'status' => TRUE,
            'data' => $data,
        );

        $this->response($json, REST_Controller::HTTP_OK);
    }

    public function wallet_get() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $response = array(
                'status' => FALSE,
                'message' => 'Unauthorized Access!',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $response = array(
                'status' => FALSE,
                'message' => 'Access Denied! Admin only.',
            );
            $this->response($response, REST_Controller::HTTP_OK);
            return;
        }

        $admin_totals = $this->Total_model->adminTotals();
        
        $this->load->model('Wallet_model');
        $filter = array(
            'status_gt' => 0,
            'parent_id' => 0,
            'not_negative_balence' => true,
            'page_num' => 1,
            'per_page' => 50,
            'offset' => 0,
        );
        
        $transactions = $this->Wallet_model->getTransaction($filter, false, 'ONLY_PARENTS');

        $data = array_merge(array(
            'admin_balance' => number_format((float)$admin_totals['admin_balance'], 2, '.', ''),
            'sale_localstore_total' => number_format((float)$admin_totals['sale_localstore_total'], 2, '.', ''),
            'sale_localstore_vendor_total' => number_format((float)$admin_totals['sale_localstore_vendor_total'], 2, '.', ''),
            'order_external_total' => number_format((float)$admin_totals['order_external_total'], 2, '.', ''),
            'click_action_total' => (int)$admin_totals['click_action_total'],
            'click_action_commission' => number_format((float)$admin_totals['click_action_commission'], 2, '.', ''),
            'click_localstore_total' => (int)$admin_totals['click_localstore_total'],
            'click_integration_total' => (int)$admin_totals['click_integration_total'],
            'click_form_total' => (int)$admin_totals['click_form_total'],
            'click_localstore_commission' => number_format((float)$admin_totals['click_localstore_commission'], 2, '.', ''),
            'click_integration_commission' => number_format((float)$admin_totals['click_integration_commission'], 2, '.', ''),
            'click_form_commission' => number_format((float)$admin_totals['click_form_commission'], 2, '.', ''),
            'transactions' => $transactions,
        ), get_currency_settings());

        $json = array(
            'status' => TRUE,
            'data' => $data,
        );

        $this->response($json, REST_Controller::HTTP_OK);
    }

    public function profile_get() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $this->response(array('status' => FALSE, 'message' => 'Unauthorized Access!'), REST_Controller::HTTP_OK);
            return;
        }

        $user_id = isset($verify_data['userdata']['id']) ? $verify_data['userdata']['id'] : '';
        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $this->response(array('status' => FALSE, 'message' => 'Access Denied! Admin only.'), REST_Controller::HTTP_OK);
            return;
        }

        $this->load->model('user_model', 'user');
        $user = $this->user->get_user_by_id($user_id);

        if (empty($user)) {
            $this->response(array('status' => FALSE, 'message' => 'Admin not found'), REST_Controller::HTTP_OK);
            return;
        }

        $phone_val = !empty($user['PhoneNumber']) ? $user['PhoneNumber'] : (!empty($user['phone']) ? $user['phone'] : '');
        $city_val = !empty($user['City']) ? $user['City'] : (!empty($user['ucity']) ? $user['ucity'] : '');
        $zip_val = !empty($user['Zip']) ? $user['Zip'] : (!empty($user['uzip']) ? $user['uzip'] : '');
        $country_id = !empty($user['Country']) ? $user['Country'] : (!empty($user['ucountry']) ? $user['ucountry'] : '');

        $country_code = '';
        $country_name = '';
        $country_flag = '';
        if (!empty($country_id)) {
            $country_data = $this->db->query("SELECT sortname, name FROM countries WHERE id = ?", array($country_id))->row();
            if ($country_data) {
                $country_code = $country_data->sortname;
                $country_name = $country_data->name;
                $country_flag = base_url('assets/vertical/assets/images/flags/' . strtolower($country_code) . '.png');
            }
        }

        $this->load->model('Product_model');
        $countries_raw = $this->Product_model->getcountry();
        $countries_list = array();
        if (!empty($countries_raw)) {
            foreach ($countries_raw as $c) {
                $countries_list[] = array('id' => $c->id, 'name' => $c->name);
            }
        }

        $response = array(
            'status' => TRUE,
            'message' => 'Admin profile loaded successfully',
            'data' => array(
                'firstname' => $user['firstname'],
                'lastname' => $user['lastname'],
                'email' => $user['email'],
                'username' => $user['username'],
                'PhoneNumber' => $phone_val,
                'city' => $city_val,
                'pincode' => $zip_val,
                'country_id' => $country_id,
                'country_code' => $country_code,
                'country_name' => $country_name,
                'country_flag' => $country_flag,
                'profile_avatar' => (!empty($user['avatar'])) ? base_url('assets/images/users/' . $user['avatar']) : base_url('assets/vertical/assets/images/no-image.jpg'),
                'role' => $user['type'],
                'countries' => $countries_list,
            )
        );

        $this->response($response, REST_Controller::HTTP_OK);
    }

    public function update_profile_post() {
        $verify_data = verify_request();

        if (isset($verify_data['status']) && $verify_data['status'] == 401) {
            $this->response(array('status' => FALSE, 'message' => 'Unauthorized Access!'), REST_Controller::HTTP_OK);
            return;
        }

        $user_id = isset($verify_data['userdata']['id']) ? $verify_data['userdata']['id'] : '';
        $user_type = isset($verify_data['userdata']['type']) ? $verify_data['userdata']['type'] : '';

        if ($user_type !== 'admin') {
            $this->response(array('status' => FALSE, 'message' => 'Access Denied! Admin only.'), REST_Controller::HTTP_OK);
            return;
        }

        $this->load->model('user_model', 'user');

        $updateArray = array(
            'firstname' => $this->input->post('firstname', true),
            'lastname'  => $this->input->post('lastname', true),
            'email'     => $this->input->post('email', true),
        );

        $phone = $this->input->post('phone', true);
        if ($phone !== null) {
            $updateArray['PhoneNumber'] = $phone;
            $updateArray['phone'] = $phone;
        }

        $country_id = $this->input->post('country_id', true);
        if ($country_id !== null) {
            $updateArray['Country'] = $country_id;
            $updateArray['ucountry'] = $country_id;
        }

        $city = $this->input->post('city', true);
        if ($city !== null) {
            $updateArray['City'] = $city;
            $updateArray['ucity'] = $city;
        }

        $pincode = $this->input->post('pincode', true);
        if ($pincode !== null) {
            $updateArray['Zip'] = $pincode;
            $updateArray['uzip'] = $pincode;
        }

        $password = $this->input->post('password', true);
        if (!empty($password)) {
            $updateArray['password'] = sha1($password);
        }

        if (!empty($_FILES['avatar']['name'])) {
            $config['upload_path'] = 'assets/images/users';
            $config['allowed_types'] = 'png|gif|jpeg|jpg';
            $config['max_size'] = 2048;
            $this->load->library('upload', $config);
            if ($this->upload->do_upload('avatar')) {
                $upload_data = $this->upload->data();
                $updateArray['avatar'] = $upload_data['file_name'];
            }
        }

        $this->user->update_user($user_id, $updateArray);

        $updated_user = $this->user->get_user_by_id($user_id);

        $phone_val = !empty($updated_user['PhoneNumber']) ? $updated_user['PhoneNumber'] : (!empty($updated_user['phone']) ? $updated_user['phone'] : '');
        $city_val = !empty($updated_user['City']) ? $updated_user['City'] : (!empty($updated_user['ucity']) ? $updated_user['ucity'] : '');
        $zip_val = !empty($updated_user['Zip']) ? $updated_user['Zip'] : (!empty($updated_user['uzip']) ? $updated_user['uzip'] : '');
        $c_id = !empty($updated_user['Country']) ? $updated_user['Country'] : (!empty($updated_user['ucountry']) ? $updated_user['ucountry'] : '');

        $country_code = '';
        $country_name = '';
        $country_flag = '';
        if (!empty($c_id)) {
            $country_data = $this->db->query("SELECT sortname, name FROM countries WHERE id = ?", array($c_id))->row();
            if ($country_data) {
                $country_code = $country_data->sortname;
                $country_name = $country_data->name;
                $country_flag = base_url('assets/vertical/assets/images/flags/' . strtolower($country_code) . '.png');
            }
        }

        $response = array(
            'status' => TRUE,
            'message' => 'Profile updated successfully',
            'data' => array(
                'firstname' => $updated_user['firstname'],
                'lastname' => $updated_user['lastname'],
                'email' => $updated_user['email'],
                'username' => $updated_user['username'],
                'PhoneNumber' => $phone_val,
                'city' => $city_val,
                'pincode' => $zip_val,
                'country_id' => $c_id,
                'country_code' => $country_code,
                'country_name' => $country_name,
                'country_flag' => $country_flag,
                'profile_avatar' => (!empty($updated_user['avatar'])) ? base_url('assets/images/users/' . $updated_user['avatar']) : base_url('assets/vertical/assets/images/no-image.jpg'),
                'role' => $updated_user['type'],
            )
        );

        $this->response($response, REST_Controller::HTTP_OK);
    }

}
