<?php

function write_mail($user_id, $ank_id, $msg) {
    global $time;
    $db = new db;
    $user = get_user($user_id);
    $ank = get_user($ank_id);

    if (mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_conts` WHERE `id_user` = '$ank[id]' AND `id_ank` = '$user[id]' AND `type` = 'all'"), 0) == 0) {
        $db->query("INSERT INTO `mail_conts` (`id_user`, `id_ank`, `time`, `nick`, `time_last`, `count`) VALUES ('$ank[id]', '$user[id]', '$time', '$user[nick]', '$time', '1')");
        $db->query("INSERT INTO `mail` SET `id_user` = '$ank[id]', `id_cont` = '" . mysql_insert_id() . "', `msg` = '" . mysql_real_escape_string($msg) . "', `time` = '$time', `type` = 'to', `read` = '0'");
    } else {
        $acont = mysql_fetch_array(mysql_query("SELECT * FROM `mail_conts` WHERE `id_user` = '$ank[id]' AND `id_ank` = '$user[id]' AND `type` = 'all'"));
        $db->query("INSERT INTO `mail` SET `id_user` = '$ank[id]', `id_cont` = '$acont[id]', `msg` = '" . mysql_real_escape_string($msg) . "', `time` = '$time', `type` = 'to', `read` = '0'");
        $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `id_cont` = '$acont[id]' AND `read` = '0'"), 0);
        $db->query("UPDATE `mail_conts` SET `time_last` = '$time', `count` = '$count' WHERE `id` = '$acont[id]'");
    }
    if (mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_conts` WHERE `id_user` = '$user[id]' AND `id_ank` = '$ank[id]' AND `type` = 'all'"), 0) == 0) {
        $db->query("INSERT INTO `mail_conts` (`id_user`, `id_ank`, `time`, `nick`, `time_last`) VALUES ('$user[id]', '$ank[id]', '$time', '$ank[nick]', '$time')");
        $hid = mysql_insert_id();
        $db->query("INSERT INTO `mail` SET `id_user` = '$user[id]', `id_cont` = '" . mysqli_insert_id() . "', `msg` = '" . mysql_real_escape_string($msg) . "', `time` = '$time', `type` = 'at', `read` = '0'");
    } else {
        $ucont = mysql_fetch_array(mysql_query("SELECT * FROM `mail_conts` WHERE `id_user` = '$user[id]' AND `id_ank` = '$ank[id]' AND `type` = 'all'"));
        $db->query("UPDATE `mail_conts` SET `time_last` = '$time' WHERE `id` = '$ucont[id]'");
        $db->query("INSERT INTO `mail` SET `id_user` = '$user[id]', `id_cont` = '$ucont[id]', `msg` = '" . mysql_real_escape_string($msg) . "', `time` = '$time', `type` = 'at', `read` = '0'");
        $hid = $ucont['id'];
    }
    return $hid;
}
