<?php 

defined('BASEPATH') or exit ('Direct script access not allowed');

require_once APPPATH . "core/My_Admin.php";

class Users extends My_Admin{

    public function __construct()
    {
        parent::__construct();

        date_default_timezone_set('Asia/Kolkata');
    }


    //  * users list
    public function index(){

        $this->load->view('admin/includes/header');
        $this->load->view('admin/users/view');
        $this->load->view('admin/includes/footer');

    }


    // * view user details
    public function view_details(){
        $user_id = $this->input->get('id');

        $data['details'] = $this->cm->search_single_where(['id' => $user_id], 'users');

        $this->load->view('admin/includes/header', $data);
        $this->load->view('admin/users/details');
        $this->load->view('admin/includes/footer');

    }


    // * datatable users list
    public function view_list()
    {
        $datas = $this->user->get_data_table(['register' => '1']);

        $final = [];
        $sno = $_POST['start'];
        foreach ($datas as $data) {
            $row = [];
            $row[] = ++$sno;
            $row[] = $data['name'];
            
            $row[] = $data['email'];
            $row[] = $data['wallet'];

            if($data['user_type'] == 'regular'){
                $row[] = '<button onclick="change_user_type('.$data['id'].', \'regular\')" class="btn btn-info btn-sm">Regular</button>';
            }else{
                $row[] = '<button onclick="change_user_type('.$data['id'].',\'partner\')" class="btn btn-success btn-sm">Partner</button>';
            }

            // $row[] = "<div class='btn-group' role='group' aria-label='Basic example'>
            //     <button type='button' onclick='openAssignCoinsModal(" . $data['id'] . ")' class='btn btn-primary'><i class='fa-solid fa-coins'></i></button>
            //     <button type='button' class='btn btn-info' onclick='window.location.href=\"".site_url('admin/users/wallet_history/'.$data['id'])."\"'><i class='fa-solid fa-clock-rotate-left'></i></button>
            //     <button type='button' class='btn btn-danger' onclick='deleteUser(" . $data['id'] . ")'><i class='fa-solid fa-trash'></i></button>
            // </div>";

            $row[] = "
                    <button type='button' onclick='openAssignCoinsModal(" . $data['id'] . ")' class='btn btn-success btn-sm' data-toggle='tooltip' title='Assign Coins'>
                        <i class='fa-solid fa-coins'></i>
                    </button>
                    <button type='button' class='btn btn-primary btn-sm' onclick='window.location.href=\"" . site_url('admin/users/wallet_history/' . $data['id']) . "\"' data-toggle='tooltip' title='View Wallet History'>
                        <i class='fa-solid fa-clock-rotate-left'></i>
                    </button>
                    <button type='button' class='btn btn-danger btn-sm' onclick='deleteUser(" . $data['id'] . ")' data-toggle='tooltip' title='Delete User'>
                        <i class='fa-solid fa-trash'></i>
                    </button>
                ";


            $final[] = $row;
        }

        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->user->count_all_data(['register' => '1']),
            "recordsFiltered" => $this->user->count_filtered_data(['register' => '1']),
            "data" => $final,
        );

