<?php
require_once("../config/conexion.php");
require_once("../modelos/Permiso.php");

$permiso = new Permiso();

switch ($_GET["op"]) {
    case "listar":
        $datos = $permiso->get_permisos();
        $data = [];
        foreach ($datos as $row) {
            $sub_array = [];
            $sub_array[] = $row["Ctab_per"];
            $sub_array[] = $row["Catrib_per"];
            $sub_array[] = $row["Ctipo_per"];
            $sub_array[] = $row["rol_descripcion"];
            $sub_array[] = '<button type="button" onClick="mostrar(' . $row["Npermi_ID"] . ');" class="btn btn-info btn-sm"><i class="fa fa-pencil"></i></button>';
            $sub_array[] = '<button type="button" onClick="eliminar(' . $row["Npermi_ID"] . ');" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button>';
            $data[] = $sub_array;
        }
        $results = [
            "sEcho" => 1,
            "iTotalRecords" => count($data),
            "iTotalDisplayRecords" => count($data),
            "aaData" => $data
        ];
        echo json_encode($results);
        break;

    case "guardaryeditar":
        if (empty($_POST["Npermi_ID"])) {
            $permiso->insert_permiso($_POST["Ctab_per"], $_POST["Catrib_per"], $_POST["Ctipo_per"], $_POST["N_rolID"]);
        } else {
            $permiso->update_permiso($_POST["Npermi_ID"], $_POST["Ctab_per"], $_POST["Catrib_per"], $_POST["Ctipo_per"], $_POST["N_rolID"]);
        }
        break;

    case "mostrar":
        $datos = $permiso->get_permiso_by_id($_POST["Npermi_ID"]);
        echo json_encode($datos);
        break;

    case "eliminar":
        $permiso->delete_permiso($_POST["Npermi_ID"]);
        break;

    case "obtener_atributos":
        $datos = $permiso->get_atributos($_POST["tabla"]);
        $html = "";
        foreach ($datos as $row) {
            $html .= "<option value='" . $row["Field"] . "'>" . $row["Field"] . "</option>";
        }
        echo $html;
        break;

    case "obtener_tablas":
        $datos = $permiso->get_tablas();
        $html = "";
        foreach ($datos as $row) {
            $html .= "<option value='" . $row["Tables_in_sistemaqr"] . "'>" . $row["Tables_in_sistemaqr"] . "</option>";
        }
        echo $html;
        break;

    case "obtener_roles":
        $datos = $permiso->get_roles();
        $html = "";
        foreach ($datos as $row) {
            $html .= "<option value='" . $row["N_rolID"] . "'>" . $row["Sdescrip"] . "</option>";
        }
        echo $html;
        break;
}
