<?php

namespace Blocks\Models;

use CodeIgniter\Model;
use User\Models\Transactions as ModelsTransactions;

class QueueModel extends Model
{
    protected $table = 'queue';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useSoftDeletes = false;

    protected $allowedFields = ['task_type', 'task_data', 'status', 'created_at', 'updated_at'];
    public function __construct()
    {
        parent::__construct();
        $this->transaction_model = new ModelsTransactions();
        
    }
     public function addTask($taskType, $taskData)
    {
        $data = [
            'task_type' => $taskType,
            'task_data' => $taskData,
            'status'    => 'pending',
            'created_at' => now()
        ];

        $this->insert($data);

        return $this->affectedRows() > 0;
    }

    private function module_task($uid,$method, $type, $transaction_id, $ids)
    {
        $tmp =  $this->transaction_model->get_info_by_temp_ids($ids);
       
        if (empty($tmp)) {
            return false;
        }
        $temp_amount = amount_format($tmp['all_info']['total_amount']);
        $transaction_id = post('transaction_id');

        $message1 = '';
        $message2 = '';
        $message3 = '';

        $address = '';
       
        switch ($method) {
            case 'bkash':
                $address = 'bkash';
                $transactionid = 'TrxID ' . $transaction_id;

                if ($type == 'personal') {
                    $message1 = "You have received Tk " . $temp_amount;
                } elseif ($type == 'agent') {
                    $message1 = "Cash Out Tk " . $temp_amount;
                } elseif ($type == 'payment_number') {
                    $message1 = "You have received payment Tk " . $temp_amount;
                }

                break;

            case 'nagad':
                $address = 'nagad';
                $transactionid = 'TxnID: ' . $transaction_id;
                $temp_amount = str_replace(",", "", $temp_amount);
                if ($type == 'personal') {
                $message1 = "Money Received. Amount: Tk ".$temp_amount;
                 
                } elseif ($type == 'agent') {
                    $message1 = "Cash Out Received. Amount: Tk " . $temp_amount;     }
                break;
            case 'surecash':
		    	$address ='16495';
		        $transactionid = 'TxnID: ' . $transaction_id;
		        $temp_amount = str_replace(",","",$temp_amount);

		        if ($type=='personal') {
		        	$message1 = "Amount: Tk ". $temp_amount;
		        }elseif ($type=='agent') {
		        	$message1 = "Amount: Tk ". $temp_amount;
		        }
		        break;

            case 'rocket':
                $address = '16216';
                $transactionid = 'TxnID:' . $transaction_id;
                if ($type == 'personal') {
                    $message1 = "Your account has been successfully credited by Tk. " . $temp_amount;
                    $message2 = "Tk" . $temp_amount . " received";
                } elseif ($type == 'agent') {
                    $message1 = "Amount: Tk " . $temp_amount;
                }
                break;
            case 'upay':
                $address = 'upay';
                $transactionid = 'TrxID ' . $transaction_id;
                if ($type == 'personal') {
                    $message1 = "Your account has been successfully credited by Tk. " . $temp_amount;
                    $message2 = "Tk. " . $temp_amount . " has been received";
                } elseif ($type == 'agent') {
                    $message1 = "Amount: Tk " . $temp_amount;
                }
                break;
            case 'cellfin':
		    	$address ='Islami.Bank';
		        $transactionid = 'TrxId: ' . $transaction_id;
		        $temp_amount = str_replace(",","",$temp_amount);
		        if ($type=='personal') {
		        	$message1 = 'Received ' . $temp_amount;
		        }elseif ($type=='agent') {
		        	$message1 = "Received ". $temp_amount;
		        }
		        break;
                
            case 'tap':
                $address = 'tap';
                $transactionid = 'TrxID ' . $transaction_id;
                if ($type == 'personal') {
                    $message1 = "You have received Tk " . $temp_amount . " via Tap.";
                } elseif ($type == 'agent') {
                    $message1 = "Cash out of Tk " . $temp_amount . " via Tap.";
                }
                break;

            case 'ipay':
                $address = '09638900800';
                $transactionid = 'TrxID ' . $transaction_id;
                if ($type == 'personal') {
                    $message1 = "You have received Tk " . $temp_amount . " via Ipay.";
                } elseif ($type == 'agent') {
                    $message1 = "Cash out of Tk " . $temp_amount . " via Ipay.";
                }
                break;

            case 'ok_wallet':
                $address = '01401195496';
                $transactionid = 'TrxID ' . $transaction_id;
                if ($type == 'personal') {
                    $message1 = "You have received Tk " . $temp_amount . " via OK Wallet.";
                } elseif ($type == 'agent') {
                    $message1 = "Cash out of Tk " . $temp_amount . " via OK Wallet.";
                }
                break;

            case 'mcash':
                $address = 'mCash';
                $transactionid = 'TrxID ' . $transaction_id;
                if ($type == 'personal') {
                    $message1 = "You have received Tk " . $temp_amount . " via mCash.";
                } elseif ($type == 'agent') {
                    $message1 = "Cash out of Tk " . $temp_amount . " via mCash.";
                }
                break;

            case 'Easypaisa':
                $address = '3737';
                $transactionid = 'TrxID ' . $transaction_id;

                if ($type == 'personal') {
                    $message1 = "You have received Rs " . $temp_amount;
                } elseif ($type == 'agent') {
                    $message1 = "Cash Out Tk " . $temp_amount;
                }
                break;

                        default:
                return ["status"  => "error", "title" => "Payment Failed", "message" => 'Illegal Operation!'];
                break;
        }
        

        $builder = $this->db->table('module_data');
        $builder->select('*');

        if (!empty($message2)) {
            $builder->groupStart();
            $builder->like('message', $message1);
            $builder->orLike('message', $message2);
            if (!empty($message3)) {
                $builder->orLike('message', $message3);
            }
            $builder->groupEnd();
        } else {
            $builder->like('message', $message1);
        }

        $builder->like('message', $transactionid);
        $builder->where('status', '0');
        $builder->where('address', $address);
        $builder->where('uid', $uid);

        $query = $builder->get();
        $result = $query->getRow();

        if(!empty($result)){
            $object = array(
                'tmp_id' => $ids,
                'status' => 1,
            );
    
            $this->db->table('module_data')->where('id', $result->id)->update($object);
            return true;
        }
        return false;       

    }

