<?php 

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

class Store 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;
        }
    }


    // * get store credit list
    public function get_store_credit_list(){
        
        request_method('GET');

        $credits = $this->cm->select_multiple_where('id,credits,og_price,price,discount',['remove' => '0'], 'ASC', 'CAST(credits AS UNSIGNED)', 'store');

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

    // * complete credit purchase with Razorpay verification
    public function complete_credit_purchase(){

        // Ensure the request method is POST
        request_method('POST');

        // Get authenticated user details
        $user = $this->get_user_details();
        if (empty($user) || empty($user['id'])) {
            echo json_encode([
                'status' => '0',
                'message' => 'User authentication failed.'
            ]); exit;
        }

        $userId = $user['id'];



        // Get POST data
        $transactionId = $this->input->post('transactionId');
        $amount = $this->input->post('amount');
        $plan_id = $this->input->post('plan_id');

        // 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');

        // payment status
        $payment_status = $this->input->post('payment_status');

        // 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;
        }

        // Fetch selected plan
        $plan = $this->db->get_where('store', ['remove' => '0', 'id' => $plan_id])->row_array();

        if(empty($plan)){
            echo json_encode([
                'status' => '0',
                'message' => 'Invalid plan selected.'
            ]); exit;
        }

        $data = array(
            'transaction_id' => $transactionId,
            'user_id' => $userId,
            'amount_paid' => $amount,
            'plan_id' => $plan['id'],
            'points_user' => (float) $plan['credits'],
            'razorpay_order_id' => $razorpay_order_id,
            'razorpay_payment_id' => $razorpay_payment_id,
            'razorpay_signature' => $razorpay_signature,
            'payment_status' => $payment_status
        );

        $referrer_bonus = false;

        // Handle referral
        $referral = $this->db->get_where('referral_tracking', ['referee_id' => $userId])->row_array();
        
        if(!empty($referral)) {

            $data['referrer_id'] = $referral['referrer_id'];
            $data['referrer_type'] = $referral['referrer_type'];

            $data['points_referrer'] = 0;

            if ($referral['referrer_type'] == 'partner') {
                $data['points_referrer'] = round((5 / 100) * $plan['credits'], 2);
                $referrer_bonus = true;
            } else {
                $exists = $this->db->get_where('store_transaction_history', [
                    'user_id' => $userId,
                    'referrer_id' => $referral['referrer_id']
                ])->row_array();
    
                if (empty($exists)) {
                    $data['points_referrer'] = round((5 / 100) * $plan['credits'], 2);
                    $referrer_bonus = true;
                }
            }
            
        } else {
            $data['points_referrer'] = 0;
        }

        
    // Store transaction
    $this->db->trans_start();
    $this->db->insert('store_transaction_history', $data);
    $transaction_id = $this->db->insert_id();

    if (!$transaction_id) {
        $this->db->trans_complete();
        echo json_encode([
            'status' => '0',
            'message' => 'Failed to record transaction'
        ]); exit;
    }

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

    $this->db->insert('user_wallet_history', [
        'user_id' => $userId,
        'type' => 'credit_purchase',
        'description' => 'User store credit purchase',
        'coins' => $data['points_user'],
        'from' => $user['wallet'],
        'to' => $new_wallet,
        'store_transaction_id' => $transaction_id,
        'created' => date('Y-m-d H:i:s')
    ]);

    // Update referrer wallet
    if (!empty($referral) && $referrer_bonus) {
        $referrer = $this->db->get_where('users', ['id' => $data['referrer_id']])->row_array();
        if ($referrer) {
            $new_referrer_wallet = $referrer['wallet'] + $data['points_referrer'];
            $this->db->update('users', ['wallet' => $new_referrer_wallet], ['id' => $referrer['id']]);

            $this->db->insert('user_wallet_history', [
                'user_id' => $referrer['id'],
                'type' => 'referrer_credit_purchase',
                'description' => 'Referrer reward from store credit purchase',
                'coins' => $data['points_referrer'],
                'from' => $referrer['wallet'],
                'to' => $new_referrer_wallet,
                'store_transaction_id' => $transaction_id,
                'created' => date('Y-m-d H:i:s')
            ]);
        }
    }

    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        echo json_encode([
            'status' => '0',
            'message' => 'Transaction failed. Please try again.'
        ]); exit;
    }

    echo json_encode([
        'status' => '1',
        'message' => 'Transaction successful and verified.'
    ]); exit;

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

        // if($ins){
        //     // Update user wallet
        //     $new_wallet = $user['wallet'] + $data['points_user'];
        //     $this->db->update('users', ['wallet' => $new_wallet], ['id' => $userId]);

        //     // entry in user_wallet_history
        //     // Log coin assignment
        //     $entry = [
        //         'user_id' => $userId,
        //         'type' => 'credit_purchase',
        //         'description' => 'User store credit purchase',
        //         'coins' => $data['points_user'],
        //         'from' => $user['wallet'],
        //         'to' => $new_wallet,
        //         'store_transaction_id' => $ins,
        //         'created' => date('Y-m-d H:i:s')
        //     ];

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



        //     // Handle referral wallet update
        //     if (!empty($referral) && $referrer_bonus) {
        //         $referrer = $this->db->get_where('users', ['id' => $data['referrer_id']])->row_array();
        //         $new_referrer_wallet = $referrer['wallet'] + $data['points_referrer'];
        //         $this->db->update('users', ['wallet' => $new_referrer_wallet], ['id' => $referrer['id']]);

        //         $entry = [
        //             'user_id' => $referrer['id'],
        //             'type' => 'referrer_credit_purchase',
        //             'description' => 'referrer store credit purchase',
        //             'coins' => $data['points_referrer'],
        //             'from' => $referrer['wallet'],
        //             'to' => $new_referrer_wallet,
        //             'store_transaction_id' => $ins,
        //             'created' => date('Y-m-d H:i:s')
        //         ];
    
        //         $this->db->insert('user_wallet_history', $entry);
    
        //     }

        //     echo json_encode([
        //         'status' => '1',
        //         'message' => 'Transaction successful & verified',
        //     ]); exit;
        // } else {
        //     echo json_encode([
        //         'status' => '0',
        //         'message' => 'Transaction failed'
        //     ]); exit;
        // }
    }



    // * get store transaction history 
    public function get_store_transaction_history() {
        request_method('GET');
    
        $user = $this->get_user_details();
        $user_id = $user['id'];
    
        // Fetch transactions where the user is the purchaser
        $user_transactions = $this->db->select("
                store_transaction_history.id, 
                store_transaction_history.transaction_id, 
                store_transaction_history.user_id, 
                store_transaction_history.amount_paid, 
                store_transaction_history.plan_id, 
                store_transaction_history.points_user AS points_earned, 
                store_transaction_history.referrer_id, 
                store_transaction_history.referrer_type, 
                store_transaction_history.created_at, 
                'purchase' AS transaction_type,
                u1.name AS user_name, 
                u2.name AS referrer_name
            ")
            ->from('store_transaction_history')
            ->join('users AS u1', 'u1.id = store_transaction_history.user_id', 'left')  // Get user name
            ->join('users AS u2', 'u2.id = store_transaction_history.referrer_id', 'left') // Get referrer name
            ->where('store_transaction_history.user_id', $user_id)
            ->order_by('store_transaction_history.created_at', 'DESC')
            ->get()
            ->result_array();
    
        // Fetch transactions where the user is the referrer
        $referrer_transactions = $this->db->select("
                store_transaction_history.id, 
                store_transaction_history.transaction_id, 
                store_transaction_history.user_id, 
                store_transaction_history.amount_paid, 
                store_transaction_history.plan_id, 
                store_transaction_history.points_referrer AS points_earned, 
                store_transaction_history.referrer_id, 
                store_transaction_history.referrer_type, 
                store_transaction_history.created_at, 
                'referral' AS transaction_type,
                u1.name AS user_name, 
                u2.name AS referrer_name
            ")
            ->from('store_transaction_history')
            ->join('users AS u1', 'u1.id = store_transaction_history.user_id', 'left') // Get user name
            ->join('users AS u2', 'u2.id = store_transaction_history.referrer_id', 'left') // Get referrer name
            ->where('store_transaction_history.referrer_id', $user_id)
            ->order_by('store_transaction_history.created_at', 'DESC')
            ->get()
            ->result_array();
    
        // Combine both results
        $transactions = array_merge($user_transactions, $referrer_transactions);
    
        // Sort by created_at (latest first)
        usort($transactions, function ($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });
    
        if (!empty($transactions)) {
            echo json_encode([
                'status' => '1',
                'message' => 'Transaction history found',
                'details' => $transactions
            ]);
        } else {
            echo json_encode([
                'status' => '0',
                'message' => 'No transactions found'
            ]);
        }
        exit;
    }


    // spin wheel
    /*
        1. get spin wheel values 
        2. get a spin (transactionId , amount store in database)
        3. spin wheel reward (check if spins avalible if it does , give reward)
        4. get_pending_spin_count
    */
    
    
    public function get_spin_wheel(){
        request_method('GET');
    
        $user = $this->get_user_details();

        $data = $this->db->get_where('spin_wheel')->row_array();

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

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


    public function get_new_spin(){
        request_method('POST');

        $user = $this->get_user_details();

        $request = array(
            'transactionId' => true,
            'amount' => true
        );

        $userId = $user['id'];

        $request['userId'] = $userId;

        // spin count transaction 
        $add_record = $this->db->insert('spin_count_transactions', $request);

        if($add_record){
            $new_spin_count = $user['pending_spin_count'] + 1;
            $upd = $this->db->update('users', ['pending_spin_count' => $new_spin_count], ['id' => $userId]);

            $get_user = $this->db->get_where('users', ['id' => $userId])->row_array();

            echo json_encode([
                'status' => '1',
                'message' => 'spin count increased',
                'details' => array(
                    'spin_count' => $get_user['pending_spin_count']
                )
            ]);exit;
        }

        echo json_encode([
            'status' => '0', 
            'message' => 'Failed to add spin count transaction']);

    }


    public function spin_wheel_reward(){
        request_method('POST');
    
        $user = $this->get_user_details();

        if($user['pending_spin_count'] <= 0){
            echo json_encode([
                'status' => '0',
                'message' => 'invalid spin count'
            ]);exit;
        }

        $user_id = $user['id'];

        $winning = $this->input->post('reward');

        $new_wallet = $user['wallet'] + $winning;

        $new_spin_count = $user['pending_spin_count'] - 1;
 
        $upd = $this->db->update('users', ['wallet' => $new_wallet], ['id' => $user_id]);

        if($upd){

            $this->db->update('users', ['pending_spin_count' => $new_spin_count], ['id' => $user_id]);
            
            echo json_encode([
                'status' => '1',
                'message' => 'wallet updated'
            ]);exit;
        }

        echo json_encode([
            'status' => '0',
            'message' => 'wallet not updated'
        ]);exit;

    }


    public function get_pending_spin_count(){
        request_method('GET');
    
        $user = $this->get_user_details();

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

}







// public function complete_credit_purchase()
// {
//     // Ensure the request method is POST
//     request_method('POST');

//     // Get authenticated user details
//     $user = $this->get_user_details();
//     if (empty($user) || empty($user['id'])) {
//         return $this->json_response(0, 'User authentication failed.');
//     }
//     $userId = $user['id'];

//     // Required POST parameters
//     $required_fields = ['transactionId', 'amount', 'plan_id', 'razorpay_order_id', 'razorpay_payment_id', 'razorpay_signature', 'payment_status'];
//     foreach ($required_fields as $field) {
//         if (!$this->input->post($field)) {
//             return $this->json_response(0, "Missing required field: {$field}");
//         }
//     }

//     // Sanitize input
//     $transactionId = trim($this->input->post('transactionId'));
//     $amount = (float) $this->input->post('amount');
//     $plan_id = (int) $this->input->post('plan_id');
//     $razorpay_order_id = trim($this->input->post('razorpay_order_id'));
//     $razorpay_payment_id = trim($this->input->post('razorpay_payment_id'));
//     $razorpay_signature = trim($this->input->post('razorpay_signature'));
//     $payment_status = trim($this->input->post('payment_status'));

//     // Signature verification
//     $key_secret = 'Eb1byki59nUdw4sXEH4MeGTA'; // Consider moving this to a config/env file
//     $generated_signature = hash_hmac('sha256', "{$razorpay_order_id}|{$razorpay_payment_id}", $key_secret);

//     if (!hash_equals($generated_signature, $razorpay_signature)) {
//         return $this->json_response(0, 'Razorpay signature verification failed.');
//     }

//     // Fetch plan details
//     $plan = $this->db->get_where('store', ['remove' => '0', 'id' => $plan_id])->row_array();
//     if (empty($plan)) {
//         return $this->json_response(0, 'Invalid plan selected.');
//     }

//     // Prepare transaction data
//     $data = [
//         'transaction_id' => $transactionId,
//         'user_id' => $userId,
//         'amount_paid' => $amount,
//         'plan_id' => $plan_id,
//         'points_user' => (float) $plan['credits'],
//         'razorpay_order_id' => $razorpay_order_id,
//         'razorpay_payment_id' => $razorpay_payment_id,
//         'razorpay_signature' => $razorpay_signature,
//         'payment_status' => $payment_status
//     ];

//     $referrer_bonus = false;

//     // Handle referral
//     $referral = $this->db->get_where('referral_tracking', ['referee_id' => $userId])->row_array();
//     if (!empty($referral)) {
//         $data['referrer_id'] = $referral['referrer_id'];
//         $data['referrer_type'] = $referral['referrer_type'];

//         $data['points_referrer'] = 0;

//         if ($referral['referrer_type'] == 'partner') {
//             $data['points_referrer'] = round((5 / 100) * $plan['credits'], 2);
//             $referrer_bonus = true;
//         } else {
//             $exists = $this->db->get_where('store_transaction_history', [
//                 'user_id' => $userId,
//                 'referrer_id' => $referral['referrer_id']
//             ])->row_array();

//             if (empty($exists)) {
//                 $data['points_referrer'] = round((5 / 100) * $plan['credits'], 2);
//                 $referrer_bonus = true;
//             }
//         }
//     } else {
//         $data['points_referrer'] = 0;
//     }

//     // Store transaction
//     $this->db->trans_start();
//     $this->db->insert('store_transaction_history', $data);
//     $transaction_id = $this->db->insert_id();

//     if (!$transaction_id) {
//         $this->db->trans_complete();
//         return $this->json_response(0, 'Failed to record transaction.');
//     }

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

//     $this->db->insert('user_wallet_history', [
//         'user_id' => $userId,
//         'type' => 'credit_purchase',
//         'description' => 'User store credit purchase',
//         'coins' => $data['points_user'],
//         'from' => $user['wallet'],
//         'to' => $new_wallet,
//         'store_transaction_id' => $transaction_id,
//         'created' => date('Y-m-d H:i:s')
//     ]);

//     // Update referrer wallet
//     if (!empty($referral) && $referrer_bonus) {
//         $referrer = $this->db->get_where('users', ['id' => $data['referrer_id']])->row_array();
//         if ($referrer) {
//             $new_referrer_wallet = $referrer['wallet'] + $data['points_referrer'];
//             $this->db->update('users', ['wallet' => $new_referrer_wallet], ['id' => $referrer['id']]);

//             $this->db->insert('user_wallet_history', [
//                 'user_id' => $referrer['id'],
//                 'type' => 'referrer_credit_purchase',
//                 'description' => 'Referrer reward from store credit purchase',
//                 'coins' => $data['points_referrer'],
//                 'from' => $referrer['wallet'],
//                 'to' => $new_referrer_wallet,
//                 'store_transaction_id' => $transaction_id,
//                 'created' => date('Y-m-d H:i:s')
//             ]);
//         }
//     }

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

//     if ($this->db->trans_status() === FALSE) {
//         return $this->json_response(0, 'Transaction failed. Please try again.');
//     }

//     return $this->json_response(1, 'Transaction successful and verified.');
// }

/**
 * Helper function to send JSON responses
 */
// private function json_response($status, $message)
// {
//     echo json_encode([
//         'status' => (string) $status,
//         'message' => $message
//     ]);
//     exit;
// }
