<?php 

    
class Billing extends Core {

    function getPlans() {
        
        $white_label_id = $this->config['WHITE_LABEL_ID'];
        $sql_plans = "SELECT * FROM plans WHERE white_label_id = :white_label_id ORDER BY id ASC";
        $stmt_plans = parent::$conn->prepare($sql_plans);
        $stmt_plans->execute([':white_label_id' => $white_label_id]);
        $plans = $stmt_plans->fetchAll(PDO::FETCH_ASSOC);

        $sql_options = "SELECT * FROM plan_options WHERE plan_id = :plan_id AND quota_period = 'annual' ORDER BY name";
        $sql_payment_opt = "SELECT * FROM plan_payment_contracts WHERE plan_id = :plan_id";

        foreach($plans as $key => $plan) {            
            $stmt_options = parent::$conn->prepare($sql_options);
            $stmt_options->execute([':plan_id' => $plan['id']]);
            $plans[$key]['options'] = $stmt_options->fetchAll(PDO::FETCH_ASSOC);
        }

        foreach($plans as $key => $plan) {
            $stmt_payments = parent::$conn->prepare($sql_payment_opt);
            $stmt_payments->execute([':plan_id' => $plan['id']]);
            $payments = $stmt_payments->fetchAll(PDO::FETCH_ASSOC);            
            $plans[$key]['payments'] = $this->getPlanPaymentOptions($payments);
        }

        return [
            'type' => 'OK',
            'data' => $plans
        ];                

    }

    private function getPlanPaymentOptions($payments) {

        foreach($payments as $key => $payment) {
            $sql = "SELECT * FROM plan_payment_options WHERE plan_payment_id = :plan_payment_id";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([':plan_payment_id' => $payment['id']]);
            $options = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $payments[$key]['options'] = $options;
        }

        return $payments;

    }

