<?php
class DataValidation extends Core
{

    function cpf()
    {

        $cpf = $_GET['cpf'];
        $account_type = $_GET['accountType'];
        $sql = "SELECT * FROM leads WHERE cpf = ? AND account_type = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$cpf, $account_type]);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($stmt->rowCount() > 0)
            return ['type' => 'ALREAD_EXIST', 'dados' => $result];

        return ['type' => 'OK'];
    }

    function cnpj()
    {

        $cnpj = $_GET['cnpj'];

        $sql = "SELECT companyname, cnpj FROM companies WHERE cnpj = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$cnpj]);

        if ($stmt->rowCount() > 0)
            return ['type' => 'ALREAD_EXIST', 'data' => $stmt->fetch(PDO::FETCH_ASSOC)];

        return ['type' => 'OK'];
    }

    function phone()
    {

        $phone = $_GET['phone'];
        $account_type = $_GET['accountType'];
        $id = $_GET['id'];
        $sql = "SELECT * FROM leads WHERE phone = ? AND id <> ? AND account_type = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$phone, $id, $account_type]);

        if ($stmt->rowCount() > 0)
            return ['type' => 'ALREAD_EXIST'];

        return ['type' => 'OK'];
    }

    function email()
    {

        $email = $_GET['email'];
        $id = $_GET['id']?$_GET['id']:null;

        $sql = "SELECT * FROM leads WHERE email = ?";
        if (!empty($id)) {
            $sql .= " AND id <> ?";
        }

        $stmt = parent::$conn->prepare($sql);
        if (!empty($id)) {
            $stmt->execute([$email, $id]);
        } else {
            $stmt->execute([$email]);
        }

        if ($stmt->rowCount() > 0) {
            return ['type' => 'ALREADY_EXIST'];
        }

        return ['type' => 'OK'];
    }
}
