<?php
require '../conexao/conexao.php';
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cidade = $_POST['cidadepcp'] ?? '';
    $ano = $_POST['anopcp'] ?? '';
    $mes = $_POST['mespcp'] ?? '';
    $filial = $_POST['filialpcp'] ?? '';
    $etapapcp = $_POST['etapapcp'] ?? '';
    $funcionariopcp = $_POST['funcionariopcp'] ?? '';
    $id_meta = $_POST['id_metas_pcp'] ?? '';

    $query_string = http_build_query([
        'cidade' => $cidade,
        'ano' => $ano,
        'mes' => $mes,
        'filial' => $filial,
        'etapa' => $etapapcp,
        'cliente' => $funcionariopcp,
        'pesquisar' => ''
    ]);

    if (isset($_POST['confirmacao']) && $_POST['confirmacao'] === 'sim') {
        if (empty($id_meta)) {
            $location = 'index.php?status=erro&' . $query_string;
            header("Location: $location");
            exit();
        }

        $connectionmysql->begin_transaction();

        try {
            $stmt = $connectionmysql->prepare("DELETE FROM kpi.metas_producao WHERE codigo_funcionario = ? AND etapa = ? AND ano = ? AND mes = ?");
            if ($stmt === false) {
                throw new Exception('Prepare statement failed: ' . $connectionmysql->error);
            }

            $stmt->bind_param("iiii", $id_meta, $etapapcp, $ano, $mes);
            $stmt->execute();
            $stmt->close();

            $stmt2 = $connectionmysql->prepare("DELETE FROM kpi.adicao_producao WHERE codigo_funcionario = ? AND etapa = ? AND ano = ? AND mes = ?");
            if ($stmt2 === false) {
                throw new Exception('Prepare statement failed: ' . $connectionmysql->error);
            }

            $stmt2->bind_param("iiii", $id_meta, $etapapcp, $ano, $mes);
            $stmt2->execute();
            $stmt2->close();

            $connectionmysql->commit();

            $location = 'index.php?status=sucesso&acao=excluir&' . $query_string;
            header("Location: $location");
            exit();
        } catch (Exception $e) {
            $connectionmysql->rollback();
            error_log($e->getMessage());

            $location = 'index.php?status=erro&' . $query_string;
            header("Location: $location");
            exit();
        }
    } elseif (isset($_POST['confirmacao']) && $_POST['confirmacao'] === 'nao') {
        $location = 'index.php?' . $query_string;
        header("Location: $location");
        exit();
    } else {
        $location = 'index.php?' . $query_string;
        header("Location: $location");
        exit();
    }
} else {
    $location = 'index.php';
    header("Location: $location");
    exit();
}
