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

/**
 * ARUA FRIENDS SACCO API Controller
 * Class 88 - Here to Empower One Another
 * 
 * This controller handles all SACCO operations including:
 * - Member management
 * - Ledger operations
 * - Loan management
 * - Transactions
 * - Dashboard statistics
 */
class Payments extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
        
        // Enable CORS for API requests
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        // Handle preflight requests
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            exit(0);
        }

        // Ensure required tables/columns exist for RBAC + workflow.
        // This keeps deployments resilient when DB migrations lag behind.
      
    }
  
  Public function makePayment(){
    //payment initilialisation


  $json_data = json_decode(@file_get_contents('php://input'), true);
  $customer_email = $json_data['email'] ;
  $customer_phone = $json_data['phone'] ;
  $amount = $json_data['amount'] ;
  $business_name = $json_data['business_name'] ;
  $business_description = $json_data['business_description'] ;
  $logo = $json_data['logo'] ;
  $redirect_url = $json_data['redirect_url'] ;
  $currency = $json_data['currency'] ;
  $invoice_id = $json_data['invoice_id'] ;

  $txn_data = array(
            "txn_id" => $invoice_id,
            "amount" =>$amount,
            "txn_ref"=> $invoice_id,
            "date_created" => date('Y-m-d H:i:s'),
            "status" => 'pending'
        );
        

         $sql = "CREATE TABLE IF NOT EXISTS ovalpay_transactions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                amount DECIMAL(10, 2) NOT NULL,
                txn_ref VARCHAR(255) NOT NULL,
                date_created DATETIME NOT NULL,
                status VARCHAR(255) NOT NULL
            )";
            $this->db->query($sql);
        if($this->db->insert('ovalpay_transactions',$txn_data)){

            // call flutterwave
            
            $customer = array(
            "email" => $customer_email,
            "phone" => $customer_phone
        );
            
            $flutter_data = array(
            'tx_ref' => $invoice_id,
            'amount' => $amount,
            "customer" => $customer,
            "payment_options" => "card",
            "redirect_url" => $redirect_url,
            "customizations" => array(
                "title" => $business_name,
                "description" => $business_description,
                "logo" => $logo
            ),
            'currency' => $currency
        );
				
            $ch = curl_init('https://api.flutterwave.com/v3/payments');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($flutter_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                        'Authorization:Bearer FLWSECK-aa43d1167006f52cf5141b524cbf3d4e-18d69340664vt-X'
                    ));
                    //execute the curl
                    $result = curl_exec($ch);
                    
                     return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'payment_processor'=>json_decode($result),
                    'message' => 'PAYMENT_LINK_SUCCESSFULLY',
                    
                )));
        }
  }

}