<?php
require '../../config/db.php';
ini_set("display_errors", 0);

session_start();
if (!isset($_SESSION['admin_session'])) {
    header("Location: ../login.php");
    exit;
}

$token = bin2hex(random_bytes(10));

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_form'])) {
    $data = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $value = str_replace(['.', ','], ['', '.'], $data['value_product']);
    $dailyReturn = str_replace(['.', ','], ['', '.'], $data['dayreturn_product']);
    $totalReturnFormat = ($dailyReturn * $data['duration_product']);  
    
    var_dump($data);

    if (empty($data) ) {
        $_SESSION['toast_message'] = $toastMessage = 'Você precisa preencher todos os campos.';
        $_SESSION['toast_type'] = $toastType = 'error';
        header("Location: administer_products.php");
        exit;
    } elseif (!isset($_SESSION['admin_session'])) {
        $_SESSION['toast_message'] = $toastMessage = 'Você precisa está logado como admin.';
        $_SESSION['toast_type'] = $toastType = 'error';
        header("Location: ../login.php");
        exit;
    } else {
        try {
            $pdo->beginTransaction();
            // Insere o produto na tabela
            $insertProduct = $pdo->prepare("INSERT INTO investment_products (token, name, img, description, value, total_days, daily_return, total_return, is_active, created_at) VALUES (:token, :name, :img, :description, :value, :total_days, :daily_return, :total_return, :is_active, :created_at)");
            $insertProduct->execute([
                ':token' => $token,
                ':name' => $data['name_product'],
                ':img' => $data['img_product'],
                ':description' => $data['description_product'],
                ':value' => $value,
                ':daily_return' => $dailyReturn,
                ':total_days' => $data['duration_product'],
                ':total_return' => $totalReturnFormat,
                ':is_active' => 1,
                ':created_at' => date('Y-m-d H:i:s')
            ]);
            $pdo->commit();
            $_SESSION['toast_message'] = $toastMessage = 'Produto adicionado com sucesso!';
            $_SESSION['toast_type'] = $toastType = 'success';
            header("Location: administer_products.php");
            exit;
        } catch (PDOException $e) {
            $_SESSION['toast_message'] = $toastMessage = 'Ocorreu um erro interno, ao adicionar o produto. ' . $e->getMessage();
            $_SESSION['toast_type'] = $toastType = 'error';
            header("Location: administer_products.php");
            exit;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_user'])) {
    $id = filter_input(INPUT_POST, "id_product", FILTER_VALIDATE_INT);

    if (empty($id) || $id === false) {
        $_SESSION['toast_message'] = $toastMessage = 'ID do produto não encontrado.';
        $_SESSION['toast_type'] = $toastType = 'error';
        header("Location: administer_products.php");
        exit;
    } else {
        try {
            $pdo->beginTransaction();
            $deleteUser = $pdo->prepare("DELETE FROM investment_products WHERE id = :id");
            $deleteUser->execute([
            ':id' => $id
            ]);
            $pdo->commit();
            $_SESSION['toast_message'] = $toastMessage = 'Produto excluído com sucesso!';
            $_SESSION['toast_type'] = $toastType = 'success';
            header("Location: administer_products.php");
            exit;
        } catch (PDOException $e) {
            $_SESSION['toast_message'] = $toastMessage = 'Ocorreu um erro interno, ao deletar o produto. ' . $e->getMessage();
            $_SESSION['toast_type'] = $toastType = 'error';
            header("Location: administer_products.php");
            exit;
        } 
    }
    
}