https://t.me/RX1948
Server : Apache/2.4.18 (Ubuntu)
System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64
User : oppastar ( 1041)
PHP Version : 7.0.33-0ubuntu0.16.04.15
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
Directory :  /var/www/laciasmara.com/public_html/shop/application/controllers/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/laciasmara.com/public_html/shop/application/controllers/admin/Affiliator.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Affiliator extends Admin_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('affiliator_m');
        $this->load->model('product_m');
        $this->load->model('customer_m');
        $this->load->model('log_m');
    }


    function dashboard()
    {
        $data['userdata'] = $this->session->userdata();
        $data['role'] = $this->session->userdata('role');

        $data['approved_affiliate'] = $this->affiliator_m->count_approved_affiliate(); // Count active affiliate
        $data['pending_affiliate'] = $this->affiliator_m->count_pending_affiliate(); // Count pending affiliate
        $data['rejected_affiliate'] = $this->affiliator_m->count_rejected_affiliate(); // Count rejected affiliate

        $data['affiliate_transactions'] = $this->affiliator_m->count_affiliate_transactions(); // Count transaction using affiliate referral code
        $data['paid_commission'] = $this->affiliator_m->get_paid_commission(); // Count transaction using affiliate referral code
        $data['top_affiliate'] = $this->affiliator_m->get_best_affiliate();


        $data['title'] = 'Dashboard Afiliasi | Laciasmara';

        $this->load->view('admin_new/layouts/header', $data);
        $this->load->view('admin_new/affiliate/index');
        $this->load->view('admin_new/layouts/footer');
    }

    function transactions()
    {
        $data['userdata'] = $this->session->userdata();
        $data['title'] = 'Transaksi Afiliasi | Laciasmara';
        $data['affiliates'] = $this->affiliator_m->fetch_all_affiliates();


        $this->load->view('admin_new/layouts/header', $data);
        $this->load->view('admin_new/affiliate/transaksi');
        $this->load->view('admin_new/layouts/footer');
    }

    public function manage()
    {
        $data['userdata'] = $this->session->userdata();
        $data['title'] = 'Daftar Affiliate | Laciasmara';

        $this->load->view('admin_new/layouts/header', $data);
        $this->load->view('admin_new/affiliate/manage');
        $this->load->view('admin_new/layouts/footer');
    }

    public function add()
    {

        $data['userdata'] = $this->session->userdata();
        $data['title'] = 'Tambah Affiliate | Laciasmara';
        $data['customers'] = $this->customer_m->fetch_all_customers();

        $this->load->view('admin_new/layouts/header', $data);
        $this->load->view('admin_new/affiliate/add');
        $this->load->view('admin_new/layouts/footer');
    }
    public function commission()
    {
        $data['userdata'] = $this->session->userdata();
        $data['title'] = 'Laporan Komisi | Laciasmara';

        $this->load->view('admin_new/layouts/header', $data);
        $this->load->view('admin_new/affiliate/commission');
        $this->load->view('admin_new/layouts/footer');
    }

    public function detail($id_affiliate = NULL)
    {
        if (!$id_affiliate) {
            redirect('admin/affiliate/manage');
        }
        $data['userdata'] = $this->session->userdata();
        $data['title'] = 'Detail Affiliate | Laciasmara';

        // Fetch data order
        $data['affiliate'] = $this->affiliator_m->fetch_affiliate_data($id_affiliate);
        if (!$data['affiliate']) {
            $this->session->set_flashdata('message', 'Affiliate ID tidak ditemukan.');
            $this->session->set_flashdata('message_type', 'error');
            redirect('admin/affiliate/manage');
        }

        $this->load->view('admin_new/layouts/header', $data);
        $this->load->view('admin_new/affiliate/detail');
        $this->load->view('admin_new/layouts/footer');
    }

    public function get_affiliate_orders()
    {
        // Get filter parameters
        $tab = $this->input->get('tab', true);
        $sort = $this->input->get('sort', true);
        $dateFilter = $this->input->get('date_filter', true);
        $startDate = $this->input->get('start_date', true);
        $endDate = $this->input->get('end_date', true);
        $isAsmaradoor = filter_var($this->input->get('isAsmaradoor', true), FILTER_VALIDATE_BOOLEAN);
        $isAsmarasana = filter_var($this->input->get('isAsmarasana', true), FILTER_VALIDATE_BOOLEAN);

        $isBCATransfer = filter_var($this->input->get('isBCATransfer', true), FILTER_VALIDATE_BOOLEAN);
        $isMandiriTransfer = filter_var($this->input->get('isMandiriTransfer', true), FILTER_VALIDATE_BOOLEAN);
        $isPaypal = filter_var($this->input->get('isPaypal', true), FILTER_VALIDATE_BOOLEAN);
        $isDoku = filter_var($this->input->get('isDoku', true), FILTER_VALIDATE_BOOLEAN);

        $isRegularShipping = filter_var($this->input->get('isRegularShipping', true), FILTER_VALIDATE_BOOLEAN);
        $isTwoHourShipping = filter_var($this->input->get('isTwoHourShipping', true), FILTER_VALIDATE_BOOLEAN);
        $isOneDayShipping = filter_var($this->input->get('isOneDayShipping', true), FILTER_VALIDATE_BOOLEAN);
        $isNextDayShipping = filter_var($this->input->get('isNextDayShipping', true), FILTER_VALIDATE_BOOLEAN);

        $page = (int) ($this->input->get('page', true) ?? 1);
        $limit = (int) ($this->input->get('limit', true) ?? 10);
        $offset = ($page - 1) * $limit;

        $searchTerm = $this->input->get('search', true);
        $affiliateIds = $this->input->get('affiliateId', true);

        // Build main query
        $this->db->select('
            o.id_orders, 
            o.customer_id, 
            o.order_date, 
            o.payment_status, 
            o.payment_confirm, 
            o.grand_total_amount, 
            o.payment_type, 
            o.recipient_name, 
            o.address, 
            o.district, 
            o.subdistrict, 
            o.province, 
            o.phone, 
            o.email, 
            o.redeemed_voucher_code, 
            o.redeemed_voucher_type, 
            o.redeemed_voucher_value, 
            o.redeemed_voucher_amount, 
            o.shipping_fee, 
            o.customer_note,
            o.admin_note, 
            o.created_by, 
            o.admin_note, 
            o.first, 
            o.gift_receiver_name, 
            o.gift_receiver_phone, 
            o.insurance_status, 
            o.insurance_cost,
            o.source, 
            o.medium, 
            o.campaign, 
            o.tokopedia_invoice, 
            o.no_resi
        ');
        $this->db->from('orders o');

        // Get list of affiliate referral codes if affiliateIds is provided
        if ($affiliateIds) {
            $affiliateIdArray = explode(',', $affiliateIds);
            if (!empty($affiliateIdArray)) {
                $this->db->join('affiliator_register ar', 'o.redeemed_voucher_code = ar.referral OR o.source = ar.referral OR o.referral = ar.referral', 'inner');
                $this->db->where_in('ar.id_daftar', $affiliateIdArray);
            }
        } else {
            // If no specific affiliateIds, get all orders with any affiliate referral code
            $this->db->join('affiliator_register ar', 'o.redeemed_voucher_code = ar.referral OR o.source = ar.referral OR o.referral = ar.referral', 'inner');
        }

        $kategoriConditions = [];

        if ($isAsmaradoor) {
            $kategoriConditions[] = "ar.kategori = 'asmaradoor'";
        }

        if ($isAsmarasana) {
            $kategoriConditions[] = "ar.kategori = 'asmarasana'";
        }

        // Terapkan filter kategori jika ada yang dipilih
        if (!empty($kategoriConditions)) {
            $this->db->group_start();
            $this->db->where(implode(' OR ', $kategoriConditions), null, false);
            $this->db->group_end();
        }

        // Apply filter based on tab
        if ($tab) {
            switch ($tab) {
                case 'pending':
                    $this->db->where_in('o.payment_status', [0, 1, 3]);
                    break;
                case 'cancelled':
                    $this->db->where('o.payment_status', 2);
                    break;
                case 'processing':
                    $this->db->where('o.payment_status', 4);
                    break;
                case 'done':
                    $this->db->where_in('o.payment_status', [5, 8]);
                    break;
            }
        }

        // Array untuk menyimpan kondisi pembayaran yang valid
        $paymentTypes = [];

        if ($isBCATransfer) {
            $paymentTypes[] = 'bank transfer BCA';
        }
        if ($isMandiriTransfer) {
            $paymentTypes[] = 'bank transfer MANDIRI';
        }
        if ($isPaypal) {
            $paymentTypes[] = 'Paypal';
        }
        if ($isDoku) {
            $paymentTypes[] = 'DOKU';
        }

        // Tambahkan filter shipping method di sini
        $shippingMethods = [];

        if ($isRegularShipping) {
            $shippingMethods[] = 3; // Regular shipping
        }
        if ($isTwoHourShipping) {
            $shippingMethods[] = 2; // Two hour shipping
        }
        if ($isOneDayShipping) {
            $shippingMethods[] = 1; // One day shipping
        }
        if ($isNextDayShipping) {
            $shippingMethods[] = 4; // Next day shipping
        }

        // Jika ada filter shipping method, tambahkan where clause
        if (!empty($shippingMethods)) {
            $this->db->join('orders_detail od', 'o.id_orders = od.orders_id', 'inner');
            $this->db->where_in('od.chosen_shipping_id', $shippingMethods);
            $this->db->group_by('o.id_orders'); // Penting untuk menghindari duplikasi orders
        }

        // Jika ada tipe pembayaran yang valid, terapkan filter
        if (!empty($paymentTypes)) {
            $this->db->where_in('o.payment_type', $paymentTypes);
        }

        if ($dateFilter) {
            switch ($dateFilter) {
                case 'today':
                    $this->db->where('DATE(o.order_date) = CURDATE()');
                    break;
                case 'yesterday':
                    $this->db->where('DATE(o.order_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)');
                    break;
                case 'last7days':
                    $this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)');
                    break;
                case 'last30days':
                    $this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)');
                    break;
                case 'thisMonth':
                    $this->db->where('MONTH(o.order_date) = MONTH(CURDATE()) AND YEAR(o.order_date) = YEAR(CURDATE())');
                    break;
                case 'thisYear':
                    $this->db->where('YEAR(o.order_date) = YEAR(CURDATE())');
                    break;
                case 'custom':
                    if ($startDate && $endDate) {
                        $startDate = date('Y-m-d', strtotime($startDate));
                        $endDate = date('Y-m-d', strtotime($endDate));
                        if ($startDate && $endDate) {
                            $this->db->where('DATE(o.order_date) >=', $startDate);
                            $this->db->where('DATE(o.order_date) <=', $endDate);
                        }
                    }
                    break;
            }
        }

        if (!empty($searchTerm)) {
            $this->db->group_start();
            $this->db->like('o.id_orders', $searchTerm);
            $this->db->or_like('o.tokopedia_invoice', $searchTerm);
            $this->db->or_like('o.recipient_name', $searchTerm);
            $this->db->or_like('o.email', $searchTerm);
            $this->db->or_like('o.redeemed_voucher_code', $searchTerm);
            $this->db->or_like('o.payment_type', $searchTerm);
            $this->db->or_like('o.address', $searchTerm);
            $this->db->or_like('o.province', $searchTerm);
            $this->db->or_like('o.district', $searchTerm);
            $this->db->or_like('o.subdistrict', $searchTerm);
            $this->db->or_like('o.source', $searchTerm);
            $this->db->or_like('o.referral', $searchTerm);
            $this->db->or_like('ar.referral', $searchTerm);
            $this->db->or_like('ar.nama', $searchTerm);
            $this->db->group_end();
        }

        // Apply sorting
        if ($sort) {
            switch ($sort) {
                case 'paling_baru':
                    $this->db->order_by('o.order_date', 'DESC');
                    break;
                case 'paling_lama':
                    $this->db->order_by('o.order_date', 'ASC');
                    break;
                default:
                    // Default sort by newest
                    $this->db->order_by('o.order_date', 'DESC');
            }
        } else {
            // Default sort by newest
            $this->db->order_by('o.order_date', 'DESC');
        }

        $this->db->limit($limit, $offset);

        // Execute query
        $query = $this->db->get();
        $all_orders = $query->result();

        // Post-processing: Get order details for each order
        foreach ($all_orders as $order) {
            // Get order details
            $this->db->select('
                od.id_orders_detail,
                od.item_id, 
                od.product_id, 
                od.item_name, 
                od.item_price, 
                od.quantity, 
                od.subtotal, 
                od.sku, 
                od.attributes, 
                od.chosen_shipping_id,
                sm.name as shipping_method_name,
                pi.image as product_image
            ');
            $this->db->from('orders_detail od');
            $this->db->join('shipment_method sm', 'od.chosen_shipping_id = sm.id', 'left');
            $this->db->join('product_images pi', 'od.item_id = pi.product_details_id AND pi.priority = 1 AND pi.status = 1', 'left');
            $this->db->where('od.orders_id', $order->id_orders);
            $details_query = $this->db->get();
            $order->items = $details_query->result();

            // Calculate total items
            $order->total_items = 0;
            foreach ($order->items as $item) {
                $order->total_items += $item->quantity;
            }

            // Format some data if needed
            $order->order_date_formatted = date('d M Y H:i', strtotime($order->order_date));

            // Get affiliate information
            $this->db->select('ar.id_daftar, ar.nama, ar.referral, ar.kategori');
            $this->db->from('affiliator_register ar');
            $this->db->where("(ar.referral = '" . $order->redeemed_voucher_code . "' OR ar.referral = '" . $order->source . "' OR ar.referral = '" . ($order->referral ?? '') . "')");
            $affiliate_query = $this->db->get();
            $order->affiliate_info = $affiliate_query->row();

            // Set payment status text
            switch ($order->payment_status) {
                case 0:
                    $order->payment_status_text = 'Pending';
                    $order->payment_status_class = 'bg-yellow-100 text-yellow-700 px-2 py-1 rounded';
                    break;
                case 1:
                    $order->payment_status_text = 'Menunggu Pembayaran';
                    $order->payment_status_class = 'bg-orange-100 text-orange-700 px-2 py-1 rounded';
                    break;
                case 2:
                    $order->payment_status_text = 'Dibatalin';
                    $order->payment_status_class = 'bg-red-100 text-red-700 px-2 py-1 rounded';
                    break;
                case 3:
                    $order->payment_status_text = 'Sudah Dibayar';
                    $order->payment_status_class = 'bg-green-100 text-green-700 px-2 py-1 rounded';
                    break;
                case 4:
                    $order->payment_status_text = 'Diproses';
                    $order->payment_status_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded';
                    break;
                case 5:
                    $order->payment_status_text = 'Selesai';
                    $order->payment_status_class = 'bg-gray-100 text-gray-700 px-2 py-1 rounded';
                    break;
                case 8:
                    $order->payment_status_text = 'Selesai (Affiliate)';
                    $order->payment_status_class = 'bg-purple-100 text-purple-700 px-2 py-1 rounded';
                    break;
                default:
                    $order->payment_status_text = 'Unknown';
                    $order->payment_status_class = 'bg-gray-300 text-gray-800 px-2 py-1 rounded';
            }
        }

        // Return JSON response
        echo json_encode($all_orders);
    }

    public function get_affiliates()
    {
        // Get filter parameters
        $tab = $this->input->get('tab', true);
        $sort = $this->input->get('sort', true);

        $isMale = filter_var($this->input->get('isMale', true), FILTER_VALIDATE_BOOLEAN);
        $isFemale = filter_var($this->input->get('isFemale', true), FILTER_VALIDATE_BOOLEAN);
        $isOther = filter_var($this->input->get('isOther', true), FILTER_VALIDATE_BOOLEAN);

        $page = (int) ($this->input->get('page', true) ?? 1);
        $limit = (int) ($this->input->get('limit', true) ?? 10);
        $offset = ($page - 1) * $limit;

        $searchTerm = $this->input->get('search', true);
        // Hitung total terlebih dahulu
        $this->db->select('COUNT(DISTINCT ar.id_daftar) as total');
        $this->db->from('affiliator_register ar');

        // Apply tab filter untuk counting
        if ($tab && $tab != 'all') {
            $this->db->where('ar.status', $tab);
        }

        // Apply gender filter untuk counting
        if ($isMale || $isFemale || $isOther) {
            $this->db->join('customers c', 'ar.id_customer = c.id_customers', 'left');

            $sexTypes = [];
            if ($isMale) $sexTypes[] = 'male';
            if ($isFemale) $sexTypes[] = 'female';
            if ($isOther) $sexTypes[] = 'others';

            if (!empty($sexTypes)) {
                $this->db->where_in('c.sex_type', $sexTypes);
            }
        }

        // Apply search filter untuk counting
        if (!empty($searchTerm)) {
            $this->db->group_start();
            $this->db->like('ar.nama', $searchTerm);
            $this->db->or_like('ar.email', $searchTerm);
            $this->db->or_like('ar.no_telpon', $searchTerm);
            $this->db->or_like('ar.sosial_media', $searchTerm);
            $this->db->or_like('ar.referral', $searchTerm);
            $this->db->or_like('ar.voucher', $searchTerm);
            $this->db->group_end();
        }

        $count_query = $this->db->get();
        $count_result = $count_query->row();
        $total_affiliates = $count_result->total;
        // Build main query untuk data
        $this->db->select('
            ar.id_daftar,
            ar.id_customer,
            ar.nama,
            ar.no_telpon,
            ar.email,
            ar.sosial_media,
            ar.ktp,
            ar.status,
            ar.kategori,
            ar.voucher,
            ar.referral,
            ar.komisi,
            ar.created,
            ar.account_name,
            ar.account_number,
            ar.account_type,
            cs.shipping_address,
            cs.shipping_province,
            cs.shipping_district,
            cs.shipping_subdistrict,
            IFNULL(orders.total_orders, 0) as total_orders,
            IFNULL(orders.total_sales, 0) as total_sales
            ');
        $this->db->from('affiliator_register ar');

        // Join dengan customers
        $this->db->join('customers cs', 'ar.id_customer = cs.id_customers', 'left');

        // Join dengan subquery untuk clicks
        // $this->db->join("(
        //     SELECT 
        //         al.customer_id, 
        //         COUNT(DISTINCT lt.ip_address) as total_clicks
        //     FROM affiliator_link al
        //     LEFT JOIN link_tracks lt ON al.link = lt.link_url
        //     GROUP BY al.customer_id
        // ) as clicks", 'ar.id_customer = clicks.customer_id', 'left');


        $this->db->join("(
            SELECT 
                o.redeemed_voucher_code,
                o.referral,
                COUNT(DISTINCT o.id_orders) as total_orders,
                SUM(o.grand_total_amount) as total_sales
            FROM orders o
            WHERE o.payment_status = 5
            GROUP BY o.redeemed_voucher_code, o.referral
        ) as orders", '(orders.redeemed_voucher_code = ar.referral OR orders.referral = ar.referral)', 'left');

        // Apply tab filter
        if ($tab && $tab != 'all') {
            $this->db->where('ar.status', $tab);
        }

        // Apply gender filter if provided
        if ($isMale || $isFemale || $isOther) {
            $this->db->join('customers c', 'ar.id_customer = c.id_customers', 'left');

            $sexTypes = [];
            if ($isMale) $sexTypes[] = 'male';
            if ($isFemale) $sexTypes[] = 'female';
            if ($isOther) $sexTypes[] = 'others';

            if (!empty($sexTypes)) {
                $this->db->where_in('c.sex_type', $sexTypes);
            }
        }

        // Apply search filter
        if (!empty($searchTerm)) {
            $this->db->group_start();
            $this->db->like('ar.nama', $searchTerm);
            $this->db->or_like('ar.email', $searchTerm);
            $this->db->or_like('ar.no_telpon', $searchTerm);
            $this->db->or_like('ar.sosial_media', $searchTerm);
            $this->db->or_like('ar.referral', $searchTerm);
            $this->db->or_like('ar.voucher', $searchTerm);
            $this->db->group_end();
        }

        // Apply sorting
        if ($sort) {
            switch ($sort) {
                case 'paling_baru':
                    $this->db->order_by('ar.created', 'DESC');
                    break;
                case 'paling_lama':
                    $this->db->order_by('ar.created', 'ASC');
                    break;
                // case 'klik_banyak':
                //     $this->db->order_by('total_clicks', 'DESC');
                //     break;
                // case 'klik_dikit':
                //     $this->db->order_by('total_clicks', 'ASC');
                //     break;
                case 'jual_banyak':
                    $this->db->order_by('total_orders', 'DESC');
                    break;
                case 'jual_dikit':
                    $this->db->order_by('total_orders', 'ASC');
                    break;
                default:
                    $this->db->order_by('ar.created', 'DESC');
            }
        } else {
            $this->db->order_by('ar.created', 'DESC');
        }

        // Apply pagination
        $this->db->limit($limit, $offset);

        // Execute query
        $query = $this->db->get();
        $all_affiliates = $query->result();

        // Post-processing data
        foreach ($all_affiliates as $affiliate) {
            // Format date
            $affiliate->created_formatted = date('d M Y H:i', strtotime($affiliate->created));

            // Format status with text and class for display
            switch ($affiliate->status) {
                case 'approve':
                    $affiliate->status_text = 'Approved';
                    $affiliate->status_class = 'bg-green-100 text-green-700 px-2 py-1 rounded';
                    break;
                case 'waiting':
                    $affiliate->status_text = 'Waiting';
                    $affiliate->status_class = 'bg-yellow-100 text-yellow-700 px-2 py-1 rounded';
                    break;
                case 'rejected':
                    $affiliate->status_text = 'Rejected';
                    $affiliate->status_class = 'bg-red-100 text-red-700 px-2 py-1 rounded';
                    break;
                default:
                    $affiliate->status_text = ucfirst($affiliate->status);
                    $affiliate->status_class = 'bg-gray-100 text-gray-700 px-2 py-1 rounded';
            }

            // Format category
            $affiliate->kategori_text = ucfirst($affiliate->kategori);

            // Format commission
            $affiliate->komisi_formatted = 'Rp ' . number_format($affiliate->komisi, 0, ',', '.');

            // Format account info
            $affiliate->account_info = $affiliate->account_name . ' - ' . $affiliate->account_number . ' (' . $affiliate->account_type . ')';

            // Format total sales
            $affiliate->total_sales_formatted = 'Rp ' . number_format($affiliate->total_sales, 0, ',', '.');
        }

        // Prepare pagination info
        $total_pages = ceil($total_affiliates / $limit);

        $pagination = [
            'current_page' => $page,
            'total_pages' => $total_pages,
            'total_records' => $total_affiliates,
            'limit' => $limit
        ];

        foreach ($all_affiliates as $affiliate) {
            $affiliate->_pagination = $pagination;
        }

        // Return JSON response
        echo json_encode($all_affiliates);
    }
    public function get_commissions()
    {
        // Get filter parameters
        $tab = $this->input->get('tab', true);
        $page = (int) ($this->input->get('page', true) ?? 1);
        $limit = (int) ($this->input->get('limit', true) ?? 10);
        $offset = ($page - 1) * $limit;
        $searchTerm = $this->input->get('search', true);

        // Build main query
        $this->db->select(
            '
            ar.id_daftar,
            ar.id_customer,
            ar.nama,
            ar.email,
            ar.no_telpon,
            ar.sosial_media,
            ar.account_name,
            ar.account_number,
            ar.account_type,
            ar.komisi,
            ar.referral,
            IFNULL(SUM(DISTINCT ac.commission), 0) as paid_commission,
            IFNULL(SUM(DISTINCT lt_count.total_clicks * 50), 0) as open_link_commission'
                . ($tab == 'paid' ? ', ac.proof' : '') // Ambil proof hanya jika tab = paid
        );
        $this->db->from('affiliator_register ar');

        // Join ke tabel affiliator_commision
        if ($tab == 'pending') {
            $this->db->join('affiliator_commision ac', 'ar.id_daftar = ac.id_affiliator', 'left');
            $this->db->where('(ac.id_commision IS NULL OR ar.komisi > ac.commission)');
        } else if ($tab == 'paid') {
            $this->db->join('affiliator_commision ac', 'ar.id_daftar = ac.id_affiliator', 'inner');
        }

        // Optimasi open_link_commission: JOIN langsung dengan agregasi
        $this->db->join(
            '(SELECT al.customer_id, COUNT(DISTINCT lt.ip_address) as total_clicks 
                          FROM affiliator_link al
                          LEFT JOIN link_tracks lt ON al.link = lt.link_url
                          GROUP BY al.customer_id) lt_count',
            'ar.id_customer = lt_count.customer_id',
            'left'
        );

        // Apply search filter
        if (!empty($searchTerm)) {
            $this->db->group_start();
            $this->db->like('ar.nama', $searchTerm);
            $this->db->or_like('ar.account_name', $searchTerm);
            $this->db->or_like('ar.account_number', $searchTerm);
            $this->db->or_like('ar.account_type', $searchTerm);
            $this->db->group_end();
        }

        $this->db->group_by('ar.id_daftar');
        $this->db->order_by('ar.nama', 'ASC');

        // Execute query
        $query = $this->db->get();
        $all_commissions = $query->result();

        // Post-processing & filtering
        $filtered_commissions = [];
        foreach ($all_commissions as $commission) {
            $commission->total_commission = $commission->komisi + $commission->open_link_commission;
            $commission->pending_commission = $commission->total_commission - $commission->paid_commission;

            // Filter pending commission > 10,000
            if ($tab == 'pending' && $commission->pending_commission <= 10000) {
                continue;
            }

            // Format output
            $commission->account_info = $commission->account_name . ' - ' . $commission->account_number . ' (' . $commission->account_type . ')';
            $commission->proof = !empty($commission->proof) ? base_url('uploads/commision_proof/' . $commission->proof) : null;
            $commission->komisi_formatted = 'Rp ' . number_format($commission->komisi, 0, ',', '.');
            $commission->open_link_commission_formatted = 'Rp ' . number_format($commission->open_link_commission, 0, ',', '.');
            $commission->total_commission_formatted = 'Rp ' . number_format($commission->total_commission, 0, ',', '.');
            $commission->paid_commission_formatted = 'Rp ' . number_format($commission->paid_commission, 0, ',', '.');
            $commission->pending_commission_formatted = 'Rp ' . number_format($commission->pending_commission, 0, ',', '.');

            $filtered_commissions[] = $commission;
        }

        // Pagination
        $total_commissions = count($filtered_commissions);
        $paginated_commissions = array_slice($filtered_commissions, $offset, $limit);
        $total_pages = ceil($total_commissions / $limit);
        $pagination = [
            'current_page' => $page,
            'total_pages' => $total_pages,
            'total_records' => $total_commissions,
            'limit' => $limit
        ];

        foreach ($paginated_commissions as $commission) {
            $commission->_pagination = $pagination;
        }

        // Return JSON response
        echo json_encode($paginated_commissions);
    }
    public function create_affiliate()
    {
        $customer_id = (int) $this->input->post('id_customers', true);
        $name = $this->input->post('affiliate_name', true);
        $email = $this->input->post('affiliate_email', true);
        $phone = (int) $this->input->post('affiliate_phone', true);
        $social = $this->input->post('affiliate_social', true);
        $category = $this->input->post('affiliate_category', true);
        $status = $this->input->post('affiliate_status', true);
        $referral = $this->input->post('affiliate_ref', true);
        $bank_name = $this->input->post('affiliate_bank', true);
        $account_name = $this->input->post('account_name', true);
        $account_number = (int) $this->input->post('account_number', true);


        $customer = $this->db->select('affiliate')
            ->from('customers')
            ->where('id_customers', $customer_id)
            ->get()
            ->row();

        if ($customer && !empty($customer->affiliate)) {
            // Jika sudah terdaftar sebagai affiliate, kembalikan pesan error
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message', 'Customer ini sudah pernah mendaftar sebagai affiliate.');
            redirect(base_url('admin/affiliate/add'));
            return;
        }

        $referralExists = $this->db->where('voucher', $referral)
            ->or_where('referral', $referral)
            ->get('affiliator_register')
            ->num_rows();

        if ($referralExists > 0) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message', 'Kode referral sudah digunakan, silakan pilih kode lain.');
            redirect(base_url('admin/affiliate/add'));
            return;
        }


        $this->db->trans_start();

        try {
            $data = [
                'id_customer' => $customer_id,
                'nama' => $name,
                'no_telpon' => $phone,
                'email' => $email,
                'sosial_media' => $social,
                'status' => $status,
                'kategori' => $category,
                'voucher' => $referral,
                'referral' => $referral,
                'account_name' => $account_name,
                'account_number' => $account_number,
                'account_type' => $bank_name,
                'created' => date('Y-m-d H:i:s'),
            ];

            $this->db->insert('affiliator_register', $data);

            if ($this->db->trans_status() === false) {
                throw new Exception('Database error occurred');
            }

            $this->db->trans_commit();
            // Set flashdata dan redirect
            $this->session->set_flashdata('message_type', 'success');
            $this->session->set_flashdata('message', 'Affiliate berhasil ditambahkan!');
            redirect(base_url('admin/affiliate/manage'));
        } catch (Exception $e) {
            $this->db->trans_rollback();

            // Set flashdata untuk error dan redirect
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message', $e->getMessage());
            redirect(base_url('admin/affiliate/add'));
        }
    }

    public function upload_proof($id_affiliator)
    {
        $config['upload_path'] = './uploads/commision_proof/';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['max_size'] = 1024; // Maksimal 1MB
        $config['encrypt_name'] = TRUE;

        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, TRUE);
        }

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

        if (!$this->upload->do_upload('proof')) {
            $response = [
                'status' => 'error',
                'message' => $this->upload->display_errors('', '')
            ];
            echo json_encode($response);
            return;
        }

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

        $this->db->trans_begin(); // Mulai transaksi database

        try {
            // Simpan ke database affiliator_commision
            $data = [
                'created' => date('Y-m-d H:i:s'),
                'id_affiliator' => $id_affiliator,
                'proof' => $file_name,
                'account_name' => $this->input->post('account_name'),
                'account_number' => $this->input->post('account_number'),
                'account_type' => $this->input->post('account_type'),
                'commission' => $this->input->post('commission'),
                'status' => $this->input->post('status') ?? 'pending'
            ];

            $this->db->insert('affiliator_commision', $data);

            // Reset field `commission` di tabel affiliator_register menjadi 0
            $this->db->where('id_daftar', $id_affiliator);
            $this->db->update('affiliator_register', ['komisi' => 0]);

            if ($this->db->trans_status() === FALSE) {
                throw new Exception('Database transaction failed.');
            }

            $this->db->trans_commit(); // Commit transaksi jika semua berhasil

            echo json_encode([
                'success' => true,
                'message' => 'Proof berhasil diupload dan komisi telah direset!',
                'data' => $data
            ]);
        } catch (Exception $e) {
            $this->db->trans_rollback(); // Rollback jika terjadi error

            echo json_encode([
                'success' => false,
                'message' => 'Gagal upload proof: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Function to add product links for affiliators
     * Receives product data from AJAX request and stores in affiliator_link table
     * 
     * @return void
     */
    public function add_product_links()
    {
        // Check if request is AJAX
        if (!$this->input->is_ajax_request()) {
            show_404();
        }

        // Get product data from POST request
        $products_json = $this->input->post('products');
        $products = json_decode($products_json, true);

        if (empty($products) || !is_array($products)) {
            $response = [
                'success' => false,
                'message' => 'Data produk tidak valid'
            ];
            echo json_encode($response);
            return;
        }

        $current_datetime = date('Y-m-d H:i:s');
        $success_count = 0;
        $error_messages = [];

        // Begin transaction
        $this->db->trans_begin();

        try {
            foreach ($products as $product) {
                // Prepare data for insertion
                $link_data = [
                    'product_id' => $product['product_id'],
                    'product_name' => $product['product_name'],
                    'customer_id' => $product['customer_id'],
                    'affiliator_name' => $product['affiliator_name'],
                    'unique_id' => $product['unique_id'],
                    'status' => 'active', // Default status
                    'link' => $product['link'],
                    'open' => 0, // Initial values
                    'order' => 0,
                    'komisi_order' => 0,
                    'created_date' => $current_datetime,
                    'product_detail_id' => $product['product_detail_id']
                ];

                // Insert data to the affiliator_link table
                $result = $this->db->insert('affiliator_link', $link_data);

                if ($result) {
                    $success_count++;
                } else {
                    $error_messages[] = "Gagal menyimpan produk: {$product['product_name']}";
                }
            }

            // Check if all inserts were successful
            if ($success_count === count($products)) {
                $this->db->trans_commit();
                $response = [
                    'success' => true,
                    'message' => "$success_count produk berhasil ditambahkan"
                ];
            } else {
                // If any insert failed, rollback the transaction
                $this->db->trans_rollback();
                $response = [
                    'success' => false,
                    'message' => implode(', ', $error_messages)
                ];
            }
        } catch (Exception $e) {
            $this->db->trans_rollback();
            $response = [
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ];
        }

        // Return JSON response
        echo json_encode($response);
    }

    public function send_product()
    {
        if ($this->input->server('REQUEST_METHOD') !== 'POST') {
            show_error('Method Not Allowed', 405);
        }

        $userdata = $this->session->userdata();
        $postData = $this->input->post();

        // Validate required inputs
        if (empty($postData['customer_id']) || empty($postData['product_id']) || empty($postData['product_detail_id'])) {
            $this->session->set_flashdata('message', 'Data produk atau customer tidak lengkap');
            $this->session->set_flashdata('message_type', 'error');
            redirect('admin/affiliate/detail/' . $postData['daftar_id']);
        }

        // Get customer data
        $customer = $this->db->get_where('customers', ['id_customers' => $postData['customer_id']])->row_array();
        if (!$customer) {
            $this->session->set_flashdata('message', 'Customer tidak ditemukan');
            $this->session->set_flashdata('message_type', 'error');
            redirect('admin/affiliate/detail/' . $postData['daftar_id']);
        }

        // Get product data - assuming you have a products table
        $product = $this->db->get_where('products', ['id_products' => $postData['product_id']])->row_array();
        if (!$product) {
            $this->session->set_flashdata('message', 'Produk tidak ditemukan');
            $this->session->set_flashdata('message_type', 'error');
            redirect('admin/affiliate/detail/' . $postData['daftar_id']);
        }

        // Get product detail data
        $product_detail = $this->db->get_where('product_details', ['id' => $postData['product_detail_id']])->row_array();
        if (!$product_detail) {
            $this->session->set_flashdata('message', 'Detail produk tidak ditemukan');
            $this->session->set_flashdata('message_type', 'error');
            redirect('admin/affiliate/detail/' . $postData['daftar_id']);
        }

        // Data untuk tabel orders
        $orderData = [
            'customer_id' => (int) $customer['id_customers'],
            'payment_status' => 0,
            'grand_total_amount' => 0,
            'total_amount' => 0,
            'payment_type' => 'bank transfer BCA',
            'recipient_name' => $customer['name'],
            'address' => !empty($customer['shipping_address']) ? $customer['shipping_address'] : '',
            'district' => !empty($customer['shipping_district']) ? $customer['shipping_district'] : '',
            'subdistrict' => !empty($customer['shipping_subdistrict']) ? $customer['shipping_subdistrict'] : '',
            'province' => !empty($customer['shipping_province']) ? $customer['shipping_province'] : '',
            'phone' => !empty($customer['shipping_phone']) ? $customer['shipping_phone'] : '',
            'email' => $customer['email'],
            'country' => 'Indonesia',
            'redeemed_voucher_code' => null,
            'redeemed_voucher_type' => null,
            'redeemed_voucher_value' => 0,
            'redeemed_voucher_amount' => 0,
            'shipping_fee' => 0,
            'created_by' => $userdata['name'],
            'source' => 'Marketing',
            'distribution_type' => 'Marketing',
            'distribution_department' => 'Marketing',
            'distribution_purpose' => 'Produk untuk Asmaradoor',
        ];

        // Mulai transaksi database
        $this->db->trans_start();

        // Insert ke tabel orders
        $this->db->insert('orders', $orderData);
        $orderId = $this->db->insert_id();


        // Prepare order detail data for single product
        $orderDetailData = [
            'orders_id' => $orderId,
            'item_id' => !empty($postData['product_detail_id']) ? $postData['product_detail_id'] : null,
            'product_id' => !empty($postData['product_id']) ? $postData['product_id'] : null,
            'item_name' => !empty($product['title']) ? $product['title'] : '', // Get name from products table
            'item_price' => !empty($product_detail['price']) ? (int) $product_detail['price'] : 0, // Get price from product_detail
            'quantity' => 1, // Set quantity to 1 as requested
            'subtotal' => 0, // Set subtotal to 0 as requested
            'sku' => !empty($product_detail['sku']) ? $product_detail['sku'] : '', // Get SKU from product_detail
            'attributes' => !empty($product_detail['attributes']) ? $product_detail['attributes'] : '', // Get attributes from product_detail
            'warehouse_id' => 1,
            'chosen_shipping_id' => 3, // Fixed value as requested
            'shipping_fee' => 0 // Fixed value as requested
        ];


        // Insert to orders_detail
        $insert_result = $this->db->insert('orders_detail', $orderDetailData);
        if ($insert_result) {
            log_message('error', 'Order Inserted Successfully: Order ID ' . $orderId);
        } else {
            log_message('error', 'Order Insert Failed: ' . print_r($this->db->error(), true));
        }
        // Update Stock logic remains the same
        if ($insert_result) {
            $this->db->select('id, stock');
            $this->db->where('id_product', $postData['product_id']);
            $this->db->where('id_product_detail', $postData['product_detail_id']);
            $this->db->where('warehouse_id', 1);
            $stock = $this->db->get('stock')->row();

            if ($stock) {
                $stock_id = $stock->id;
                $old_stock = $stock->stock; // Simpan stok sebelum perubahan

                // Update Stock
                $this->db->set('stock', 'stock - 1', false) // Use fixed quantity 1
                    ->where('id_product', $postData['product_id'])
                    ->where('id_product_detail', $postData['product_detail_id'])
                    ->where('warehouse_id', 1);
                $update_stock_result = $this->db->update('stock');

                if ($update_stock_result) {
                    // Ambil stok setelah perubahan
                    $this->db->select('stock');
                    $this->db->where('id', $stock_id);
                    $new_stock = $this->db->get('stock')->row()->stock;

                    // Insert stock movement
                    $movement_data = [
                        'stock_id' => $stock_id,
                        'type' => '-',
                        'stock_change' => 1, // Fixed quantity 1
                        'remark' => 'Sales Order No: ' . $orderId,
                        'total' => $new_stock,
                        'name' => 'System',
                        'datetime' => date('Y-m-d H:i:s')
                    ];
                    $insert_movement_result = $this->db->insert('stock_movement', $movement_data);

                    // Panggil log stok dengan stok sebelum dan sesudah perubahan
                    $this->log_m->log_stock_update(
                        $orderId,
                        $postData['product_detail_id'],
                        $product['name'],
                        $old_stock,
                        $new_stock,
                        base_url('admin/products/stock-product?tab=all'),
                        null,
                        'stock',
                        'orders'
                    );

                    if (!$insert_movement_result) {
                        log_message('error', 'Stock Movement Insert Failed: ' . print_r($this->db->error(), true));
                    }
                } else {
                    log_message('error', 'Stock Update Failed: ' . print_r($this->db->error(), true));
                }
            } else {
                log_message('error', 'Stock ID Not Found for Product: ' . $product['name']);
            }
        } else {
            $db_error = $this->db->error();
            log_message('error', 'Order Detail Insert Failed: ' . print_r($db_error, true));
        }

        // Selesaikan transaksi
        $this->db->trans_complete();

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();

            $this->session->set_flashdata('message', 'Gagal menambahkan pesanan');
            $this->session->set_flashdata('message_type', 'error');

            // Redirect to affiliate page
            redirect('admin/affiliate/detail/' . $postData['daftar_id']);
        } else {
            $name = $this->session->userdata('name');
            $description = "Pesanan Baru telah ditambahkan dengan Order ID {$orderId}. Pesanan ini dibuat oleh {$name}.";

            $reference_url = base_url('admin/orders/manage-order?tab=pending');
            $log_id = $this->log_m->log_order_create($orderId, $description, $reference_url);
            $this->log_m->send_order_notifications('CREATE_ORDER', $log_id, $description);

            $this->session->set_flashdata('message', 'Berhasil menambah pesanan baru dengan ID: ' . $orderId);
            $this->session->set_flashdata('message_type', 'success');

            // Redirect to manage-order page
            redirect('admin/affiliate/detail/' . $postData['daftar_id']);
        }
    }

    // Old
    //this is to list all affiliator
    public function index()
    {

        //pagination in action. 50 results per page
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/affiliator';

        $this->db->select('id_daftar')->from('affiliator_register');
        $daftar_count = $this->db->get()->num_rows();
        $config['total_rows'] = $daftar_count;
        $config['per_page'] = 100;
        $config["uri_segment"] = 4;
        $config['num_tag_open'] = '<span style="padding-left:10px; padding-right:10px">';
        $config['num_tag_close'] = '</span>';

        $this->pagination->initialize($config);

        $this->db->select('*');
        $this->db->from('affiliator_register');
        $this->db->order_by('id_daftar', 'DESC');
        $this->db->limit($config["per_page"], $this->uri->segment(4));
        $this->data['affiliator_register'] = $this->db->get()->result();

        //load view
        $this->data['subview'] = 'admin/affiliator/index';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    public function list()
    {
        // Load pagination library
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/affiliator';

        $this->db->select('id_daftar')->from('affiliator_register');
        $daftar_count = $this->db->get()->num_rows();
        $config['total_rows'] = $daftar_count;
        $config['per_page'] = 100;
        $config["uri_segment"] = 4;
        $config['num_tag_open'] = '<span style="padding-left:10px; padding-right:10px">';
        $config['num_tag_close'] = '</span>';
        $this->pagination->initialize($config);

        // Query affiliator data
        $this->db->select('*');
        $this->db->from('affiliator_register');
        $this->db->where('status', 'approve');
        $this->db->order_by('id_daftar', 'DESC');
        $affiliator_list = $this->db->get()->result();

        // Calculate earned and pending for each affiliator
        foreach ($affiliator_list as $affiliator) {
            if (isset($affiliator->voucher)) {
                // Hitung jumlah kunjungan
                $count_visit = $this->db->select('id')
                    ->from('visits')
                    ->where('referral', $affiliator->voucher)
                    ->where('date >=', '2024-08-01')
                    ->group_by('ip_address')
                    ->get()
                    ->num_rows();

                // Hitung total komisi yang sudah dicairkan
                $this->db->select_sum('commission');
                $this->db->from('affiliator_commision');
                $this->db->where('id_affiliator', $affiliator->id_daftar);
                $query = $this->db->get();
                $result = $query->row();
                $count_already_earned = $result->commission;

                // Hitung komisi yang diperoleh
                if ($affiliator->voucher == 'laciput') {
                    $earned = $count_visit * 0;
                } else {
                    $earned = $count_visit * 50;
                }

                // Hitung komisi yang masih pending
                $pending = $earned - $count_already_earned;

                // Assign nilai ke objek affiliator
                $affiliator->earned = $earned;
                $affiliator->pending = $pending;
            } else {
                $affiliator->earned = 0;
                $affiliator->pending = 0;
            }
        }


        // Sort affiliator list by earned amount in descending order
        usort($affiliator_list, function ($a, $b) {
            return $b->earned - $a->earned;
        });

        // Prepare data for view
        $this->data['affiliator_list'] = $affiliator_list;

        // Load views
        $this->data['subview'] = 'admin/affiliator/list';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }



    public function mission()
    {

        //pagination in action. 50 results per page
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/affiliator';

        $this->db->select('id_mission')->from('mission');
        $daftar_count = $this->db->get()->num_rows();
        $config['total_rows'] = $daftar_count;
        $config['per_page'] = 10;
        $config["uri_segment"] = 4;
        $config['num_tag_open'] = '<span style="padding-left:10px; padding-right:10px">';
        $config['num_tag_close'] = '</span>';

        $this->pagination->initialize($config);

        $this->db->select('*');
        $this->db->from('mission');
        $this->db->limit($config["per_page"], $this->uri->segment(4));
        $this->data['mission_list'] = $this->db->get()->result();

        //load view
        $this->data['subview'] = 'admin/affiliator/mission';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    public function progressmission()
    {
        $this->data_header['page_title'] = 'Affiliate Program';

        // Pagination configuration
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/affiliator/progressmission';
        $config['total_rows'] = $this->db->count_all('affiliator_register');
        $config['per_page'] = 100;
        $config["uri_segment"] = 4;
        $config['num_tag_open'] = '<span style="padding-left:10px; padding-right:10px">';
        $config['num_tag_close'] = '</span>';
        $this->pagination->initialize($config);

        // Load progress report data
        $this->db->select('*');
        $this->db->from('mission_progress_submit');
        $this->db->order_by('id_customer');
        $progressreport = $this->db->get()->result();

        $this->data['progressreport'] = $progressreport;

        // Get affiliator list
        $this->db->select('*');
        $this->db->from('customers');
        $this->db->where('affiliate', 'approve');
        $this->db->order_by('id_customers', 'DESC');
        $affiliator_list = $this->db->get()->result();

        $this->data['affiliator_list'] = $affiliator_list;

        // Get mission progress details
        $this->db->select('mission_progress_detail.id_customer, mission.name as mission_name, mission.target as mission_target, mission_progress_detail.progress');
        $this->db->from('mission_progress_detail');
        $this->db->join('mission', 'mission.id_mission = mission_progress_detail.id_mission');
        $this->db->join('customers', 'customers.id_customers = mission_progress_detail.id_customer');
        $this->db->where('customers.affiliate', 'approve');
        $this->db->order_by('mission_progress_detail.id_customer', 'ASC');
        $this->db->order_by('mission_progress_detail.id_mission', 'ASC');
        $progress_list = $this->db->get()->result();

        $this->data['progress_list'] = $progress_list;

        // Load view
        $this->data['subview'] = 'admin/affiliator/progress-mission';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    public function submitview($id)
    {

        if ($id == null) {
            redirect('admin/affiliator/progressmission');
        }

        //get affiliator
        $this->db->select('id_submit')->from('mission_progress_submit')->where('id_submit', $id);
        $current_submit_count = $this->db->get()->num_rows();

        if ($current_submit_count < 1) {
            show_404();
        }


        if (isset($_POST['status'])) {

            /* if($this->order_m->cek_order($id,$_POST['register_status']) == FALSE){
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Order telah diproses</p>');
				redirect('admin/orders/view/' . $id);
			} */

            //var_dump($this->input->post('register_status')); exit();

            if ($this->input->post('status') == "approved") {

                $this->db->select('*');
                $this->db->from('mission_progress_submit');
                $this->db->where('id_submit', $id);
                $progressreport = $this->db->get()->row();

                // Update status to approved
                $data = array(
                    'status' => "approved",
                );
                $this->db->where('id_submit', $id);
                $this->db->update('mission_progress_submit', $data);

                // Check if entry exists in mission_progress_detail
                $this->db->where('id_customer', $progressreport->id_customer);
                $this->db->where('id_mission', $progressreport->id_mission);
                $query = $this->db->get('mission_progress_detail');

                if ($query->num_rows() > 0) {
                    // Entry exists, update progress
                    $row = $query->row();
                    $data2 = array(
                        'progress' => $row->progress + 1
                    );
                    $this->db->where('id_customer', $progressreport->id_customer);
                    $this->db->where('id_mission', $progressreport->id_mission);
                    $this->db->update('mission_progress_detail', $data2);
                } else {
                    // Entry does not exist, insert new entry with progress 1
                    $data2 = array(
                        'id_customer' => $progressreport->id_customer,
                        'id_mission' => $progressreport->id_mission,
                        'progress' => 1
                    );
                    $this->db->insert('mission_progress_detail', $data2);
                }

                $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status report progress berhasil diupdate</p>');
                redirect('admin/affiliator/submitview/' . $id);
            }

            if ($this->input->post('status') == "rejected") {

                //Status DELIVERED
                $data = array(
                    'status' => "rejected",
                );
                $this->db->where('id_submit', $id);
                $this->db->update('mission_progress_submit', $data);


                $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status report progress berhasil diupdate</p>');
                redirect('admin/affiliator/submitview/' . $id);
            }
        }

        $this->data['progress'] = $this->affiliator_m->get_affiliator_mission_submit($id);
        $this->data['subview'] = 'admin/affiliator/submit-view';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    public function addmission()
    {


        if (isset($_POST['submit'])) {

            //Add mission
            $data = array(
                'name' => $this->security->xss_clean($this->input->post('name')),
                'quest' => $this->security->xss_clean($this->input->post('quest')),
                'target' => $this->input->post('target'),
                'type' => $this->security->xss_clean($this->input->post('type')),
                'customer_id' => 0,
                'status' => $this->security->xss_clean($this->input->post('status'))
            );

            $this->db->insert('mission', $data);

            $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Misi berhasil ditambahkan</p>');
            redirect('admin/affiliator/mission');
        }

        $this->data['subview'] = 'admin/affiliator/addmission';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    public function missionview($id)
    {

        if ($id == null) {
            redirect('admin/affiliator/mission');
        }

        //get affiliator
        $this->db->select('id_mission')->from('mission')->where('id_mission', $id);
        $current_order_count = $this->db->get()->num_rows();

        if ($current_order_count < 1) {
            show_404();
        }


        if (isset($_POST['status'])) {

            /* if($this->order_m->cek_order($id,$_POST['register_status']) == FALSE){
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Order telah diproses</p>');
				redirect('admin/orders/view/' . $id);
			} */

            //var_dump($this->input->post('register_status')); exit();

            if ($this->input->post('status') == "1") {

                //Status DELIVERED
                $data = array(
                    'status' => "1",
                );
                $this->db->where('id_mission', $id);
                $this->db->update('mission', $data);

                $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status misi berhasil diupdate</p>');
                redirect('admin/affiliator/missionview/' . $id);
            }
            if ($this->input->post('status') == "2") {

                //Status DELIVERED
                $data = array(
                    'status' => "2",
                );
                $this->db->where('id_mission', $id);
                $this->db->update('mission', $data);


                $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status misi berhasil diupdate</p>');
                redirect('admin/affiliator/missionview/' . $id);
            }
        }

        $this->data['mission'] = $this->affiliator_m->get_affiliator_mission($id);
        $this->data['subview'] = 'admin/affiliator/mission-view';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    // Old Commision
    public function commision()
    {
        // Load pagination library
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/affiliator';

        // Hitung jumlah affiliator
        $this->db->select('id_daftar')->from('affiliator_register');
        $daftar_count = $this->db->get()->num_rows();
        $config['total_rows'] = $daftar_count;
        $config['per_page'] = 100;
        $config["uri_segment"] = 4;
        $config['num_tag_open'] = '<span style="padding-left:10px; padding-right:10px">';
        $config['num_tag_close'] = '</span>';
        $this->pagination->initialize($config);

        // Query affiliator data
        $this->db->select('*');
        $this->db->from('affiliator_register');
        $this->db->where('status', 'approve');
        $this->db->order_by('id_customer', 'DESC');
        $affiliator_list = $this->db->get()->result();

        // Calculate pending for each affiliator and filter
        $filtered_affiliator_list = [];
        foreach ($affiliator_list as $affiliator) {
            if (isset($affiliator->voucher)) {
                // Hitung jumlah kunjungan
                $count_visit = $this->db->select('id')
                    ->from('visits')
                    ->where('referral', $affiliator->voucher)
                    ->where('date >=', '2024-08-01')
                    ->group_by('ip_address')
                    ->get()
                    ->num_rows();

                // Hitung total komisi yang sudah dicairkan
                $this->db->select_sum('commission');
                $this->db->from('affiliator_commision');
                $this->db->where('id_affiliator', $affiliator->id_daftar);
                $query = $this->db->get();
                $result = $query->row();
                $count_already_earned = $result->commission ?? 0;

                // Hitung komisi dari open link yang diperoleh (50 rupiah per visit)
                $earned = $count_visit * ($affiliator->voucher == 'laciput' ? 0 : 50);

                // Jika kategori asmaradoor, hitung total komisi dari semua link affiliator
                if ($affiliator->kategori == 'asmaradoor') {
                    $this->db->select_sum('komisi_order');
                    $this->db->from('affiliator_link');
                    $this->db->where('customer_id', $affiliator->id_customer);
                    $query_komisi_link = $this->db->get();
                    $komisi_order_link = $query_komisi_link->row()->komisi_order ?? 0;

                    $this->db->select_sum('komisi');
                    $this->db->from('affiliator_register');
                    $this->db->where('id_customer', $affiliator->id_customer);
                    $query_order = $this->db->get();
                    $komisi = $query_order->row()->komisi ?? 0;

                    // Tambahkan komisi_order ke earned
                    $earned += $komisi_order_link + $komisi;
                }

                if ($affiliator->kategori == 'asmarasana') {
                    $earned_asmarasana = $affiliator->komisi ?? 0;
                } else {
                    $earned_asmarasana = 0;
                }

                // Hitung komisi yang masih pending
                $pending = $earned - $count_already_earned;
                $pending_asmarasana = $earned_asmarasana - $count_already_earned;

                // Masukkan ke filtered list jika pending di atas 10,000
                if ($pending > 10000 || $pending_asmarasana > 10000) {
                    $affiliator->earned = $earned;
                    $affiliator->pending = $pending;
                    $affiliator->earned_asmarasana = $earned_asmarasana;
                    $affiliator->pending_asmarasana = $pending_asmarasana;
                    $filtered_affiliator_list[] = $affiliator;
                }
            }
        }

        // Set filtered list to data
        $this->data['affiliator_list'] = $filtered_affiliator_list;

        // Load views
        $this->data['subview'] = 'admin/affiliator/commision';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }


    public function commision_done()
    {
        // Load pagination library
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/affiliator';

        // Hitung jumlah komisi
        $this->db->select('id_commision')->from('affiliator_commision');
        $commision_count = $this->db->get()->num_rows();
        $config['total_rows'] = $commision_count;
        $config['per_page'] = 100;
        $config["uri_segment"] = 4;
        $config['num_tag_open'] = '<span style="padding-left:10px; padding-right:10px">';
        $config['num_tag_close'] = '</span>';
        $this->pagination->initialize($config);

        // Query affiliator data dengan join ke affiliator_register untuk mendapatkan nama affiliator
        $this->db->select('affiliator_commision.*, affiliator_register.nama as affiliator_name');
        $this->db->from('affiliator_commision');
        $this->db->join('affiliator_register', 'affiliator_commision.id_affiliator = affiliator_register.id_daftar', 'left');
        $this->db->order_by('affiliator_commision.id_commision', 'DESC');
        $this->db->limit($config['per_page'], $this->uri->segment(4));
        $done_list = $this->db->get()->result();

        // Simpan data ke array untuk digunakan di view
        $this->data['commision_list'] = $done_list;

        // Load views
        $this->data['subview'] = 'admin/affiliator/commision_done';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }


    public function commision_proof()
    {
        if (!isset($_POST['submit_proof'])) {
            redirect('affiliator/commision');
        }

        $id_daftar = $this->input->post('id_daftar');
        log_message('debug', 'File MIME Type: ' . $_FILES['receipt_file']['type']);

        if ($_FILES['receipt_file']['size'] !== 0) {
            $config['upload_path'] = './uploads/commision_proof/';
            $config['allowed_types'] = 'jpeg|jpg|png|pdf';
            $config['max_size'] = '5000';
            $config['encrypt_name'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);

            if (!$this->upload->do_upload('receipt_file')) {
                $this->session->set_flashdata('proof_error', $this->upload->display_errors('<p style="background:red; color:white; padding:5px; font-weight:bold;">', '</p>'));
                redirect('admin/affiliator/commision');
            } else {
                $image = $this->upload->data();
                $image_name =  $image['file_name'];
            }
        }

        $data = [
            'created' => date('Y-m-d H:i:s'),
            'id_affiliator' => $id_daftar,
            'proof' => $image_name,
            'account_name' => $this->input->post('account_name'),
            'account_number' => $this->input->post('account_number'),
            'account_type' => $this->input->post('account_type'),
            'commission' => $this->input->post('commission'),
            'status' => 'Completed' // atau sesuaikan dengan status yang diperlukan
        ];

        $this->db->insert('affiliator_commision', $data);

        // Logging
        $user_id = $this->session->userdata('admin')['id'];
        $activity = 'User upload bukti transfer (' . $id_daftar . ')';
        log_activity($user_id, $activity);

        $this->session->set_flashdata('success', 'Bukti transfer berhasil diupload dan komisi telah diperbarui.');
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function product()
    {
        //pagination in action. 50 results per page
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/affiliator';

        $this->db->select('id_daftar')->from('affiliator_register');
        $daftar_count = $this->db->get()->num_rows();
        $config['total_rows'] = $daftar_count;
        $config['per_page'] = 100;
        $config["uri_segment"] = 4;
        $config['num_tag_open'] = '<span style="padding-left:10px; padding-right:10px">';
        $config['num_tag_close'] = '</span>';

        $this->pagination->initialize($config);

        $this->db->select('*');
        $this->db->from('affiliator_register');
        $this->db->where('status', 'approve');
        $this->db->order_by('id_customer', 'DESC');
        $this->data['affiliator_list'] = $this->db->get()->result();

        $this->db->select('product_id');
        $this->db->from('affiliator_product');
        $this->db->order_by('id', 'DESC');
        $this->data['product_list'] = $this->db->get()->result();

        //load view
        $this->data['sent'] = $this->affiliator_m->get_sent_product();
        $this->data['subview'] = 'admin/affiliator/product';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }


    public function product_add()
    {
        //pagination in action. 50 results per page
        if (isset($_POST['submit'])) {

            $id = $this->security->xss_clean($this->input->post('product'));
            $this->db->select('product_id')->from('product_details')->where('id', $id);
            $pdf_data['product_id'] = $this->db->get()->row();

            //Add mission
            $data = array(
                'product_id' => $pdf_data['product_id']->product_id,
                'product_detail_id' => $this->security->xss_clean($this->input->post('product')),
                'affiliator_id' => $this->security->xss_clean($this->input->post('affiliator')),
                'created' => date('Y-m-d H:i:s'),
                'address' => $this->security->xss_clean($this->input->post('address'))
            );

            $order_affiliator_id  = (int) $this->affiliator_m->add_product($data);

            $product_detail_id = $this->security->xss_clean($this->input->post('product'));
            $curent_stock     = $this->db->select('stock')->from('stock')->where('id_product_detail', $product_detail_id)->where('warehouse_id', 1)->get()->row();

            $warehouse = $this->db->select('*')->from('warehouse')->where('id', 1)->get()->row();

            if ($warehouse->warehouse_type == 'virtual') {
                $final_stock = array(
                    'stock_virtual' => $curent_stock->stock_virtual - 1,
                );
                $this->db->where('id_product_detail', $product_detail_id);
                $this->db->where('warehouse_id', 1);
                $this->db->update('stock', $final_stock);
            } else {
                $final_stock = array(
                    'stock' => $curent_stock->stock - 1,
                );
                $this->db->where('id_product_detail', $product_detail_id);
                $this->db->where('warehouse_id', 1);
                $this->db->update('stock', $final_stock);

                // insert mov stock
                $id_stock = $this->db->select('id')->from('stock')->where('id_product_detail', $product_detail_id)->where('warehouse_id', 1)->get()->row();
                $this->db->select('name')->from('users')->where('id', $this->session->userdata('admin')['id']);
                $user_name = $this->db->get()->row()->name;

                $last_stock = $curent_stock->stock - 1;

                $insert_mov_stock = array(
                    'stock_id'         => $id_stock->id,
                    'type'             => '-',
                    'stock_change'     => 1,
                    'remark'         => 'Sent Product to affiliator : ' . $order_affiliator_id,
                    'total'         => $last_stock,
                    'name'             => $user_name,
                    'datetime'         => date("Y-m-d H:i:s"),
                );
                $this->db->insert('stock_movement', $insert_mov_stock);
            }

            $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Pengiriman produk berhasil ditambahkan</p>');
            redirect('admin/affiliator/product');
        }

        $this->db->select('*');
        $this->db->from('affiliator_register');
        $this->db->where('status', 'approve');
        $this->db->order_by('id_customer', 'DESC');
        $this->data['affiliator_list'] = $this->db->get()->result();

        //load view
        $this->data['product_active'] = $this->db->select('p.id_products, pd.id as product_details_id, p.title, GROUP_CONCAT(pad.attribute_detail SEPARATOR ", ") AS attributes_name')
            ->from('product_combination pc')
            ->join('products p', 'pc.product_id = p.id_products')
            ->join('product_details pd', 'pc.product_details_id = pd.id')
            ->join('product_attributes pa', 'pa.id = pc.attribute_id')
            ->join('product_attributes_detail pad', 'pad.id = pc.attribute_detail_id')
            ->order_by('title', 'ASC')
            ->group_by('pd.id')
            ->get()->result();


        $this->data['subview'] = 'admin/affiliator/product_add';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    // Generate Delivery Receipt
    public function generate_deliveryreceipt($id)
    {
        if ($id == NULL) {
            redirect('admin/affiliator/product');
        }

        $count_order = $this->db->select('id')->from('affiliator_product')->where('id', $id)->get()->num_rows();
        if ($count_order < 1) {
            redirect('admin/affiliator/product');
        }

        //get website info
        $pdf_data['website_data'] = $this->db->select('logo, website_name')->from('configuration')->where('id_configuration', 1)->get()->row();

        //add PDF attachment DOMPDF 	  
        $pdf_data['title'] = 'Delivery Receipt Affiliator No: ' . $id;

        //get order
        $this->db->select('*')->from('affiliator_product')->where('id', $id);
        $pdf_data['order'] = $this->db->get()->row();

        if ($count_order > 0) {

            $data = array(
                'status' => 'sent'
            );

            $this->db->where('id', $id);
            $this->db->update('affiliator_product', $data);

            //get customer detail
            $pdf_data['customer'] = $this->db->select('*')->from('affiliator_register')->where('id_daftar', $pdf_data['order']->affiliator_id)->get()->row();

            // get Product & Product detail
            $pdf_data['product_detail']     = $this->db->select('*')->from('product_details')->where('id', $pdf_data['order']->product_detail_id)->get()->row();
            $pdf_data['product']     = $this->db->select('*')->from('products')->where('id_products', $pdf_data['order']->product_id)->get()->row();


            //Print Pdf Delivery Receipt
            $this->load->library('dompdf_gen');
            $html = $this->load->view('pdf/deliveryreceiptaff', $pdf_data, true);
            $this->dompdf->loadHtml($html);
            $this->dompdf->setPaper('A4', 'portrait');
            $this->dompdf->render();
            $this->dompdf->stream('deliveryreceiptaff.pdf', array("Attachment" => 0));
            $output = $this->dompdf->output();
            $file_to_save = 'uploads/pdf/deliveryreceiptaff.pdf';
            file_put_contents($file_to_save, $output);
        } else {
            redirect('admin/affiliator/product');
        }
    }

    // Generate Report Commision
    public function generate_commision_report($id)
    {
        if ($id == NULL) {
            redirect('admin/affiliator/commision');
        }

        $count_order = $this->db->select('id_daftar')->from('affiliator_register')->where('id_daftar', $id)->get()->num_rows();
        if ($count_order < 1) {
            redirect('admin/affiliator/commision');
        }

        //get website info
        $pdf_data['website_data'] = $this->db->select('logo, website_name')->from('configuration')->where('id_configuration', 1)->get()->row();

        //add PDF attachment DOMPDF 	  
        $pdf_data['title'] = 'Report No: ' . $id;

        //get affiliator register
        $this->db->select('*')->from('affiliator_register')->where('id_daftar', $id);
        $pdf_data['affiliator'] = $this->db->get()->row();

        //get affiliator register
        $this->db->select('affiliator_product.*, products.title as product_name, product_details.price as product_price')
            ->from('affiliator_product')
            ->join('products', 'products.id_products = affiliator_product.product_id', 'left')
            ->join('product_details', 'product_details.id = affiliator_product.product_detail_id', 'left')
            ->where('affiliator_id', $id);
        $pdf_data['products'] = $this->db->get()->result(); // Menggunakan result() untuk mendapatkan semua data sebagai array objek

        // Perhitungan earned dan pending
        $affiliator_voucher = $pdf_data['affiliator']->voucher;

        $count_visit = $this->db->select('id')
            ->from('visits')
            ->where('referral', $affiliator_voucher)
            ->where('date >=', '2024-08-01')
            ->group_by('ip_address')
            ->get()
            ->num_rows();

        $count_already_earned = 0;
        if ($affiliator_voucher == 'laciput') {
            $earned = $count_visit * 0;
        } else {
            $earned = $count_visit * 50;
        }
        // Calculate already earned
        $this->db->select_sum('commission');
        $this->db->from('affiliator_commision');
        $this->db->where('id_affiliator', $id);
        $query = $this->db->get();
        $result = $query->row();
        $count_already_earned = $result->commission ?? 0; // Use 0 if no result

        $pending = $earned - $count_already_earned;

        $pdf_data['total'] = $earned;
        $pdf_data['earned'] = $earned;
        $pdf_data['pending'] = $pending;

        if ($count_order > 0) {
            //get customer detail
            $pdf_data['customer'] = $this->db->select('*')->from('customers')->where('id_customers', $pdf_data['affiliator']->id_customer)->get()->row();

            // get order detail
            $pdf_data['orders_detail']     = $this->db->select('*')->from('orders_detail')->where('orders_id', $id)->get()->result();

            //Print Pdf Invoice
            $this->load->library('dompdf_gen');
            $html = $this->load->view('pdf/commision_report_affiliator', $pdf_data, true);
            $this->dompdf->loadHtml($html);
            $this->dompdf->setPaper('A4', 'portrait');
            $this->dompdf->render();
            $this->dompdf->stream('commision_report.pdf', array("Attachment" => 0));
            $output = $this->dompdf->output();
            $file_to_save = 'uploads/pdf/commision_report.pdf';
            file_put_contents($file_to_save, $output);
        } else {
            redirect('admin/affiliator/commision');
        }
    }

    // View Affiliator
    public function view($id)
    {
        if ($id == null) {
            redirect('admin/affiliator');
        }

        //get affiliator
        $this->db->select('id_daftar')->from('affiliator_register')->where('id_daftar', $id);
        $current_order_count = $this->db->get()->num_rows();

        if ($current_order_count < 1) {
            show_404();
        }

        $this->db->select('*')->from('affiliator_register')->where('id_daftar', $id);
        $current_account = $this->db->get()->row();
        $data['product_active'] = $this->product_m->get_active_product();

        if (isset($_POST['register_status'])) {

            /* if($this->order_m->cek_order($id,$_POST['register_status']) == FALSE){
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Order telah diproses</p>');
				redirect('admin/orders/view/' . $id);
			} */

            //var_dump($this->input->post('register_status')); exit();

            if ($this->input->post('register_status') == "rejected") {

                //Status DELIVERED
                $data = array(
                    'status' => "rejected",
                );
                $this->db->where('id_daftar', $id);
                $this->db->update('affiliator_register', $data);

                $data1 = array(
                    'affiliate' => "rejected",
                    'affiliate_register_cooldown' => date('Y-m-d H:i:s', strtotime('+30 days')),
                );
                $this->db->where('id_customers', $current_account->id_customer);
                $this->db->update('customers', $data1);

                $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pendaftaran berhasil diupdate</p>');
                redirect('admin/affiliator/view/' . $id);
            }
            if ($this->input->post('register_status') == "approve") {

                // $randomunique = bin2hex(random_bytes(3));

                $this->db->select('voucher, kategori');
                $this->db->from('affiliator_register');
                $this->db->where('id_customer', $current_account->id_customer);
                $customer_data = $this->db->get()->row();

                if ($customer_data) {
                    $voucher_code = $customer_data->voucher;

                    if ($customer_data->kategori === 'asmarasana') {
                        $voucher_name = "Asmarasana";
                    } else {
                        $voucher_name = "Asmaradoor";
                    }

                    // Data untuk membuat voucher baru
                    $voucher_data = array(
                        'voucher_name' => $voucher_name . ' ' . $current_account->nama,
                        'voucher_code' => $voucher_code,
                        'discount_type' => 'percentage',
                        'discount_value' => 10,
                        'created_date' => date('Y-m-d H:i:s'),
                        'voucher_type' => 'normal promo',
                    );

                    $this->db->insert('vouchers', $voucher_data);
                    $data = array(
                        'status' => "approve",
                    );
                    $this->db->where('id_daftar', $id);
                    $this->db->update('affiliator_register', $data);

                    $data1 = array(
                        'affiliate' => "approve",
                    );
                    $this->db->where('id_customers', $current_account->id_customer);
                    $this->db->update('customers', $data1);

                    $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pendaftaran berhasil diupdate dan voucher baru telah dibuat</p>');
                    redirect('admin/affiliator/view/' . $id);
                } else {
                    $this->session->set_flashdata('error', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Data customer tidak ditemukan</p>');
                }
            }
        }
        $this->data['link'] = $this->affiliator_m->get_unique_link($current_account->id_customer);
        $this->data['affiliator'] = $this->affiliator_m->get_affiliator_register($id);
        $this->data['product_active'] = $this->affiliator_m->get_active_product();
        $this->data['subview'] = 'admin/affiliator/view';
        $this->load->view('admin/templates/header', $this->data_header);
        $this->load->view('admin/_layout_main', $this->data);
        $this->load->view('admin/templates/footer');
    }

    // Create Unique Link
    public function create_unique_link()
    {
        $product_id = $this->input->post('product_affiliate_choose');
        $unique_id = $this->input->post('unique');
        $customer_id = $this->input->post('customer_id');
        $name = $this->input->post('aff_name');

        $this->db->select('title, alias');
        $this->db->from('products');
        $this->db->where('id_products', $product_id);
        $product_name = $this->db->get()->row();

        $unique_link = base_url() . 'product/' . $product_name->alias . '/' . $unique_id;


        $data = array(
            'product_id' => $product_id,
            'product_name' => $product_name->title,
            'customer_id' => $customer_id,
            'affiliator_name' => $name,
            'unique_id' => $unique_id,
            'status' => 'Active',
            'link' => $unique_link,
            'open' => 0,
            'order' => 0,
            'created_date' => date('Y-m-d H:i:s')
        );
        $this->db->insert('affiliator_link', $data);


        // Redirect kembali ke halaman sebelumnya
        redirect($_SERVER['HTTP_REFERER']);
    }

    // Update Link
    public function update_link()
    {
        $claimId = $this->input->post('claim_id');
        $newLink = $this->input->post('new_link');

        // Perbarui link_bukti pada tabel claim_garansi
        $this->db->set('link_bukti', $newLink);
        $this->db->where('id_claim', $claimId);
        $this->db->update('claim_garansi');

        //logging
        $user_id = $this->session->userdata('admin')['id'];

        $activity = 'User mengedit link bukti claim garansi (' . $claimId . ')';


        log_activity($user_id, $activity);

        // Redirect kembali ke halaman sebelumnya
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function update_category()
    {
        // Get the submitted data from the form
        $affiliator_id = $this->input->post('affiliator_id');
        $kategori_affiliator = $this->input->post('kategori_affiliator');

        // Check if affiliator exists
        $this->db->select('*')->from('affiliator_register')->where('id_daftar', $affiliator_id);
        $affiliator = $this->db->get()->row();

        if (!$affiliator) {
            // If affiliator does not exist, show an error or redirect
            $this->session->set_flashdata('error', 'Affiliator not found');
            redirect('admin/affiliator/view/' . $affiliator_id);
        }

        // Update the affiliator category in the database
        $data = array(
            'kategori' => $kategori_affiliator
        );
        $this->db->where('id_daftar', $affiliator_id);
        $this->db->update('affiliator_register', $data);

        // Set success message and redirect back to the view page
        $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Kategori affiliator berhasil diperbarui</p>');
        redirect('admin/affiliator/view/' . $affiliator_id);
    }

    public function search_customer()
    {
        $query = $this->input->get('query'); // Ambil parameter query dari URL

        if ($query) {
            // Query langsung ke database tanpa model
            $this->db->select('id_customers, name, email, phone');
            $this->db->from('customers');
            $this->db->like('name', $query);
            $this->db->or_like('email', $query);
            $this->db->limit(5); // Batas hasil yang diambil (opsional)

            $result = $this->db->get(); // Jalankan query

            if ($result->num_rows() > 0) {
                echo json_encode($result->result_array());
            } else {
                echo json_encode([]); // Tidak ada hasil
            }
        } else {
            echo json_encode([]);
        }
    }

    public function register_affiliator()
    {
        // Tambahkan log untuk debug

        $id_customer = (int) $this->input->post('id_customer');

        // Validasi ID customer
        if ($id_customer <= 0) {
            echo json_encode(array('status' => 'error', 'message' => 'ID customer tidak valid.'));
            return;
        }

        $nama = $this->input->post('nama');
        $referral = 'LACI' . strtoupper(substr($nama, 0, 3));
        $voucher = 'LACI' . strtoupper(substr($nama, 0, 3));
        $kategori = $this->input->post('kategori');

        // Data untuk insert
        $data = array(
            'id_customer' => $id_customer,
            'nama' => $this->input->post('nama'),
            'no_telpon' => $this->input->post('no_telpon'),
            'email' => $this->input->post('email'),
            'sosial_media' => $this->input->post('sosial_media'),
            'kategori' => $this->input->post('kategori'),
            'referral' => $referral,
            'voucher' => $voucher,
            'account_type' => $this->input->post('bank_name'),
            'account_name' => $this->input->post('account_name'),
            'account_number' => $this->input->post('account_number'),
            'status' => $this->input->post('status'),
            'created' => date('Y-m-d H:i:s')
        );

        // Cek apakah insert berhasil
        if (!$this->db->insert('affiliator_register', $data)) {
            log_message('error', 'Error insert data: ' . $this->db->last_query());
            echo json_encode(array('status' => 'error', 'message' => 'Gagal menyimpan data.'));
            return;
        }

        // Update data customer
        $data_customer = array(
            'affiliate' => $this->input->post('status'),
            'affiliate_register_date' => date('Y-m-d H:i:s')
        );

        if ($kategori === 'asmarasana') {
            $voucher_name = "Asmarasana";
        } else {
            $voucher_name = "Asmaradoor";
        }

        // Data untuk membuat voucher baru
        $voucher_data = array(
            'voucher_name' => $voucher_name . ' ' . $nama,
            'voucher_code' => $voucher,
            'discount_type' => 'percentage',
            'discount_value' => 10,
            'created_date' => date('Y-m-d H:i:s'),
            'voucher_type' => 'normal promo',
        );

        $this->db->insert('vouchers', $voucher_data);

        $this->db->where('id_customers', $id_customer);
        if (!$this->db->update('customers', $data_customer)) {
            log_message('error', 'Error update data customer: ' . $this->db->last_query());
            echo json_encode(array('status' => 'error', 'message' => 'Gagal mengupdate data customer.'));
            return;
        }

        $this->session->set_flashdata('success', 'Affiliator berhasil ditambahkan');

        // Kembalikan respons JSON dengan pengalihan
        echo json_encode(array('status' => 'success', 'redirect' => base_url('admin/affiliator')));
    }

    public function delete_product($id)
    {

        try {
            $this->db->where('id', $id);
            $this->db->delete('affiliator_product');

            $response = array(
                'status' => 'success',
                'message' => 'Record deleted successfully'
            );
            echo json_encode($response);
        } catch (Exception $e) {
            $response = array(
                'status' => 'error',
                'message' => 'Error deleting record: ' . $e->getMessage()
            );
            echo json_encode($response);
        }
    }
}

https://t.me/RX1948 - 2025