<?php
session_start();
if (!isset($_SESSION['id'])) {
    header("Location: logout.php");
}

include "db_connect.php";
?>
<!DOCTYPE html>
<html lang="pt-BR" data-bs-theme="auto">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Controle de estoque">
    <meta name="author" content="Jadiel Sousa, OnTop Sistemas">
    <meta name="generator" content="VSCode">
    <title>WContagem - OnTop Sistemas</title>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/produtos.css" rel="stylesheet">
    <link href="assets/icons/font/bootstrap-icons.css" rel="stylesheet">
    <script src="assets/js/sweetalert2.all.js"></script>
</head>

<body class="bg-success bg-gradient">
    <nav class="navbar navbar-expand-md navbar-light bg-light fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="index.php"><i class="bi bi-house"></i>  WContagem - <?= $_SESSION['nome'] ?></a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <div class="navbar-nav me-auto mb-2 mb-md-0">
                    <a class="nav-item nav-link active" href="produtos.php">Produtos</a>
                    <a class="nav-item nav-link disabled" href="alteracao.php">Alteração</a>
                    <a class="nav-item nav-link " href="historico.php">Histórico</a>
                    <a class="nav-item nav-link " href="logout.php">Sair</a>

                </div>
            </div>
        </div>
    </nav>

    <main class="w-100 form ">
        <div class="container mt-3 mb-3">
            <div class="accordion" id="accordionExample">
                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button class="accordion-button bg-warning text-white fw-bold <?= (isset($_POST['pesquisar'])) ? "collapsed" : "" ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="<?= (isset($_POST['pesquisar'])) ? "false" : "true" ?>" aria-controls="collapseOne">
                            PESQUISA DE PRODUTOS
                        </button>
                    </h2>
                    <div id="collapseOne" class="accordion-collapse collapse <?= (isset($_POST['pesquisar'])) ? "" : "show" ?>" data-bs-parent="#accordionExample">
                        <div class="accordion-body">
                            <form action="produtos.php" method="post">
                                <div class="row">
                                    <div class="my-1 col-12 col-md-2 col-lg-1 col-xl-1 col-xxl-1">
                                        <div class="form-floating">
                                            <input type="text" class="form-control" id="arcodigo" name="arcodigo" maxlength="14" placeholder="." style="text-transform:uppercase">
                                            <label for="arcodigo" class="">Código/Referência/Cod. Barras</label>
                                        </div>
                                    </div>
                                    <div class="my-1 col-12 col-md-5 col-lg-6">
                                        <div class="form-floating">
                                            <input type="text" class="form-control" id="ardesnot" name="ardesnot" placeholder="." style="text-transform:uppercase">
                                            <label for="ardesnot" class="">Descrição</label>
                                        </div>
                                    </div>
                                    <div class="my-1 col-6 col-sm-12 col-md-5">
                                        <div class="form-floating">
                                            <input type="text" class="form-control" id="arnomgru" name="arnomgru" placeholder="." style="text-transform:uppercase" list="datalistGrupos">
                                            <datalist id="datalistGrupos">
                                                <?php
                                                $query = "SELECT CONCAT(arcodgru, ' - ', arnomgru) as nome, arcodgru, arnomgru FROM grupos WHERE sr_deleted != 'T' ORDER BY arnomgru";
                                                $res = mysqli_query($conn, $query);
                                                if (mysqli_num_rows($res) > 0) {
                                                    while ($row = $res->fetch_object()) {
                                                        echo "<option value='$row->arcodgru'>$row->nome</option>";
                                                    }
                                                }
                                                ?>
                                            </datalist>
                                            <label for="arnomgru" class="">Grupos</label>
                                        </div>
                                    </div>
                                    <div class="my-1 col-6 col-sm-12 col-md-5">
                                        <div class="form-floating">
                                            <input type="text" class="form-control" id="arnommar" name="arnommar" placeholder="." style="text-transform:uppercase" list="datalistMarcas">
                                            <datalist id="datalistMarcas">
                                                <?php
                                                $query = "SELECT CONCAT(arcodmar, ' - ', arnommar) as nome, arcodmar, arnommar FROM marcas WHERE sr_deleted != 'T' ORDER BY arnommar";
                                                $res = mysqli_query($conn, $query);
                                                if (mysqli_num_rows($res) > 0) {
                                                    while ($row = $res->fetch_object()) {
                                                        echo "<option value='$row->arcodmar'>$row->nome</option>";
                                                    }
                                                }
                                                ?>
                                            </datalist>
                                            <label for="arnommar" class="">Marca</label>
                                        </div>
                                    </div>
                                </div>
                                <hr>
                                <div class="row">
                                    <div class="col">
                                        <legend class="col-form-label">Filtrar por...</legend>
                                        <div class="d-flex-md-row justify-content-between">
                                            <div class="my-1 form-check form-check-inline">
                                                <input class="form-check-input form-check-input-color" type="radio" name="orderby" id="inlineRadio1" value="ardesnot" checked>
                                                <label class="form-check-label" for="inlineRadio1">Descrição</label>
                                            </div>
                                            <div class="my-1 form-check form-check-inline">
                                                <input class="form-check-input form-check-input-color" type="radio" name="orderby" id="inlineRadio2" value="arrefere">
                                                <label class="form-check-label" for="inlineRadio2">Referência</label>
                                            </div>
                                            <div class="my-1 form-check form-check-inline ">
                                                <input class="form-check-input form-check-input-color" type="radio" name="orderby" id="inlineRadio3" value="arcodbar">
                                                <label class="form-check-label" for="inlineRadio3">Código de barras</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <hr>
                                <div class="row">
                                    <div class="col-12 mt-2">
                                        <button type="submit" class="btn btn-lg btn-success w-100 "><i class="bi-search"></i> Pesquisar</button>
                                    </div>
                                </div>
                                <input name="pesquisar" value="1" hidden>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php if (isset($_POST['pesquisar'])) {
            $limite = 50;
            $arcodigo = $_POST['arcodigo'];
            if ($arcodigo <> '') {
                $arcodigo = str_pad($_POST['arcodigo'], 7, '0', STR_PAD_LEFT);
            }
            $ardesnot = $_POST['ardesnot'];
            $arrefere = $_POST['arcodigo'];
            $arcodbar = $_POST['arcodigo'];
            $arcodmar = $_POST['arnommar'];
            $arcodgru = $_POST['arnomgru'];
            $orderby = $_POST['orderby'];
            $pagina = $_POST['pagina'] * $limite;

            $like_array_tags = explode(PHP_EOL, $ardesnot);
            $like_termos = "";
            foreach ($like_array_tags as $termo) {
                $like_termos = $like_termos . "(";
                $like_array = explode(' ', $termo);
                foreach ($like_array as $palavra) {
                    $like_termos = $like_termos . "COALESCE( e.ardesnot, e.ardescri ) LIKE '%$palavra%' AND ";
                }
                $like_termos = substr($like_termos, 0, -5) . ") OR ";
            }

            $like_termos = substr($like_termos, 0, -4);

            $query = "SELECT e.arcodigo, e.ardesnot, e.arunidad, e.arlcacao, e.arrefere, e.arcodbar, e.arfracio, 
                    CAST( MID( e.arqtdest, ( e.artabatu - 1) * 9 + 1 , 9 ) * 1 AS DECIMAL( 9,3 ) ) AS arqtdest, 
                    CAST( MID( arvrvend, ( artabatu - 1) * 16 + 1, 16 ) * 1 AS DECIMAL( 16,2 ) ) AS vr_vista,
                    CAST( MID( arvrcust, ( artabatu - 1) * 16 + 1, 16 ) * 1 AS DECIMAL( 16,2 ) ) AS vr_custo,
                    e.arqtd_estok, e.sr_recno, CONCAT(e.arcodmar, '-', m.arnommar) AS arnommar, CONCAT(e.arcodgru, '-', g.arnomgru) AS arnomgru ";
            if (($arcodmar <> '') && ($arcodgru <> '')) {
                $query .= "FROM (SELECT * FROM estoque WHERE arcodmar = '$arcodmar' AND arcodgru = '$arcodgru') e ";
            } elseif ($arcodmar <> '') {
                $query .= "FROM (SELECT * FROM estoque WHERE arcodmar = '$arcodmar') e ";
            } elseif ($arcodgru <> '') {
                $query .= "FROM (SELECT * FROM estoque WHERE arcodgru = '$arcodgru') e ";
            } else {
                $query .= "FROM estoque e ";
            }

            $query .= "LEFT JOIN marcas m ON m.arcodmar = e.arcodmar LEFT JOIN grupos g ON g.arcodgru = e.arcodgru ";

            if (($ardesnot <> '') || ($arcodigo <> '') || ($arcodmar <> '') || ($arcodgru <> '')) {
                $query .= "WHERE e.sr_deleted != 'T' AND";
            }
            if (($arcodigo <> '') && is_numeric($arcodigo)) {
                $query .= "(e.arcodigo = '$arcodigo' AND '$arcodigo' <> '') OR ";
            }
            if ($ardesnot <> '') {
                $query .= "($like_termos AND '$ardesnot' <> '') OR ";
            }
            if ($arrefere <> '') {
                $query .= "(e.arrefere LIKE '$arrefere%' AND '$arrefere' <> '') OR ";
            }
            if (($arcodbar <> '') && is_numeric($arcodbar)) {
                $query .= "(e.arcodbar LIKE '$arcodbar%' AND '$arcodbar' <> '') OR ";
            }

            if (substr($query, -3) == 'AND') {
                $query = substr($query, 0, -3);
            }

            if (substr($query, -3) == 'OR ') {
                $query = substr($query, 0, -3);
            }

            $res = mysqli_query($conn, $query);
            $regs = mysqli_num_rows($res);

            $query .= "ORDER BY $orderby LIMIT $pagina, $limite";
            //echo $query;
            $res = mysqli_query($conn, $query);
            if ($regs > 0) { ?>

                <?php
                $num = true;
                while ($row = $res->fetch_object()) {
                    $num = !$num;
                ?>
                    <div class="container ">
                        <form action="alteracao.php" method="post">
                            <div class="card card-mid <?php if ($num) echo "bg-success-subtle"; ?>">
                                <div class="card-body">
                                    <!-- <div class="card-header"> -->
                                    <div class="row">
                                        <div class="col-9">
                                            <div class="fs-6 fw-bold border-bottom <?php if ($num) echo "border-white"; ?>"><?php echo $row->ardesnot; ?></div>
                                        </div>
                                        <div class="col-3">
                                            <button type="submit" class="btn btn-success w-100"><i class="bi-send"></i></button>
                                            <input name="arcodigo" value="<?php echo $row->arcodigo; ?>" hidden>
                                            <input name="ardesnot" value="<?php echo $row->ardesnot; ?>" hidden>
                                            <input name="arnommar" value="<?php echo $row->arnommar; ?>" hidden>
                                            <input name="arnomgru" value="<?php echo $row->arnomgru; ?>" hidden>
                                            <input name="arrefere" value="<?php echo $row->arrefere; ?>" hidden>
                                            <input name="arcodbar" value="<?php echo $row->arcodbar; ?>" hidden>
                                            <input name="arlcacao" value="<?php echo $row->arlcacao; ?>" hidden>
                                            <input name="arqtd_estok" value="<?php echo $row->arqtdest; ?>" hidden>
                                            <input name="arunidad" value="<?php echo $row->arunidad; ?>" hidden>
                                            <input name="arqtdest" value="<?php echo $row->arqtdest; ?>" hidden>
                                            <input name="arvrvend" value="<?php echo $row->vr_vista; ?>" hidden>
                                            <input name="sr_recno" value="<?php echo $row->sr_recno; ?>" hidden>
                                            <input name="arfracio" value="<?php echo $row->arfracio; ?>" hidden>

                                        </div>
                                    </div>
                                    <!-- </div> -->
                                    <div class="row">
                                        <div class="col-6 col-md-2">
                                            <label for="arcodigo" class="small">CÓDIGO</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->arcodigo == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->arcodigo;
                                                                                                                        } ?></div>
                                        </div>
                                        <div class="col-8 col-sm-12 col-md-5">
                                            <label for="arnommar" class="small">MARCA</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->arnommar == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->arnommar;
                                                                                                                        } ?></div>
                                        </div>
                                        <div class="col-4 col-d-block d-xs-none d-sm-none d-md-none d-lg-none d-xl-none d-xxl-none">
                                            <label for="" class="small">CUSTO R$</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->vr_custo == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->vr_custo;
                                                                                                                        } ?></div>
                                        </div>
                                        <div class="col-8 col-sm-12 col-md-5">
                                            <label for="arnomgru" class="small">GRUPO</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->arnomgru == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->arnomgru;
                                                                                                                        } ?></div>
                                        </div>
                                        <div class="col-4 col-d-block d-xs-none d-sm-none d-md-none d-lg-none d-xl-none d-xxl-none">
                                            <label for="" class="small">VALOR R$</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->vr_vista == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->vr_vista;
                                                                                                                        } ?></div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-6">
                                            <label for="arcodigo" class="small">REFERÊNCIA</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->arrefere == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->arrefere;
                                                                                                                        } ?></div>
                                        </div>
                                        <div class="col-6">
                                            <label for="arrefere" class="small">CÓD. BARRAS</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->arcodbar == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->arcodbar;
                                                                                                                        } ?></div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-4">
                                            <label for="arcodigo" class="small">QTD. ESTOQUE</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->arqtdest == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->arqtdest;
                                                                                                                        } ?></div>
                                        </div>
                                        <div class="col-4">
                                            <label for="arrefere" class="small">UNIDADE</label>
                                            <div class="fs-6 border-bottom  <?php if ($num) echo "border-white"; ?>"><?php if ($row->arunidad == "") {
                                                                                                                            echo "-";
                                                                                                                        } else {
                                                                                                                            echo $row->arunidad;
                                                                                                                        } ?></div>
                                        </div>
                                        <div class="col-4">
                                            <label for="arcodigo" class="small">LOCAÇÃO</label>
                                            <div class="fs-6 border-bottom <?php if ($num) echo "border-white"; ?>"><?php if ($row->arlcacao == "") {
                                                                                                                        echo "-";
                                                                                                                    } else {
                                                                                                                        echo $row->arlcacao;
                                                                                                                    } ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                        <?php

                        ?>
                    </div>
                <?php }
                if ($regs > 50) {
                    echo "<div class='container'><div class='row mt-2'><nav aria-label='Paginação da pesquisa'><ul class='pagination justify-content-center'>";
                    if (($regs % 50) > 0) {
                        $pags = ($regs / 50) + 1;
                    } else {
                        $pags = $regs / 50;
                    }
                    $pagprior = $pagina - 1;
                    $pagnext = $pagina + 1;
                    if ($pagina == 1) {
                        echo "<li class='page-item disabled'><a class='page-link'>Anterior</a></li>";
                    } else {
                        echo "<li class='page-item '><a class='page-link' href='produtos.php?page=$pagprior'>Anterior</a></li>";
                    }
                    for ($i = 1; $i <= 10; $i++) {
                        echo "<li class='page-item'><a class='page-link' href='#'>$i</a></li>";
                    }
                    echo "<li class='page-item active '><a class='page-link' >$i</a></li>";
                    echo "<li class='page-item'><a class='page-link'>Próximo</a></li>";
                    echo "</ul></nav></div></div>";
                }
            } else {
                //echo mysqli_error($conn);
                if (isset($_POST['pesquisar'])) { ?>
                    <script type="text/javascript">
                        Swal.fire('Oops! Algo deu errado!', 'Nenhum produto encontrado!<br>Verifique se digitou os dados corretos nos campos de pesquisa', 'warning');
                    </script><?php }
                        }
                    } ?>
        <div class="container">
            <footer class="fixed-botton pt-3">
                <div class="row">
                    <div class="d-flex justify-content-between border-top text-white">
                        <p><i class="bi-pci-card"></i> <?php echo $_SESSION['mac']; ?></p>
                        <p>&copy; <script>
                                document.write(new Date().getFullYear())
                            </script> <a class="link-light" href="https://ontopsistemas.com.br">OnTop Sistemas</a>.</p>

                    </div>
                </div>

            </footer>
        </div>
    </main>
    <script src="assets/js/bootstrap.min.js"></script>

    <?php
    if (isset($_SESSION['error'])) {
        if ($_SESSION['error']) {
            $icone = 'error';
            $titulo = 'Oops! Algo deu errado!';
        } else {
            $icone = 'success';
            $titulo = 'Tudo certo!';
        }
    ?><script type="text/javascript">
            Swal.fire('<?php echo $titulo; ?>', '<?php echo $_SESSION['msg']; ?>', '<?php echo $icone; ?>');
        </script><?php
                    unset($_SESSION['error']);
                    unset($_SESSION['msg']);
                }
                    ?>
</body>

</html>