<?php
/**
 * ASISMA CRM - Empresas Controller
 */
class EmpresasController extends Controller {

    public function index() {
        $db = Database::getInstance();
        $where = "1=1";
        $params = array();

        if (!SessionHelper::isAdmin()) {
            $franquiciadoId = SessionHelper::getFranquiciadoId();
            $where = "e.id IN (SELECT DISTINCT lead.empresa_id FROM leads lead WHERE lead.franquiciado_id = :fid AND lead.empresa_id IS NOT NULL)";
            $params['fid'] = $franquiciadoId;
        }

        $sql = "SELECT e.*, r.nombre as region_nombre
                FROM empresas e
                LEFT JOIN regiones r ON e.region_id = r.id
                WHERE {$where}
                ORDER BY e.razon_social ASC";

        $empresas = $db->fetchAll($sql, $params);
        $regiones = $db->fetchAll("SELECT * FROM regiones WHERE activa = 1 ORDER BY nombre ASC");

        $this->render('empresas/index', array(
            'title'    => 'Directorio de Empresas Clientes',
            'empresas' => $empresas,
            'regiones' => $regiones
        ));
    }

    /**
     * Crear empresa (AJAX POST)
     */
    public function crear() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(array('success' => false, 'message' => 'Método no soportado.'), 405);
        }

        $razonSocial = trim($this->input('razon_social', ''));
        $rut         = normalizar_rut($this->input('rut', ''));
        $giro        = trim($this->input('giro', ''));
        $regionId    = (int)$this->input('region_id');
        $direccion   = trim($this->input('direccion', ''));
        $telefono    = trim($this->input('telefono', ''));
        $email       = trim($this->input('email', ''));
        $web         = trim($this->input('web', ''));

        if (empty($razonSocial)) {
            $this->json(array('success' => false, 'message' => 'La razón social es obligatoria.'));
        }

        $db = Database::getInstance();

        if (!empty($rut)) {
            $existe = $db->fetchOne("SELECT id FROM empresas WHERE rut = :rut", array('rut' => $rut));
            if ($existe) {
                $this->json(array('success' => false, 'message' => 'Ya existe una empresa con ese RUT.'));
            }
        }

        $datos = array(
            'razon_social' => $razonSocial,
            'rut'          => $rut ? $rut : null,
            'giro'         => $giro ? $giro : null,
            'region_id'    => $regionId > 0 ? $regionId : null,
            'direccion'    => $direccion ? $direccion : null,
            'telefono'     => $telefono ? $telefono : null,
            'email'        => $email ? $email : null,
            'sitio_web'    => $web ? $web : null,
            'activa'       => 1
        );

        $id = $db->insert('empresas', $datos);
        AuditHelper::log('create_empresa', 'empresas', $id, null, array('razon_social' => $razonSocial));
        $this->json(array('success' => true, 'message' => 'Empresa creada correctamente.', 'id' => $id));
    }

    /**
     * Editar empresa (AJAX POST)
     */
    public function editar() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(array('success' => false, 'message' => 'Método no soportado.'), 405);
        }

        $id          = (int)$this->input('id');
        $razonSocial = trim($this->input('razon_social', ''));
        $rut         = normalizar_rut($this->input('rut', ''));
        $giro        = trim($this->input('giro', ''));
        $regionId    = (int)$this->input('region_id');
        $direccion   = trim($this->input('direccion', ''));
        $telefono    = trim($this->input('telefono', ''));
        $email       = trim($this->input('email', ''));
        $web         = trim($this->input('web', ''));

        if ($id <= 0 || empty($razonSocial)) {
            $this->json(array('success' => false, 'message' => 'ID y razón social son obligatorios.'));
        }

        $db = Database::getInstance();
        $empresa = $db->fetchOne("SELECT id FROM empresas WHERE id = :id", array('id' => $id));
        if (!$empresa) {
            $this->json(array('success' => false, 'message' => 'Empresa no encontrada.'));
        }

        if (!empty($rut)) {
            $existe = $db->fetchOne("SELECT id FROM empresas WHERE rut = :rut AND id != :id", array('rut' => $rut, 'id' => $id));
            if ($existe) {
                $this->json(array('success' => false, 'message' => 'El RUT ya está en uso por otra empresa.'));
            }
        }

        $datos = array(
            'razon_social' => $razonSocial,
            'rut'          => $rut ? $rut : null,
            'giro'         => $giro ? $giro : null,
            'region_id'    => $regionId > 0 ? $regionId : null,
            'direccion'    => $direccion ? $direccion : null,
            'telefono'     => $telefono ? $telefono : null,
            'email'        => $email ? $email : null,
            'sitio_web'    => $web ? $web : null
        );

        $db->update('empresas', $datos, "id = :id", array('id' => $id));
        AuditHelper::log('edit_empresa', 'empresas', $id, null, array('razon_social' => $razonSocial));
        $this->json(array('success' => true, 'message' => 'Empresa actualizada correctamente.'));
    }

    /**
     * Toggle activo/inactivo (AJAX POST)
     */
    public function toggleActivo() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(array('success' => false, 'message' => 'Método no soportado.'), 405);
        }

        $id = (int)$this->input('id');
        if ($id <= 0) {
            $this->json(array('success' => false, 'message' => 'ID inválido.'));
        }

        $db      = Database::getInstance();
        $empresa = $db->fetchOne("SELECT id, activa FROM empresas WHERE id = :id", array('id' => $id));
        if (!$empresa) {
            $this->json(array('success' => false, 'message' => 'Empresa no encontrada.'));
        }

        $nuevo = $empresa['activa'] ? 0 : 1;
        $db->update('empresas', array('activa' => $nuevo), "id = :id", array('id' => $id));
        AuditHelper::log('toggle_empresa', 'empresas', $id, array('activa' => $empresa['activa']), array('activa' => $nuevo));
        $this->json(array('success' => true, 'activa' => $nuevo, 'message' => $nuevo ? 'Empresa activada.' : 'Empresa desactivada.'));
    }

    /**
     * Obtener datos para edición (AJAX GET)
     */
    public function getData() {
        $id = (int)$this->input('id');
        if ($id <= 0) {
            $this->json(array('success' => false, 'message' => 'ID inválido.'));
        }

        $db   = Database::getInstance();
        $data = $db->fetchOne("SELECT * FROM empresas WHERE id = :id", array('id' => $id));
        if (!$data) {
            $this->json(array('success' => false, 'message' => 'No encontrada.'));
        }

        $this->json(array('success' => true, 'data' => $data));
    }
}
