<?php
require '../config/db.php';

session_start();
ini_set("display_errors", 0);

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

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_pix'])) {
    $data = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if ($data['type_pix'] === 'PHONE') {
        $pixKey = $data['key_beneficiary'];
    } else {
        $pixKey = $data['key_beneficiary'];
    }
    if (empty($data['type_pix']) || empty($data['key_beneficiary']) || empty($data['name_beneficiary']) || empty($data['cpf_beneficiary'])) {
        $_SESSION['toast_message'] = 'Preencha todos os campos.';
        $_SESSION['toast_type'] = 'error';
        header('Location: add_bank_create.php');
        exit;
    } elseif (!in_array($data['type_pix'], ['CPF', 'EMAIL', 'PHONE'])) {
        $_SESSION['toast_message'] = 'Tipo de chave PIX inválida.';
        $_SESSION['toast_type'] = 'error';
        header('Location: add_bank_create.php');
        exit;
    } else {
        $pdo->beginTransaction();
        $stmtInsert = $pdo->prepare("INSERT INTO accounts_pix (phone_user, type_pix, key_beneficiary, name_beneficiary, cpf_beneficiary, status, created_at) VALUES (:phone_user, :type_pix, :key_beneficiary, :name_beneficiary, :cpf_beneficiary, :status, :created_at)");
        $stmtInsert->execute([
            ':phone_user' => $_SESSION['user'],
            ':type_pix' => $data['type_pix'],
            ':key_beneficiary' => $pixKey,
            ':name_beneficiary' => $data['name_beneficiary'],
            ':cpf_beneficiary' => $data['cpf_beneficiary'],
            ':status' => 'active',
            ':created_at' => date("Y-m-d H:i:s")
        ]);
        $pdo->commit();
        $_SESSION['toast_message'] = 'Conta PIX salva com sucesso!';
        $_SESSION['toast_type'] = 'success';
        header('Location: add_bank_create.php');
        exit;
    }
}