<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\PaymentModel;
use App\Models\JobModel;

class Payments extends ResourceController
{
    public function initiate()
    {
        $rules = [
            'job_id' => 'required|integer',
            'gateway' => 'required|in_list[razorpay,stripe,payu]',
            'amount' => 'required|decimal'
        ];

        if (!$this->validate($rules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $jobId = $this->request->getVar('job_id');
        $amount = $this->request->getVar('amount');
        $gateway = $this->request->getVar('gateway');

        // Verify Job exists
        $jobModel = new JobModel();
        $job = $jobModel->find($jobId);
        if (!$job) {
            return $this->failNotFound('Job not found');
        }

        // Create Payment Record
        $paymentModel = new PaymentModel();
        $paymentData = [
            'job_id' => $jobId,
            'amount' => $amount,
            'gateway' => $gateway,
            'status' => 'pending'
        ];
        $paymentModel->save($paymentData);
        $paymentId = $paymentModel->getInsertID();

        // Call Gateway API (Mocked)
        $orderId = 'ORDER_' . time() . '_' . $paymentId; // Mock Order ID

        return $this->respond([
            'payment_id' => $paymentId,
            'order_id' => $orderId,
            'amount' => $amount,
            'currency' => 'USD',
            'key' => 'test_key_123' // Should come from .env
        ]);
    }

    public function webhook()
    {
        // Handle Webhook from Gateway
        $data = $this->request->getJSON(true); // or getPost() depending on gateway
        
        // Validate Signature (Mocked)
        // Update Payment Status
        
        log_message('info', 'Payment Webhook Received: ' . json_encode($data));
        
        return $this->respond(['status' => 'ok']);
    }
}