        $this->output->set_content_type('application/json')->set_output(json_encode($output));

    
    }


    // !  change user type
    public function change_user_type(){
        
        request_method('POST');

        $request = check_parameter([
            'user_id' => true,
            'type' => true
        ]);

        if($request['type']  == 'regular'){
            $data['user_type'] = 'partner';
        }else{
            $data['user_type'] = 'regular';
        }

        $upd = $this->cm->update_where($data, ['id' => $request['user_id']], 'users');

        if($upd){
            echo json_encode([
                'status' => '1',
                'message' => 'user type changed',
            ]);exit;
        }
        echo json_encode([
            'status' => '0',
            'message' => 'failed, try again!'
        ]);exit;

    }


    // delete user
    // delete user
    public function delete_user()
    {
        request_method('POST');

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

        if (!$user_id) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User ID is required.'
            ]);
            return;
        }

        // Check if user exists
        $user = $this->cm->search_single_where(['id' => $user_id], 'users');
        if (!$user) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found.'
            ]);
            return;
        }

        // Soft delete: clear all user fields except id
        $anonymized_data = array_map(fn($v) => '', $user);  // clear all fields
        $anonymized_data['id'] = $user['id'];              // retain ID
        $anonymized_data['register'] = '0';
        $anonymized_data['deleted'] = '1';
        $anonymized_data['deleted_at'] = date('Y-m-d H:i:s');
        $anonymized_data['deleted_by'] = 'admin';

        $deleted = $this->cm->update_where($anonymized_data, ['id' => $user_id], 'users');

        if ($deleted) {
            echo json_encode([
                'status' => 'success',
                'message' => 'User deleted successfully.'
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'Failed to delete user.'
            ]);
        }
    }




    // ! coin assignment to users by admin 
    public function assign_coins()
    {
        $user_id = $this->input->post('user_id');
        $coins = $this->input->post('coins');
        // $coins = (int)$this->input->post('coins');
    
        if (!$user_id || $coins <= 0) {
            $response = ['status' => 'error', 'message' => 'Invalid input.'];
            return $this->output->set_content_type('application/json')->set_output(json_encode($response));
        }
    
        // Fetch current wallet balance before update
        $user = $this->db->get_where('users', ['id' => $user_id])->row_array();
        if (!$user) {
            $response = ['status' => 'error', 'message' => 'User not found.'];
            return $this->output->set_content_type('application/json')->set_output(json_encode($response));
        }
    
        $from_wallet = $user['wallet'];
        $to_wallet = $from_wallet + $coins;
    
        // Update wallet balance
        $this->db->set('wallet', 'wallet + ' . $coins, FALSE);
        $this->db->where('id', $user_id);
        $result = $this->db->update('users');
    
        if ($result) {
            // Log coin assignment
            $entry = [
                'user_id' => $user_id,
                'type' => 'admin',
                'from' => $from_wallet,
                'coins' => $coins,
                'to' => $to_wallet,
                'created' => date('Y-m-d H:i:s')
            ];
    
            $this->db->insert('user_wallet_history', $entry);
    
            $response = ['status' => 'success', 'message' => 'Coins assigned successfully.', 'new_wallet' => $to_wallet];
        } else {
            $response = ['status' => 'error', 'message' => 'Failed to assign coins.'];
        }
    
        $this->output->set_content_type('application/json')->set_output(json_encode($response));
    }

    
    public function wallet_history($user_id = null)
    {
        if (!$user_id) {
            show_404();
            return;
        }

        // Load user info for display
        $data['user'] = $this->cm->search_single_where(['id' => $user_id], 'users');

        if (!$data['user']) {
            show_404();
            return;
        }

        // Load page with DataTable
        $this->load->view('admin/includes/header', $data);
        $this->load->view('admin/users/wallet_history');  // you create this view (next step)
        $this->load->view('admin/includes/footer');
    }

    public function wallet_history_list($user_id = null)
{
    if (!$user_id) {
        echo json_encode(['data' => []]);
        return;
    }

    // Updated columns - no 'from'
    $columns = ['id', 'type', 'coins', 'to', 'created'];

    $limit = $this->input->post('length');
    $start = $this->input->post('start');
    $order_column_index = $this->input->post('order')[0]['column'];
    // We must map the index properly since DataTables will have Sr No in col 0, type col 1, coins col 2 ...
    // So order_column_index -1 because sr no is not from DB, or just fix in JS below (easier).
    // Let's just always order by 'created' descending regardless of user click for simplicity.
    $order_column = 'created';
    $order_dir = 'desc';
    $search_value = $this->input->post('search')['value'];

    // Total records count
    $this->db->where('user_id', $user_id);
    $totalData = $this->db->count_all_results('user_wallet_history');

    // Filtered count
    $this->db->where('user_id', $user_id);
    if (!empty($search_value)) {
        $this->db->group_start();
        $this->db->like('type', $search_value);
        $this->db->or_like('coins', $search_value);
        $this->db->or_like('to', $search_value);
        $this->db->or_like('created', $search_value);
        $this->db->group_end();
    }
    $totalFiltered = $this->db->count_all_results('user_wallet_history', false);

    // Fetch data with limit, offset, order by created desc
    $this->db->order_by($order_column, $order_dir);
    $this->db->limit($limit, $start);

    $query = $this->db->get();
    $data = [];
    foreach ($query->result() as $row) {
        $nestedData = [];
    
        // Map type codes to friendly text (plain text, no badges)
        $type_map = [
            'admin' => 'Admin Coins',
            'purchase' => 'Admin Videos',
            'credit_purchase' => 'Credit Purchase',
            'referrer_credit_purchase' => 'Referrer Credit Purchase',
            'welcome_offer' => 'Welcome Offer',
            'has_rated' => 'App Rated',
            'watch_ad' => 'Watch Ad',
            'refund' => 'Refund (Cancellation)',
            'referrer_purchase' => 'Referrer Purchase',
            'user_purchase' => 'User Purchase'
        ];
    
        $type_code = $row->type;
        $type_text = isset($type_map[$type_code]) ? $type_map[$type_code] : htmlspecialchars($type_code);
    
        $nestedData[] = $type_text;
    
        // Coins with plus/minus and colored text
        $coins = floatval($row->coins);
        if ($coins > 0) {
            $nestedData[] = "<span style='color:green;'>+{$coins}</span>";
        } elseif ($coins < 0) {
            $nestedData[] = "<span style='color:red;'>{$coins}</span>";
        } else {
            $nestedData[] = $coins;
        }
    
        $nestedData[] = htmlspecialchars($row->to);
        $nestedData[] = htmlspecialchars($row->created);

            // Only date without time
            // $date_only = date('Y-m-d', strtotime($row->created));
            // $nestedData[] = $date_only;
    
    
        $data[] = $nestedData;
    }
    
    

    $json_data = [
        "draw" => intval($this->input->post('draw')),
        "recordsTotal" => intval($totalData),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data
    ];

    echo json_encode($json_data);
}





    // CREATE TABLE `user_wallet_history` (
    //     `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    //     `user_id` INT NOT NULL,
    //     `type` ENUM('admin', 'purchase') NOT NULL,
    //      `from` DECIMAL(10,2) NOT NULL,
    //      `coins` DECIMAL(10,2) NOT NULL,
    //      `to` DECIMAL(10,2) NOT NULL,
    //     `created` DATETIME NOT NULL,
    //     FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE
    // ) 
    

    // ALTER TABLE `user_wallet_history`
    // ADD COLUMN `record_id` INT  DEFAULT NULL;
}
