<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

class PaymentController extends ResourceController
{
    protected $format = 'json';
    protected $db;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
    }

    public function create_order() {
        //require_once APPPATH . 'ThirdParty/Razorpay/Razorpay.php'; 
        require_once APPPATH . 'ThirdParty/Razorpay/libs/Requests-2.0.4/library/Requests.php';
        
        \Requests::register_autoloader();
        
        $api = new Api(env('RAZORPAY_KEY_ID'), env('RAZORPAY_KEY_SECRET'));
        // Now you can use the namespace
        //$api = new \Razorpay\Api\Api(env('RAZORPAY_KEY_ID'), env('RAZORPAY_KEY_SECRET'));
    
        $amount = (int)$this->request->getPost('price') * 100; // Razorpay expects Paise
    
        $orderData = [
            'receipt'         => 'rcpt_' . time(),
            'amount'          => $amount,
            'currency'        => 'INR',
            'payment_capture' => 1 // Auto-capture payment
        ];
    
        try {
            $razorpayOrder = $api->order->create($orderData);
            return $this->response->setJSON([
                'status' => 1,
                'order_id' => $razorpayOrder['id'],
                'amount' => $razorpayOrder['amount']
            ]);
        } catch (\Exception $e) {
            return $this->response->setJSON(['status' => 0, 'message' => $e->getMessage()]);
        }
    }
    
    public function payment_update_wallet() {
        $api = new \Razorpay\Api\Api(env('RAZORPAY_KEY_ID'), env('RAZORPAY_KEY_SECRET'));
    
        $userId = $this->request->getPost('user_id');
        $credits = $this->request->getPost('credits');
        $orderId = $this->request->getPost('razorpay_order_id');
        $paymentId = $this->request->getPost('razorpay_payment_id');
        $signature = $this->request->getPost('razorpay_signature');
        $amountPaid = (int)$this->request->getPost('price');
        try {
            // 1. Verify Signature
            $attributes = [
                'razorpay_order_id' => $orderId,
                'razorpay_payment_id' => $paymentId,
                'razorpay_signature' => $signature
            ];
            $api->utility->verifyPaymentSignature($attributes);
    
            $userId = (int)$userId;
            $credits = (int)$credits;

            // 2. Start Transaction
            $db = \Config\Database::connect();
            $db->transStart();
    
            // Update Wallet in users table
            //$db->query("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?", [$credits, $userId]);
            
            $db->table('users')
               ->where('id', $userId)
               ->set('wallet_balance', "wallet_balance + $credits", FALSE) // FALSE tells CI4 not to add quotes around the math
               ->update();
    
            // Insert into transactions/payments table
            $db->table('payments')->insert([
                'user_id' => $userId,
                'razorpay_order_id' => $orderId,
                'razorpay_payment_id' => $paymentId,
                'razorpay_signature' => $signature,
                'amount' => $amountPaid,
                'credits_added' => $credits,
                'status' => 'success'
            ]);
    
            $db->transComplete();
            
            // 4. Verification Check
            if ($db->transStatus() === FALSE) {
                // If something went wrong, this will log the specific database error
                log_message('error', 'Database Transaction Failed: ' . json_encode($db->error()));
                return $this->response->setJSON(['status' => 0, 'message' => 'Database error occurred']);
            }

            return $this->response->setJSON(['status' => 1, 'message' => 'Wallet updated successfully']);
    
        } catch (\Exception $e) {
            return $this->response->setJSON(['status' => 0, 'message' => 'Signature Verification Failed: ' . $e->getMessage()]);
        }
    }

    public function webhook()
        {
            // 1. Get the raw body and signature
            $webhookBody = file_get_contents('php://input');
            $webhookSignature = $this->request->getHeaderLine('X-Razorpay-Signature');
            $webhookSecret = env('RAZORPAY_WEBHOOK_SECRET');
    
            $api = new Api(env('RAZORPAY_KEY_ID'), env('RAZORPAY_KEY_SECRET'));
    
            try {
                // 2. Verify the signature to ensure it's from Razorpay
                $api->utility->verifyWebhookSignature($webhookBody, $webhookSignature, $webhookSecret);
                
                $data = json_decode($webhookBody, true);
    
                // 3. Process only 'payment.captured' event
                if ($data['event'] === 'payment.captured') {
                    $paymentEntity = $data['payload']['payment']['entity'];
                    $orderId = $paymentEntity['order_id'];
                    $paymentId = $paymentEntity['id'];
    
                    $db = \Config\Database::connect();
    
                    // 4. Check if this order was already processed (Idempotency)
                    $existing = $db->table('payments')
                                   ->where('razorpay_order_id', $orderId)
                                   ->where('status', 'success')
                                   ->get()
                                   ->getRow();
    
                    if (!$existing) {
                        // Logic to find user_id and credits based on order_id
                        // Note: You should ideally store order info in a table when creating it 
                        // or pass user_id/credits in Razorpay 'notes'
                        $userId = $paymentEntity['notes']['user_id'] ?? null;
                        $credits = $paymentEntity['notes']['credits'] ?? 0;
    
                        if ($userId) {
                            $db->transStart();
                            
                            // Update Wallet
                            $db->query("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?", [$credits, $userId]);
    
                            // Record in History
                            $db->table('payments')->insert([
                                'user_id' => $userId,
                                'razorpay_order_id' => $orderId,
                                'razorpay_payment_id' => $paymentId,
                                'amount' => $paymentEntity['amount'] / 100,
                                'credits_added' => $credits,
                                'status' => 'success'
                            ]);
    
                            $db->transComplete();
                        }
                    }
                }
    
                // Razorpay needs a 200 OK response to stop retrying
                return $this->response->setStatusCode(200)->setJSON(['status' => 'success']);
    
            } catch (SignatureVerificationError $e) {
                // Log error and return 400 so Razorpay knows it failed
                log_message('error', 'Webhook Signature Failed: ' . $e->getMessage());
                return $this->response->setStatusCode(400)->setJSON(['status' => 0]);
            }
        }
        
    /*public function get_wallet()
    {
        //$data = $this->request->getJSON(true);(int)($data['duration_minutes'] ?? 10);
        $userId = (int)($this->request->getVar('user_id'));
        log_message('debug', 'get_wallet Line 22 : ' . $userId);
        if (!$userId) {
            return $this->response->setJSON([
                'status' => 0,
                'message' => 'User ID missing'
            ]);
        }
    
        $user = $this->db->table('users')->where('id', $userId)->get()->getRowArray();
    log_message('debug', 'get_wallet Line 31 : ' . $userId);
        if (!$user) {
            return $this->response->setJSON([
                'status' => 0,
                'message' => 'User not found'
            ]);
        }
    
        return $this->response->setJSON([
            'status' => 1,
            'user' => $user
        ]);
    }*/


    /*public function payment_update_wallet()
    {
        //$data = $this->request->getJSON(true);
        $userId = $this->request->getVar('user_id');
    
        $user = $this->db->table('users')->where('id',$userId)->get()->getRowArray();
        if (!$user) return $this->respond(['status'=>0,'message'=>'User not found']);
    
        $newBalance = $user['wallet_balance'] + $this->request->getVar('credits');
    
        $this->db->table('users')->where('id',$userId)->update([
            'wallet_balance' => $newBalance
        ]);
    
        return $this->respond([
            'status'=>1,
            'wallet_balance'=>$newBalance
        ]);
    }*/

}
