<?php

namespace App\Controllers\Contracts;

use App\Controllers\BaseController;
use App\Models\Contracts\ContractModel;
use App\Models\Contracts\ContractClauseModel;
use App\Models\UserModel;
use CodeIgniter\HTTP\Response;
use CodeIgniter\API\ResponseTrait;


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

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 ContractController extends BaseController
{
    protected $contractModel;
    protected $userModel;

    public function __construct(){
        $this->contractModel = new ContractModel();
        $this->userModel = new UserModel();
    }

    public function GetAllContracts(){
        $contracts = $this->contractModel->findAll();
        return $this->response->setJSON($contracts);
    }

    public function GetContractByFk($fk){
        $contract = $this->contractModel->find($fk);
        if($contract){
            return $this->response->setJSON($contract);
        }else{
            return $this->response->setJSON(['status' => 'error', 'message' => 'Contract not found']);
        }
    }

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

        $email = $this->request->getPost('Email');
        $renter = $this->request->getPost('Renter');

        // Modelo usuarios
        $userModel = $this->userModel; // Asumo que ya tienes cargado $this->userModel
        $contractInfoModel = new \App\Models\Contracts\ContractInfoModel();

        // 1. Buscar usuario existente
        $existingUser = $userModel->where('Email', $email)->first();

        if ($existingUser) {
            $insertedUserID = $existingUser['PK_User']; // Ajusta si tu PK tiene otro nombre
        } else {
            // 2. Crear nuevo usuario
            $passwordPlain = bin2hex(random_bytes(5)); // 10 caracteres
            $passwordHash = password_hash($passwordPlain, PASSWORD_DEFAULT);

            $userData = [
                'Name'     => $renter,
                'Email'    => $email,
                'Rol'      => 2,
                'Password' => $passwordHash
            ];

            $insertedUserID = $userModel->insert($userData);

            if (!$insertedUserID) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'No se pudo insertar el usuario'
                ]);
            }

            // Enviar correo con contraseña
            $emailSent = $this->sendPasswordEmail($email, $passwordPlain);

            if (!$emailSent) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'No se pudo enviar el correo con la contraseña'
                ]);
            }
        }

        // 3. Validar si existe contrato activo con ese email
        $activeContract = $contractInfoModel
            ->where('Email', $email)
            ->whereIn('Status', ['Activo', 'Próximo a vencer'])
            ->first();
            
        if ($activeContract) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Ya existe un contrato activo registrado con este correo electrónico.'
            ]);
        }

        // 4. Insertar contrato
        $contractData = [
            'FK_Location'     => $this->request->getPost('FK_Location'),
            'StartDate'       => $this->request->getPost('StartDate'),
            'Rent'            => $this->request->getPost('Rent'),
            'ContractLenght'  => $this->request->getPost('QuantityPeriods'),
            'Warranty'        => filter_var($this->request->getPost('Warranty'), FILTER_VALIDATE_BOOLEAN) ? 1 : 0,
            'Furnished'       => filter_var($this->request->getPost('Furnished'), FILTER_VALIDATE_BOOLEAN) ? 1 : 0,
            'FK_User'         => $insertedUserID
        ];

        $contractInserted = $this->contractModel->insert($contractData);

        if (!$contractInserted) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'No se pudo insertar el contrato'
            ]);
        }

        $contractID = $this->contractModel->getInsertID();
        $dateStr = date('Ymd');
        $contractNumber = 'CN-' . $dateStr . '-' . str_pad($contractID, 5, '0', STR_PAD_LEFT);
        $this->contractModel->update($contractID, ['ContractNumber' => $contractNumber]);

        $this->generateContractPayments(
            $contractID,
            $contractData['StartDate'],
            (int)$contractData['ContractLenght'],
            (float)$contractData['Rent']
        );

        // 5. Insertar cláusulas (borrar las antiguas si existen)
        $clausesJson = $this->request->getPost('Clauses');
        $clauses = json_decode($clausesJson, true);

        if ($clauses && is_array($clauses)) {
            $clauseModel = new \App\Models\Contracts\ContractClauseModel();

            // Eliminar cláusulas previas
            $clauseModel->where('FK_Contract', $contractID)->delete();

            $mappedClauses = [
                ['Title' => 'Uso de la propiedad', 'Description' => $clauses['useProperty'] ?? ''],
                ['Title' => 'Pago de servicios', 'Description' => $clauses['services'] ?? ''],
                ['Title' => 'Mantenimiento', 'Description' => $clauses['maintenance'] ?? ''],
                ['Title' => 'Terminación anticipada', 'Description' => $clauses['earlyTermination'] ?? ''],
                ['Title' => 'Multa por retraso en el pago', 'Description' => $clauses['lateFee'] ?? ''],
            ];

            foreach ($mappedClauses as $clause) {
                $clause['FK_Contract'] = $contractID;
                $clauseModel->insert($clause);
            }
        }

        // 6. Respuesta exitosa
        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Contrato y usuario creados correctamente',
            'contract_id' => $contractID,
            'contract_number' => $contractNumber,
            'user_email' => $email,
            // Si usuario nuevo, enviar contraseña generada (si no, no)
            'generated_password' => isset($passwordPlain) ? $passwordPlain : null
        ]);
    }

    public function concludeContract($pk){
        $contractModel = $this->contractModel;

        $reason = $this->request->getPost('Reason');
        $date = $this->request->getPost('Date');

        $data = [
            'Concluded' => 1,
            'ConclusionDate' => $date,
            'ConclusionReason' => $reason
        ];

        
        if ($contractModel->update($pk, $data)) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Contrato terminado'
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Contrato no terminado'
            ]);        
        }
    }

    private function generateContractPayments($contractID, $startDate, $length, $rent)
    {
        $paymentModel = new \App\Models\Payments\ContractPaymentModel();

        $start = new \DateTime($startDate);

        for ($i = 0; $i < $length; $i++) {
            $dueDate = clone $start;
            $dueDate->modify("+$i months");

            $paymentModel->insert([
                'FK_Contract'   => $contractID,
                'PaymentNumber' => $i + 1,
                'DueDate'       => $dueDate->format('Y-m-d'),
                'Amount'        => $rent,
                'Balance'       => $rent,
                'IsPaid'        => 0
            ]);
        }
    }

    private function sendPasswordEmail($toEmail, $passwordPlain)
    {
        $html = '
        <div style="font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 30px;">
            <div style="max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
            
            <!-- Encabezado con fondo oscuro y logo -->
            <div style="background-color: #1c1c1c; padding: 20px; text-align: center;">
                <img src="https://us-tuna-sounds-images.voicemod.net/c56bcf5a-0e1c-446a-8d65-67402d690183-1711135828431.jpg" alt="MiSistema" style="max-width: 140px;">
            </div>

            <!-- Contenido del correo -->
            <div style="padding: 30px;">
                <h2 style="color: #000000; font-size: 22px; margin-top: 0;">Tu cuenta ha sido creada</h2>
                <p style="color: #333333; font-size: 16px;">Se ha generado una nueva contraseña para acceder al sistema. Aquí tienes los detalles:</p>

                <ul style="list-style: none; padding-left: 0; font-size: 15px; color: #444;">
                <li><strong>Correo:</strong> ' . $toEmail . '</li>
                <li><strong>Contraseña:</strong> <span style="font-weight: bold; color: #000;">' . $passwordPlain . '</span></li>
                <li><strong>Fecha de generación:</strong> ' . date('d/m/Y h:i A') . '</li>
                </ul>

                <p style="font-size: 15px; color: #333333;">Te recomendamos cambiar esta contraseña lo antes posible para mantener tu cuenta segura.</p>

                <!-- Botón -->
                <div style="margin: 30px 0; text-align: center;">
                <a href="https://tusitio.com/login" style="background-color: #3f00ff; color: #ffffff; padding: 12px 25px; border-radius: 25px; text-decoration: none; font-weight: bold; font-size: 15px;">
                    Iniciar sesión
                </a>
                </div>

                <p style="font-size: 13px; color: #777; text-align: center;">
                Si tienes dudas, puedes contactarnos o revisar la <a href="https://tusitio.com/ayuda" style="color: #3f00ff; text-decoration: none;">sección de ayuda</a>.
                </p>
            </div>
            </div>
        </div>
        ';


        $apiKey = 're_LvSv11xL_DbHNFKvnjMVtu37GbKq1ciJu'; // Pon tu API key aquí
        $url = 'https://api.resend.com/emails';

        $emailData = [
            "from" => "contacto@bravecatstudios.com",
            "to" => "$toEmail",
            "subject" => "Tu nueva contraseña generada",
            "html" => $html
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($emailData));

        $response = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($curlError) {
            log_message('error', 'cURL error al enviar correo: ' . $curlError);
            return false;
        }

        if ($httpcode == 200 || $httpcode == 202) {
            return true;
        } else {
            log_message('error', "Error al enviar correo, HTTP code: $httpcode, Response: $response");
            return false;
        }
    }

    public function getContractClauses($contractId)
    {
        $clauseModel = new \App\Models\Contracts\ContractClauseModel();

        $clauses = $clauseModel
            ->where('FK_Contract', $contractId)
            ->findAll();

        if (!$clauses) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'No se encontraron cláusulas para este contrato.'
            ]);
        }

        return $this->response->setJSON([$clauses]);
    }

}