<?php

namespace App\Services\Geral\Tabelas;

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;

class PlanoIva
{
    public function install()
    {
        try {
            if (!Schema::hasTable('planoivas')) {
                Schema::create('planoivas', function (Blueprint $table) {
                    $table->id();
                    $table->string('id_empresa')->nullable(); 
                    $table->string('id_modulo')->nullable(); 
                    $table->string('codigo_iva')->nullable(); 
                    $table->string('descricao')->nullable();
                    $table->string('taxa')->nullable(); 
                    $table->string('tipo')->nullable(); 
                    $table->string('activo')->nullable();
                    $table->string('exercicios')->nullable(); 

                    $table->timestamps();
                });

                $this->seed(); // <-- Popula automaticamente após criar

                return true;
            }
        } catch (\Throwable $th) {
            return false;
        }
    } 

    public function seed()
    {
        try {

            $dados = [

                // IVA NORMAL (ANGOLA)
                ['1', 'FIN', 'IVA14', 'IVA 14% - Taxa Normal', '14', 'Normal', 'Sim', date('Y')],

                // IVA REDUZIDO (caso aplicável)
                ['1', 'FIN', 'IVA07', 'IVA 7% - Taxa Reduzida', '7', 'Reduzido', 'Sim', date('Y')],

                // IVA ZERO
                ['1', 'FIN', 'IVA0', 'IVA 0% - Taxa Zero', '0', 'Zero', 'Sim', date('Y')],

                // ISENTO DE IVA
                ['1', 'FIN', 'ISENTO', 'Isento de IVA', '0', 'Isento', 'Sim', date('Y')],

                // NÃO SUJEITO A IVA
                ['1', 'FIN', 'NS', 'Não Sujeito a IVA', '0', 'Nao Sujeito', 'Sim', date('Y')],
            ];

            foreach ($dados as $item) {
                DB::table('planoivas')->insert([
                    'id_empresa' => $item[0],
                    'id_modulo' => $item[1],
                    'codigo_iva' => $item[2],
                    'descricao' => $item[3],
                    'taxa' => $item[4],
                    'tipo' => $item[5],
                    'activo' => $item[6],
                    'exercicios' => $item[7],
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            return true;

        } catch (\Throwable $th) {
            return false;
        }
    }

    public function revert()
    {
        try {
            Schema::dropIfExists('planoivas');
            return true;
        } catch (\Throwable $th) {
            return false;
        }
    }
}