    function cancelFreeSignature() {

        $company_id = $_POST['companyId'];

        $sql = "UPDATE company_signatures SET `status` = 'PENDING' WHERE company_id = ? AND type = 'signature'";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$company_id]);

        return ['type' => 'OK'];

    }

    function saveSignature () {
       
        $email = $_POST['email'];
        $process_count = $_POST['maxProcessCount'] ?? null;
        $newplan = $_POST['newplan'] ?? null;
        $status = 'ACTIVE';
        $white_label_id = $this->config['WHITE_LABEL_ID'];
       
        if(!is_null($process_count)) {
           
            if(!empty($newplan)){
                switch ($newplan) {
                    case '1':
                        $process_count = 1;
                        break;
                    case '2':
                        $process_count = 3;
                        break;
                    case '3':
                        $process_count = 10;
                        break;
                    case '4':
                        $process_count = 25;
                        break;
                    case '5':
                        $process_count = 50;
                        break;    
                }
            }
           
            $sql = "SELECT P.id, start_trial, process_limit, PPC.price, PPC.id AS plan_payment_id, PPO.id as plan_payment_option_id FROM plans AS P
                    LEFT JOIN plan_payment_contracts AS PPC ON PPC.plan_id = P.id
                    LEFT JOIN plan_payment_options AS PPO ON PPO.plan_payment_id = PPC.id
                    WHERE process_limit >= :process_limit AND period = 'monthly' AND P.white_label_id = :white_label_id ORDER BY id ASC LIMIT 1";
            $stmt = parent::$conn->prepare($sql);
            $stmt->bindValue(':process_limit', $process_count, PDO::PARAM_INT);
            $stmt->bindValue(':white_label_id', $white_label_id, PDO::PARAM_INT);
            $stmt->execute();
            $plan = $stmt->fetch(PDO::FETCH_ASSOC);
            $plan_id = $plan['id'];
            $plan_payment_id = $plan['plan_payment_id'];
            $plan_payment_option_id = $plan['plan_payment_option_id'] ?? null;
            $status = $plan['start_trial'] == 1 ? 'TRIAL' : 'ACTIVE';
            $price = $plan['price'];
        } else {
            $plan_id = 1; //Plano Gratis
            $plan_payment_id = 13;
            $price = '0.00';
            $plan_payment_option_id = null;
        }    
 
        $sql = "SELECT id FROM companies WHERE companyemail = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$email]);
        $company = $stmt->fetch(PDO::FETCH_ASSOC);
        $company_id = $company['id'];
 
        $sql = "DELETE FROM company_signatures WHERE company_id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$company_id]);
 
        $signature_id_free = rand(1000000, 9999999);
        //Insere plano Inpulso
        $sql = "INSERT INTO company_signatures (company_id, plan_id, plan_payment_id, plan_payment_option_id, price, status, status_text, type, signature_date, signature_id)
            VALUES(:company_id, :plan_id, :plan_payment_id, :plan_payment_option_id, :price, '{$status}', 'Assinatura grátis', 'signature', NOW(), '{$signature_id_free}_free')";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':company_id' => $company_id,
            ':plan_id' => $plan_id,
            ':plan_payment_id' => $plan_payment_id,
            ':plan_payment_option_id' => $plan_payment_option_id,
            ':price' => $price
        ]);
        $signature_id = parent::$conn->lastInsertId();
 
        //Copia regras para a ampresa
        $sql = "SELECT * FROM plan_options WHERE plan_id = :plan_id AND quota_period = 'monthly'";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':plan_id' => $plan_id]);
        $options = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
        $sql_delete_quote = "DELETE FROM signature_quotes WHERE company_id = ?";
        $stmt_delete_quote = parent::$conn->prepare($sql_delete_quote);
        $stmt_delete_quote->execute([$company_id]);
 
        $sql = "INSERT INTO signature_quotes(signature_id, company_id, plan_id, plan_option_id, `value`)
            VALUES(:signature_id, :company_id, :plan_id, :option_id, :value)";
 
        foreach($options as $option) {
 
            $stmt_option = parent::$conn->prepare($sql);
            $stmt_option->execute([
                ':signature_id' => $signature_id,
                ':company_id' => $company_id,
                ':plan_id' => $plan_id,
                ':option_id' => $option['id'],
                ':value' => $option['quota_value']
            ]);
 
        }
 
        return ['type' => 'OK', 'data' => ['id' => $signature_id]];
    }
    
    function getSignature() {

        $company_id = $_GET['companyId'];

        $sql = "SELECT * FROM company_signatures WHERE company_id = ? AND type = 'signature'";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$company_id]);
        $signature = $stmt->fetch(PDO::FETCH_ASSOC);

        if(!$signature) {
            return [
                'type' => 'OK',
                'signature' => null
            ];
        }

        $sql_plan = "SELECT * FROM plans WHERE id = ?";
        $stmt_plan = parent::$conn->prepare($sql_plan);
        $stmt_plan->execute([$signature['plan_id']]);
        $plan = $stmt_plan->fetch(PDO::FETCH_ASSOC);        

        $sql_payment = "SELECT * FROM plan_payment_contracts WHERE id = ?";
        $stmt_payment = parent::$conn->prepare($sql_payment);
        $stmt_payment->execute([$signature['plan_payment_id']]);
        $payment = $stmt_payment->fetch(PDO::FETCH_ASSOC);

        $sql_payment_opt = "SELECT * FROM plan_payment_options WHERE id = ?";
        $stmt_payment_opt = parent::$conn->prepare($sql_payment_opt);
        $stmt_payment_opt->execute([$signature['plan_payment_option_id']]);
        $payment_opt = $stmt_payment_opt->fetch(PDO::FETCH_ASSOC);

        return [
            'type' => 'OK',
            'signature' => [
                'plan' => $plan,
                'payment' => $payment,
                'payment_opt' => $payment_opt,
                'payment_link' => $signature['payment_link']
                
            ]
        ];

    }

    function printBillet() {

        $url = $_GET['link'];
        $filename = "boleto.html";
        
        $ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

		$content = curl_exec($ch);

		if (curl_errno($ch)) {
			die("Erro ao baixar o arquivo: " . curl_error($ch));
		}

		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
		curl_close($ch);

		if ($httpCode !== 200) {
			die("Arquivo não encontrado ou inacessível.");
		}

		// Envia headers para download
		header("Content-Type: " . ($contentType ?: "application/octet-stream"));
		header("Content-Disposition: attachment; filename=\"$filename\"");
		header("Content-Length: " . strlen($content));
        
        echo $content;

    }
    
}