<?php

namespace App\Controllers\Payments;

use App\Controllers\BaseController;
use App\Models\Payments\ContractPaymentModel;
use App\Models\Payments\PaymentAbonoModel;
use CodeIgniter\HTTP\Response;
use CodeIgniter\API\ResponseTrait;


$allowedOrigins = [
    // 'https://catchef.bravecatstudios.com',  // Producción
    'http://localhost:4200', // Desarrollo en local windows
    'http://localhost:8000', // Desarrollo en local Mac
];

if (isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins)) {
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}

header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

class PaymentsController extends BaseController
{
    protected $paymentModel;
    protected $abonoModel;

    public function __construct(){
        $this->paymentModel = new ContractPaymentModel();
        $this->abonoModel = new PaymentAbonoModel();
    }

    public function options()
{
    return $this->response
        ->setHeader('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN'] ?? '*')
        ->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE')
        ->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        ->setHeader('Access-Control-Allow-Credentials', 'true')
        ->setStatusCode(200);
    }

    public function GetAllPayments($contractId)
{
    // Verifica si el ID del contrato es numérico cambio de rafa
    if(!is_numeric($contractId)) {
        return $this->response->setStatusCode(400)->setJSON(['status' => 'error', 'message' => 'ID de contrato inválido']);
    }
    // Verifica si el contrato existe
    $payments = $this->paymentModel
        ->where('FK_Contract', $contractId)
        ->findAll();

    $baseURL = base_url(); 

    foreach ($payments as &$payment) {
        $abonos = $this->abonoModel
            ->where('FK_Payment', $payment['PK_Payment'])
            ->orderBy('AbonoDate', 'ASC')
            ->findAll();

        // Agrega la URL completa a cada abono que tenga ImgPath
        foreach ($abonos as &$abono) {
            if (!empty($abono['ImgPath'])) {
                if (strpos($abono['ImgPath'], 'http') !== 0 && strpos($abono['ImgPath'], '/') !== 0) {
                    $abono['ImgPath'] = $baseURL . '/' . $abono['ImgPath'];
                } elseif (strpos($abono['ImgPath'], '/') === 0) {
                    $abono['ImgPath'] = $baseURL . $abono['ImgPath'];
                }
            }
        }

        $payment['Abonos'] = $abonos;
    }

    return $this->response->setJSON($payments);
}



    public function registerAbono()
    {
        helper(['form']);

        $paymentID = $this->request->getPost('FK_Payment');
        $abono     = (float)$this->request->getPost('Amount');
        $method    = $this->request->getPost('Method');
        $notes     = $this->request->getPost('Notes');

        $paymentModel = new \App\Models\Payments\ContractPaymentModel();
        $abonoModel   = new \App\Models\Payments\PaymentAbonoModel();

        $payment = $paymentModel->find($paymentID);
        log_message('debug', 'Pago obtenido: ' . print_r($payment, true));

        if (!$payment) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Pago no encontrado']);
        }

        $paymentArr = (array)$payment;
        if (!array_key_exists('Balance', $paymentArr)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Balance no encontrado en el pago']);
        }

        $currentBalance = (float)$paymentArr['Balance'];
        $newBalance = max($currentBalance - $abono, 0);

        $paymentModel->update($paymentID, [
            'Balance'     => $newBalance,
            'IsPaid'      => $newBalance == 0 ? 1 : 0,
            'PaymentDate' => date('Y-m-d')
        ]);

        // Procesar imagen
        $imgPath = null;
        $image = $this->request->getFile('Image'); // nombre del input file debe ser 'Image'

        if ($image && $image->isValid() && !$image->hasMoved()) {
            $newName = $image->getRandomName(); // genera un nombre aleatorio
            $uploadPath = FCPATH . 'uploads/payments/';
            if (!is_dir($uploadPath)) {
                mkdir($uploadPath, 0755, true);
            }

            $image->move($uploadPath, $newName);
            $imgPath = 'uploads/payments/' . $newName;
        }

        $abonoModel->insert([
            'FK_Payment' => $paymentID,
            'Amount'     => $abono,
            'AbonoDate'  => date('Y-m-d'),
            'Method'     => $method,
            'Notes'      => $notes,
            'ImgPath'    => $imgPath // puede ser null si no se subió imagen
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Abono registrado correctamente'
        ]);
    }


}