<?php 

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

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


    // create razzorpay order 
    public function create_order() {

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

        // check user token 
        $user = $this->get_user_details();

        $userId = $user['id'];

        // Check and retrieve POST parameters
        $request = check_parameter(array(
            'amount' => true,
        ));

        $key_id = 'rzp_live_4iJV9mAuob8y4z';
        $key_secret = 'Eb1byki59nUdw4sXEH4MeGTA';
    
        $orderData = [
            'receipt' => uniqid(), // Unique receipt ID for each order
            'amount' => $request['amount'] * 100, // amount in paise 
            'currency' => 'INR',
            'payment_capture' => 1
        ];
    
        $ch = curl_init('https://api.razorpay.com/v1/orders');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD, $key_id . ':' . $key_secret);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($orderData));
    
        $response = curl_exec($ch);
    
        if(curl_errno($ch)){
            echo json_encode([
                'status' => false,
                'message' => 'Curl error: ' . curl_error($ch)
            ]);
            curl_close($ch);
            return;
        }
    
        curl_close($ch);
        $result = json_decode($response, true);
    
        if (isset($result['id'])) {
            echo json_encode([
                'status' => '1',
                'message' => 'Order created',
                'details' => array(
                    'order_id' => $result['id'],
                    'amount' => $orderData['amount'],
                    'currency' => 'INR',
                    'receipt' => $orderData['receipt']
                )
            ]);
        } else {
            echo json_encode([
                'status' => '0',
                'message' => 'Failed to create order',
                'response' => $result
            ]);
        }
    }



    // verify payment
    public function verify_payment(){

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

        // check user token 
        $user = $this->get_user_details();

        $userId = $user['id'];

        $key_secret = 'Eb1byki59nUdw4sXEH4MeGTA';
        // Receiving form-data using CI input->post
        $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');

        if (empty($razorpay_order_id) || empty($razorpay_payment_id) || empty($razorpay_signature)) {
            echo json_encode([
                'status' => '0',
                'message' => 'Missing required parameters'
            ]);
            return;
        }

        // Create signature hash
        $generated_signature = hash_hmac('sha256', $razorpay_order_id . "|" . $razorpay_payment_id, $key_secret);

        if (hash_equals($generated_signature, $razorpay_signature)) {
            echo json_encode([
                'status' => '1',
                'message' => 'Payment verified successfully'
            ]);
        } else {
            echo json_encode([
                'status' => '0',
                'message' => 'Payment verification failed!'
            ]);
        }
    }
    


}
