<?php
class DefaultController extends Controller
{
    public $layout = 'panel';

    public function actionIndex()
    {
        $db = Yii::app()->db;
        $tx = $db->beginTransaction();
        try {
            // Actualizar inspecciones en lotes
            $this->actualizarPorLotes('sidcai_inspeccion_empresa', 'habilitado', true, 'habilitado', false);

            // Actualizar declaraciones CTI en lotes
            $this->actualizarPorLotesDeclaracion();

            // Actualizar créditos fiscales en lotes
            $this->actualizarPorLotes('sidcai_credito_fiscal', 'cred_habilitado', true, 'cred_habilitado', false);

            $tx->commit();
            $this->render('index');
        } catch (Exception $e) {
            $tx->rollback();
            throw $e;
        }
    }

    private function actualizarPorLotes($tabla, $campoCondicion, $valorCondicion, $campoUpdate, $nuevoValor)
    {
        $lote = 10000;
        $db = Yii::app()->db;
        do {
            $sql = "
                WITH filas AS (
                    SELECT ctid FROM $tabla
                    WHERE $campoCondicion = :valorCondicion
                    LIMIT $lote
                )
                UPDATE $tabla t
                SET $campoUpdate = :nuevoValor
                FROM filas f
                WHERE t.ctid = f.ctid
            ";
            $filas = $db->createCommand($sql)
                ->bindValue(':valorCondicion', $valorCondicion)
                ->bindValue(':nuevoValor', $nuevoValor)
                ->execute();
        } while ($filas > 0);
    }

    private function actualizarPorLotesDeclaracion()
    {
        $lote = 10000;
        $db = Yii::app()->db;
        do {
            $sql = "
                WITH filas AS (
                    SELECT ctid FROM sidcai_declaracioncti
                    WHERE decl_tipodeclaracion = 'O'
                      AND esta_codigo_fk = 1006
                    LIMIT $lote
                )
                UPDATE sidcai_declaracioncti t
                SET esta_codigo_fk = 1001
                FROM filas f
                WHERE t.ctid = f.ctid
            ";
            $filas = $db->createCommand($sql)->execute();
        } while ($filas > 0);
    }
}
