<?php
require "global.ajax.php";

switch ($_GET["op"]) {

    case 'ajaxSaveUpdate':

        // POST VARIABLES
        $table_id = isset($_POST["table_id"]) ? funCheckInput($_POST["table_id"]) : "";
        $table_description = isset($_POST["table_description"]) ? funCheckInput($_POST["table_description"]) : "";
        $table_created_by = $session_user_id;

        if (empty($table_ent_id)) $table_ent_id = $session_user_ent_id;
        if (empty($table_pos_id)) $table_pos_id = $session_user_pos_id;

        try {

            $pdo->beginTransaction();

            $isNew = empty(trim($table_id));

            if ($isNew) {

                $stmt = $pdo->prepare("INSERT INTO tb_tables (
                    table_ent_id,
                    table_pos_id,
                    table_description,
                    table_created_by
                    ) VALUES (
                    :ent_id,
                    :pos_id,
                    :description,
                    :created_by
                )");

                $stmt->execute([
                    ':ent_id'     => $table_ent_id,
                    ':pos_id'     => $table_pos_id,
                    ':description' => $table_description,
                    ':created_by' => $table_created_by
                ]);

                $response = array("message" => $translate['saved_successfully'], "status" => "success");
            } else {

                $stmt = $pdo->prepare("UPDATE tb_tables SET
                    table_description = :description
                    WHERE table_id = :table_id
                ");

                $stmt->execute([
                    ':description' => $table_description,
                    ':table_id'    => $table_id
                ]);

                $response = array("message" => $translate['updated_successfully'], "status" => "success");
            }

            $pdo->commit();
        } catch (\RuntimeException | \InvalidArgumentException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
        } catch (\PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
        }

        echo json_encode($response);

        break;


    case 'ajaxShowTableList':

        $sql = "SELECT * FROM tb_tables;";
        $result = executePDOFetchAll($sql, $translate['could_not_display_data']);
        // exit($sql);

        //Vamos a declarar un array
        $data = array();

        /*=============================================
            SEND DATA TO DATATABLE
            =============================================*/
        foreach ($result as $key => $value) {

            $tableStatus = '<div class="form-check form-switch mb-2">
			<input class="form-check-input" type="checkbox" onclick="js_desactivate(' . $value['table_id'] . ')" id="flexSwitchCheckChecked" checked>
			<label class="form-check-label" for="flexSwitchCheckChecked">' . $translate['enabled'] . '</label>
			</div>';

            if ($value['table_access'] == "Disabled") $tableStatus = '<div class="form-check form-switch mb-2">
			<input class="form-check-input" type="checkbox" onclick="js_activate(' . $value['table_id'] . ')" id="flexSwitchCheckDefault">
			<label class="form-check-label" for="flexSwitchCheckDefault">' . $translate['disabled'] . '</label>
			</div>';

            $data[] = array(

                "0" => $value['table_id'],
                "1" => $value['table_description'],
                "2" => '<button type="button" onclick="fnOpenTableForm(\'' . $value['table_ent_id'] . '\',\'' . $value['table_pos_id'] . '\',\'' . $value['table_id'] . '\',\'' . $value['table_description'] . '\');" class="btn btn-success fs-20px"><i class="fas fa-pencil"></i> Editar</button>',
                "3" => $tableStatus
            );
        }
        $results = array(
            "sEcho" => 1, //Información para el datatables
            "iTotalRecords" => count($data), //enviamos el total registros al datatable
            "iTotalDisplayRecords" => count($data), //enviamos el total registros a visualizar
            "aaData" => $data
        );
        echo json_encode($results);

        break;


    case 'ajax_selectTable':

        $table_id = isset($_GET["table_id"]) ? funCheckInput($_GET["table_id"]) : "";

        $customWhere = "";
        if (!empty($table_id)) $customWhere = "WHERE table_id = {$table_id}";

        $sql = "SELECT
        table_id
        ,table_description
        FROM tb_tables
        $customWhere
        GROUP BY table_id ORDER BY table_description ASC;";

        // exit($sql);

        $rows = executePDOFetchAllAPI($sql);
        echo json_encode($rows);

        break;
}
