<?php

defined('BASEPATH') or exit('No direct script access allowed');
header('Content-Type: application/json');

class Users extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        date_default_timezone_set('Asia/Kolkata');

        
        // Enable CORS
        header("Access-Control-Allow-Origin: https://mrit-24277.web.app");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        header("Access-Control-Allow-Headers: Content-Type, Authorization, auth-token");
        
        // Handle preflight OPTIONS request
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit;
        }

        if ((!isset($_SERVER['HTTP_AUTH_TOKEN'])) || empty($_SERVER['HTTP_AUTH_TOKEN'])) {
            echo json_encode([
                'status' => '0',
                'message' => 'auth token required',
                'details' => []
            ]);
            exit;
        }
    }


    // ? check user 
    protected function get_user_details()
    {
        $valid = $this->cm->search_single_where(['auth_token' => $_SERVER['HTTP_AUTH_TOKEN']], 'user_tokens');
        if (empty($valid)) {
            echo json_encode([
                'status' => '0',
                'message' => 'invalid auth token',
                'details' => []
            ]);
            exit;
        } else {
            $user = $this->cm->search_single_where(['id' => $valid['user_id']], 'users');

            return $user;
        }
    }


    // * add user referrel code 
    public function add_referral_code() {
        
        request_method('POST');
    
        // user 
        $user = $this->get_user_details();
        if (!$user) {
            echo json_encode([
                'status' => '0',
                'message' => 'User authentication failed'
            ]);
            exit;
        }
    
        $referral_code = $this->input->post('referral_code');
    
        if (empty($referral_code)) {
            echo json_encode([
                'status' => '0',
                'message' => 'Referral code is required'
            ]);
            exit;
        }
    
        // referral
        $check_validity = $this->db->get_where('users', ['referral_code' => $referral_code])->row_array();
    
        if (empty($check_validity) || ($check_validity['id'] == $user['id'])) {
            echo json_encode([
                'status' => '0',
                'message' => 'Invalid referral code'
            ]);
            exit;
        }
    
        $upd = $this->db->update('users', ['referred_by' => $check_validity['id']], ['id' => $user['id']]);
    
        if ($upd) {

            $data = array(
                'referrer_id' => $check_validity['id'],
                'referee_id' => $user['id'],
                'referral_code' => $check_validity['referral_code'],
                'referrer_type' => $check_validity['user_type']
            );

            $ins = $this->db->insert('referral_tracking' , $data);


            echo json_encode([
                'status' => '1',
                'message' => 'Referral code added successfully'
            ]);

        } else {
            
            echo json_encode([
                'status' => '0',
                'message' => 'Failed to add referral code! Try again later'
            ]);

        }
        exit;
    }
    

    // * get user wallet 
    public function get_wallet()
    {
        request_method('GET');

        $user = $this->get_user_details();

        echo json_encode([
            'status' => '1',
            'message' => 'data found',
            'details' => $user['wallet']
        ]);
        exit;
    }


    // * app rated update
    public function has_rated(){

        request_method('GET');

        $user = $this->get_user_details();

        if($user['rated'] == 'yes'){
            echo json_encode([
                'status' => '0',
                'message' => 'user has rated the app'
            ]);exit;
        }

        $upd = $this->db->update('users', ['rated' => 'yes'], ['id' => $user['id']]);

        if($upd){

            // get reward for app rating
            $reward = $this->db->get_where('coins_rewards_settings', ['type' => 'app_rating'])->row_array();
            
            // upadte wallet 
            $new_wallet = $user['wallet'] + $reward['coins']; // initial 20 
            $this->db->update('users', ['wallet' => $new_wallet], ['id' => $user['id']]);

            $this->db->insert('user_wallet_history', [
                'user_id' => $user['id'],
                'type' => 'has_rated',
                'description' => 'user rated',
                'coins' => $reward['coins'],
                'from' => $user['wallet'],
                'to' => $new_wallet,
                'created' => date('Y-m-d H:i:s')
            ]);

            echo json_encode([
                'status' => '1',
                'message' => 'user rated successfully'
            ]);exit;
        }else{
            echo json_encode([
                'status' => '0',
                'message' => 'data not updated'
            ]);exit;
        }


    }


    // * get users coins rewards settings
    public function get_user_reward_settings(){

        request_method('GET');

        $user = $this->get_user_details();


        $user_type = $user['user_type'];

        $settings = $this->db->get_where('referral_rewards_settings',['user_type' => $user_type])->row_array();

        if(empty($settings)){
            echo json_encode([
                'status' => '0',
                'message' => 'data not found'
            ]);exit;
        }

        echo json_encode([
            'status' => '1',
            'message' => 'data found',
            'details' => $settings['reward_coins']
        ]);exit;
        

    }



    // * change user password 
    public function change_password()
    {

        request_method('POST');

        $request = check_parameter([

            'old_password' => true,
            'new_password' => true

        ]);

        $user = $this->get_user_details();

        if ($user['password'] == md5($request['old_password'])) {

            if($request['old_password'] == $request['new_password']){

                echo json_encode([
                    'status' => '0',
                    'message' => 'New password can not be same as old password.'
                ]);
                exit;

            }

            $this->cm->update_where([
                
                'password' => md5($request['new_password']),
                
            ], ['id' => $user['id']], 'users');

            echo json_encode([
                'status' => '1',
                'message' => 'Password has been updated successfully.'
            ]);
            exit;
            
        } else {

            echo json_encode([
                'status' => '0',
                'message' => 'Old password does not match.'
            ]);
            exit;
        }
    }


    // * get ads 
    public function get_ads(){
        request_method('GET');

        $data = $this->db->get_where('ads', ['remove' => '0'])->result_array();

        if(empty($data)){
            echo json_encode([
                'status' => '0',
                'message' => 'data not found'
            ]);exit;
        }

        echo json_encode([
            'status' => '1',
            'message' => 'data found',
            'details' => $data
        ]);exit;

    }

    
    // * watch ads
    public function watch_ads(){

        /*
        1. check valid ad
        2. entry in ads_watch_histroy
        3. increase 'watched' in ads 
        4. increase 'wallet' in users 
        */

        request_method('POST');

        $user = $this->get_user_details();

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

        $adv = $this->db->get_where('ads', ['id' => $ad_id, 'remove' => '0'])->row_array();
        
        if(empty($adv)){
            echo json_encode([
                'status' => '0',
                'message' =>'data not found'
            ]);exit;

        }


        $data = array(
            'user_id' => $user['id'],
            'ad_id' => $ad_id,
            'watch_credit' => $adv['watch_credit']
        );

        $ins = $this->db->insert('ads_watch_history', $data);

        if($ins){

            $watched_count = $adv['watched'] + 1;

            $this->db->update('ads', ['watched' => $watched_count], ['id' => $ad_id]);

            // $new_wallet = $user['wallet'] + $adv['watch_credit'];

            // $this->db->update('users', ['wallet' => $new_wallet], ['id' => $user['id']]);

            // Log coin assignment
            // $entry = [
            //     'user_id' =>  $user['id'],
            //     'type' => 'watch_ad',
            //     'coins' => $adv['watch_credit'],
            //     'from' =>  $user['wallet'],
            //     'to' => $user['wallet'] + $adv['watch_credit'],
            //     'ad_id' => $ad_id,
            //     'created' => date('Y-m-d H:i:s')
            // ];

            // $this->db->insert('user_wallet_history', $entry);


            echo json_encode([
                'status' => '1',
                'message' => 'Record added, Wallet updated'
            ]);exit;

        }

        echo json_encode([
            'status' => '0',
            'message' => 'failed to add record & update wallet'
        ]);exit;

        
    }


    // * get latest app versions 
    public function get_latest_app_version(){
    
        request_method('GET');
    
        // user 
        $user = $this->get_user_details();


        // Fetch the latest app version from the database
        $query = $this->db->order_by('id', 'DESC')->get('app_versions', 1);
        $latest_version = $query->row();

        // Check if a version exists
        if ($latest_version) {
            echo json_encode([
                'status' => '1',
                'message' => 'Latest app version found',
                'details' => array(
                    'version_number' => $latest_version->version_number,
                    'download_url' => $latest_version->file_path
                )
            ]);
        } else {
            echo json_encode([
                'status' => '0',
                'message' => 'No app version found'
            ]);
        }

        exit;
        
    }

    // * get latest app versions 
    public function get_payment_key(){
    
        request_method('GET');
    
        // user 
        $user = $this->get_user_details();


        $key = $this->db->get_where('keys', ['type' => 'payment'])->row_array();

        // Check if a version exists
        if ($key) {
            echo json_encode([
                'status' => '1',
                'message' => 'Payment gateway key',
                'details' => array(
                    'key' => $key['key']
                )
            ]);
        } else {
            echo json_encode([
                'status' => '0',
                'message' => 'No app version found'
            ]);
        }

        exit;
        
    }


    // * welcome offer
    public function welcome_offer(){
        request_method('GET');

        $user = $this->get_user_details();

        if($user['welcome_offer_exist'] == 'yes'){

            echo json_encode([
                'status' => '1',
                'message' => 'welcome offer exists',
                'details' => array(
                    'name' => 'Welcome Offer',
                    'price' => '50',
                    'coins' => '100'
                ),
            ]);exit;
        }

        echo json_encode([
            'status' => '0',
            'message' => 'offer does not exist'
        ]);exit;

    }



    // * buy welcome offer
    public function buy_welcome_offer(){
        request_method('POST');

        $user = $this->get_user_details();

        $userId = $user['id'];

        if($user['welcome_offer_exist'] == 'no'){
            echo json_encode([
                'status' => '0',
                'message' => 'Welcome offer alreday used'
            ]);exit;
        }

        // Get POST data
        $transactionId = $this->input->post('transactionId');
        $amount = $this->input->post('amount');
        
        // Razorpay fields
        $razorpay_order_id = $this->input->post('razorpay_order_id');
        $razorpay_payment_id = $this->input->post('razorpay_payment_id');
        $razorpay_signature = $this->input->post('razorpay_signature');

        // Validate Razorpay fields
        if (empty($razorpay_order_id) || empty($razorpay_payment_id) || empty($razorpay_signature)) {
            echo json_encode([
                'status' => '0',
                'message' => 'Missing Razorpay verification details'
            ]); exit;
        }

        // Razorpay signature verification
        $key_secret = 'Eb1byki59nUdw4sXEH4MeGTA'; 
        $generated_signature = hash_hmac('sha256', $razorpay_order_id . "|" . $razorpay_payment_id, $key_secret);

        if (!hash_equals($generated_signature, $razorpay_signature)) {
            echo json_encode([
                'status' => '0',
                'message' => 'Razorpay signature verification failed'
            ]); exit;
        }

        // Welcome offer details (Hardcoded as per your `welcome_offer` API)
        $offer = [
            'name' => 'Welcome Offer',
            'price' => 50,  // Amount to be paid
            'coins' => 100   // Credits to be given
        ];

        // Insert transaction into store_transaction_history
        $data = [
            'transaction_id' => $transactionId,
            'user_id' => $userId,
            'amount_paid' => $amount,
            // 'plan_id' => 'welcome_offer',
            'points_user' => $offer['coins'],
            'razorpay_order_id' => $razorpay_order_id,
            'razorpay_payment_id' => $razorpay_payment_id,
            'razorpay_signature' => $razorpay_signature,
            'type' => 'welcome' // Identifies this as a welcome offer purchase
        ];

        $ins = $this->db->insert('store_transaction_history', $data);

        $store_id = $this->cm->last_id();

        if ($ins) {
            // Update user wallet with welcome offer coins
            $new_wallet = $user['wallet'] + $offer['coins'];
            $this->db->update('users', ['wallet' => $new_wallet, 'welcome_offer_exist' => 'no'], ['id' => $userId]);

            $this->db->insert('user_wallet_history', [
                'user_id' => $userId,
                'type' => 'welcome_offer',
                'description' => 'welcome offer',
                'coins' => $offer['coins'],
                'from' => $user['wallet'],
                'to' => $new_wallet,
                'store_transaction_id' => $store_id,
                'created' => date('Y-m-d H:i:s')
            ]);


            echo json_encode([
                'status' => '1',
                'message' => 'Welcome offer purchased successfully',
            ]); exit;
        } else {
            echo json_encode([
                'status' => '0',
                'message' => 'Transaction failed'
            ]); exit;
        }
    }



}
