<?php

require_once __DIR__ . '/core.php';

if ($con->request->isAjax()) {
    $action = $con->request->post('action');
    switch ($action) {
        case 'list':
            // 获取分页
            $limit = $con->request->post(['page', 'limit'], FILTER_VALIDATE_INT);
            // 查询数据
            $data = $con->db->table('mail')->find('id, m_mail, m_time, m_ip')
                ->order('m_time DESC')->limit(($limit['page'] - 1) * $limit['limit'], $limit['limit'])->all();
            // 处理数据
            $mails = [];
            foreach ($data as $index => $mail) {
                $mails[$index]['seq'] = $index + 1;
                $mails[$index]['id'] = $mail['id'];
                foreach (['mail', 'time'] as $key) {
                    $mails[$index][$key] = $mail['m_' . $key];
                }
                $mails[$index]['ip'] = long2ip($mail['m_ip']);
            }
            // 统计总数
            $count = $con->db->table('mail')->count();
            // 返回数据
            $data = [
                'msg'   => '',
                'code'  => 0,
                'count' => $count,
                'data'  => $mails
            ];
            $con->json($data);
            break;
        case 'drop':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('mail')->delete('id = ?', [$unique])->row();
            $code = 1 === $row;
            $con->json(['code' => $code]);
            break;
        case 'delete':
            // 获取唯一标识
            $unique = $con->request->post('unique');
            // 删除数据
            $row = $con->db->table('mail')->delete('id IN ('.$unique.')')->row();
            $code = is_numeric($row);
            $con->json(['code' => $code]);
            break;
        default:break;
    }
} else {
    $con->render('mail', ['host' => $hel->url(), 'path' => $hel->path(), 'crumb' => $breadcrumb]);
}