    private function processPendingPayment()
    { 
     
        $pendindtrx = $this->fetch('*','transactions',['status'=> 1,'created_at >'=> date('Y-m-d H:i:s', strtotime("-1 days"))]);
        
        if(!empty($pendindtrx)){
            foreach($pendindtrx as $trx){
                if(!empty($trx->method_transaction_id)){                    
                    if($this->module_task($trx->uid,$trx->type,$trx->method_active,$trx->method_transaction_id,$trx->ids)){
                        $tmp = $this->transaction_model->get_info_by_temp_ids($trx->ids);
                        if (!empty($tmp['all_info']['webhook_url'])) {
                            $post_data = [
                                'paymentMethod'  => $trx->type,
                                'transactionId'  => $tmp['all_info']['transaction_id'],
                                'paymentAmount'  => $tmp['all_info']['amount'],
                                'paymentFee'     => $tmp['all_info']['fees_amount'],
                                'status'         => 2
                            ];
                            $this->db->table('temp_transactions')->update(['status' => 2], ['ids' => $trx->ids]);
                            $this->db->table('transactions')->update(['status' => 2], ['ids' => $trx->ids]);

                            $res = simple_post($tmp['all_info']['webhook_url'], $post_data);
                            $this->setLogs('Response from Webhook call-' . json_encode($res), 'user', $trx->uid);
                            $this->db->table('module_data')->delete(['tmp_id' => $trx->ids]);
                        }
                        $this->setLogs('Transaction status updated - ' . $trx->ids, 'user',$trx->uid);
                    }
                    
                }
                
            }
        }
        return;

    }

    public function processPendingTasks()
    {
      $this->processPendingPayment();
      $pendingTasks = $this->getPendingTasks();

        if (!empty($pendingTasks)) {
            foreach ($pendingTasks as $pendingTask) {
                $taskId = $pendingTask['id'];

                try {
                    $taskType = $pendingTask['task_type'];
                    $taskData = json_decode($pendingTask['task_data'], true);

                    if ($taskType === 'send_email') {
                        $to = $taskData['to'];
                        $subject = $taskData['subject'];
                        $message = $taskData['message'];

                        $this->sendMail($subject, $message, $to);
                        $this->markTaskAsCompleted($taskId);
                    } else {
                        $this->markTaskAsCompleted($taskId);
                    }
                } catch (\Exception $e) {
                    $this->markTaskAsFailed($taskId);
                    log_message('error', 'Error processing task: ' . $e->getMessage());
                }
            }
        } else {
            sleep(5);
        }
    }


    public function getPendingTasks()
    {
        if (get_option('is_clear_ticket')) {
            $days = get_option('default_clear_ticket_days');
            $cutoffDate = date('Y-m-d H:i:s', strtotime("-$days days"));

            $this->db->table('tickets')
                ->where('updated_at <', $cutoffDate)
                ->delete();
                
            $this->db->table('module_data')
                ->where('created_at <', $cutoffDate)
                ->delete();
        }

        return $this->where('status', 'pending')->findAll();
    }

    public function markTaskAsCompleted($id)
    {
        $this->update($id, ['status' => 'completed']);
    }

    public function markTaskAsFailed($id)
    {
        $this->update($id, ['status' => 'failed']);
    }
    public function trash()
    {
        return;
    }
}
