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

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

class Admin_Api extends REST_Controller {

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

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

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

        $user_id = $verify_data['userdata']['id'];
        $user_type = $verify_data['userdata']['type'];

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

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

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

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

        $month_revenue = $this->Admin_model->get_month_revenue();
        $total_revenue = $this->Admin_model->get_total_revenue();

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

        $data = array(
            'total_users' => (int)$total_users,
            'total_affiliates' => (int)$total_affiliates,
            'total_vendors' => (int)$total_vendors,
            'pending_users' => (int)$pending_users,
            'pending_withdrawals' => (int)$pending_withdrawals,
            'total_withdrawals_amount' => number_format((float)$total_withdrawals_amount, 2, '.', ''),
            'today_clicks' => (int)$today_clicks,
            'today_sales' => (int)$today_sales,
            'month_revenue' => number_format((float)$month_revenue, 2, '.', ''),
            'total_revenue' => number_format((float)$total_revenue, 2, '.', ''),
            'recent_users' => $recent_users,
        );

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

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

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

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

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

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

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

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

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

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

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

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

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

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

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

        // Map status: 'paid' => '1', 'rejected' => '4' (based on Wallet_model status array)
        $status_code = ($status === 'paid') ? '1' : '4';

        $update_data = array(
            'status' => $status_code,
            'comment' => $admin_note,
            'updated_at' => date('Y-m-d H:i:s'),
        );

        $affected_rows = $this->Admin_model->update_withdrawal_status($request_id, $update_data);

        if ($affected_rows > 0) {
            $message = ($status === 'paid') ? 'Withdrawal request approved successfully' : 'Withdrawal request rejected successfully';
            $response = array(
                'status' => TRUE,
                'message' => $message,
            );
            $this->response($response, REST_Controller::HTTP_OK);
        } else {
            $response = array(
                'status' => FALSE,
                'message' => 'Failed to update withdrawal request status',
            );
            $this->response($response, REST_Controller::HTTP_NOT_MODIFIED);
        }
    }

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

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

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

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

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

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

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

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

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

        $recent_clicks = $this->db->query("SELECT * FROM click WHERE user_id='{$user_id}' ORDER BY click_date DESC LIMIT 10")->result_array();
        $user['recent_clicks'] = $recent_clicks;

        $recent_sales = $this->db->query("SELECT * FROM sale WHERE user_id='{$user_id}' ORDER BY sale_date DESC LIMIT 10")->result_array();
        $user['recent_sales'] = $recent_sales;

        unset($user['password']);

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

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

        if (empty($user_id) || !in_array($status, ['0', '1', '2'])) {
            $response = array(
                'status' => FALSE,
                'message' => 'Invalid parameters',
            );
            $this->response($response, 400);
            return;
        }

        $this->db->where('id', $user_id);
        $this->db->where('type', 'user');
        $affected_rows = $this->Admin_model->update_user_status($user_id, array('status' => $status));

        if ($affected_rows > 0) {
            $status_text = $status == '1' ? 'approved' : ($status == '0' ? 'pending' : 'blocked');
            
            $json = array(
                'status' => TRUE,
                'message' => "User status updated to {$status_text}",
            );
        } else {
            $json = array(
                'status' => FALSE,
                'message' => 'Failed to update user status',
            );
        }

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

        $where = "1=1";
        
        if ($status_filter == 'unpaid') {
            $where .= " AND wallet.status='unpaid'";
        } elseif ($status_filter == 'paid') {
            $where .= " AND wallet.status='paid'";
        }

        $total_count = $this->db->query("SELECT COUNT(*) as count FROM wallet WHERE {$where}")->row()->count;

        $requests = $this->db->query("
            SELECT wallet.*, users.firstname, users.lastname, users.username, users.email 
            FROM wallet 
            LEFT JOIN users ON wallet.user_id = users.id 
            WHERE {$where} 
            ORDER BY wallet.created_date DESC 
            LIMIT {$start_from}, {$limit}
        ")->result_array();

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

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

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

        $wallet_id = $this->post('wallet_id');
        $action = $this->post('action');

        if (empty($wallet_id) || !in_array($action, ['approve', 'reject'])) {
            $response = array(
                'status' => FALSE,
                'message' => 'Invalid parameters',
            );
            $this->response($response, 400);
            return;
        }

        if ($action == 'approve') {
            $update = $this->db->update('wallet', array('status' => 'paid', 'updated_date' => date('Y-m-d H:i:s')), array('id' => $wallet_id));
            $message = 'Withdrawal request approved';
        } else {
            $update = $this->db->update('wallet', array('status' => 'rejected', 'updated_date' => date('Y-m-d H:i:s')), array('id' => $wallet_id));
            $message = 'Withdrawal request rejected';
        }

        if ($update) {
            $json = array(
                'status' => TRUE,
                'message' => $message,
            );
        } else {
            $json = array(
                'status' => FALSE,
                'message' => 'Failed to update withdrawal request',
            );
        }

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

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

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

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

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

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

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

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

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

        $user_type = $verify_data['userdata']['type'];

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

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

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

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

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

}
