<?php 

defined('BASEPATH') or exit('No direct script access allowed');

class CronJob extends CI_Controller{
    public function __construct(){

        parent::__construct();

        date_default_timezone_set('Asia/Kolkata');

    }

    public function check_payment_status() {
        $key_id = 'rzp_live_4iJV9mAuob8y4z';
        $key_secret = 'Eb1byki59nUdw4sXEH4MeGTA';
    
        // Fetch all pending payments
        $pendingPayments = $this->db->get_where('store_transaction_history', ['payment_status' => 'pending'])->result_array();
    
        foreach ($pendingPayments as $payment) {
            $transaction_id = $payment['id']; // Assuming you have a primary key field `id`
            $razorpay_order_id = $payment['razorpay_order_id'];
    
            // Skip if razorpay_order_id is missing
            if (empty($razorpay_order_id)) {
                log_message('error', "Missing Razorpay Order ID for transaction ID: $transaction_id");
    
                // Optional: Mark as failed or flag for review
                $this->db->where('id', $transaction_id)->update('store_transaction_history', [
                    'payment_status' => 'failed',
                    'updated_at' => date('Y-m-d H:i:s'),
                    'notes' => 'Missing Razorpay Order ID'
                ]);
    
                continue;
            }
    
            // Call Razorpay API to fetch payment info for this order
            $url = "https://api.razorpay.com/v1/orders/$razorpay_order_id/payments";
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERPWD, $key_id . ':' . $key_secret);
    
            $response = curl_exec($ch);
    
            if (curl_errno($ch)) {
                log_message('error', "Curl error while checking Razorpay order [$razorpay_order_id]: " . curl_error($ch));
                curl_close($ch);
                continue;
            }
    
            curl_close($ch);
            $result = json_decode($response, true);
    
            // Process payment details if available
            if (!empty($result['items'])) {
                $paymentData = $result['items'][0]; // Usually only one payment per order
    
                $updateData = [
                    'razorpay_payment_id' => $paymentData['id'],
                    'updated_at' => date('Y-m-d H:i:s')
                ];
    
                if ($paymentData['status'] == 'captured') {
                    $updateData['payment_status'] = 'success';
                } elseif (in_array($paymentData['status'], ['failed', 'refunded'])) {
                    $updateData['payment_status'] = $paymentData['status'];
                } else {
                    // Still pending or authorized, skip update
                    continue;
                }
    
                $this->db->where('razorpay_order_id', $razorpay_order_id)->update('store_transaction_history', $updateData);
            }
        }
    
        echo "Cron executed successfully at " . date('Y-m-d H:i:s');
    }
    
    

}