<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once dirname(__DIR__) . '/core/db/db.php';
require_once dirname(__DIR__) . '/core/lib/common.php';

$db = \Core\Db\DB::getInstance();
$action = trim((string) ($_POST['action'] ?? $_GET['action'] ?? ''));

function ytRecruitJson($code, $msg, array $data = [])
{
    echo json_encode(['code' => $code, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action !== 'apply') {
    ytRecruitJson(404, '未知操作');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    ytRecruitJson(405, '请求方法不允许');
}

$memberId = intval($_SESSION['member_id'] ?? 0);
if ($memberId <= 0) {
    ytRecruitJson(401, '请先登录');
}

requireMemberCsrfToken(true);
$recruitId = intval($_POST['recruit_id'] ?? $_POST['id'] ?? 0);
$name = trim((string) ($_POST['name'] ?? ''));
$phone = trim((string) ($_POST['phone'] ?? $_POST['mobile'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$content = trim((string) ($_POST['content'] ?? $_POST['resume'] ?? ''));

if ($recruitId <= 0) {
    ytRecruitJson(400, '参数错误');
}
if ($name === '' || $phone === '') {
    ytRecruitJson(400, '姓名和手机号不能为空');
}
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    ytRecruitJson(400, '邮箱格式不正确');
}

$recruit = $db->fetch("SELECT id, title FROM {$db->table('recruit')} WHERE id = ? AND status = 1 LIMIT 1", [$recruitId]);
if (!$recruit) {
    ytRecruitJson(404, '职位不存在或已下架');
}

$exists = $db->fetch(
    "SELECT id FROM {$db->table('recruit_apply')} WHERE member_id = ? AND recruit_id = ? ORDER BY id DESC LIMIT 1",
    [$memberId, $recruitId]
);
if ($exists) {
    ytRecruitJson(400, '您已申请过该职位，请勿重复提交');
}

$now = time();
$db->insert('recruit_apply', [
    'member_id' => $memberId,
    'recruit_id' => $recruitId,
    'name' => $name,
    'phone' => $phone,
    'email' => $email,
    'content' => $content,
    'status' => 0,
    'ip' => function_exists('getClientIp') ? getClientIp() : ($_SERVER['REMOTE_ADDR'] ?? ''),
    'create_time' => $now,
    'update_time' => $now,
]);

$db->query("UPDATE {$db->table('recruit')} SET apply_count = IFNULL(apply_count, 0) + 1 WHERE id = ?", [$recruitId]);

if (function_exists('sendAdminMessage')) {
    sendAdminMessage(
        '新职位申请：' . ($recruit['title'] ?? ''),
        "职位ID：{$recruitId}\n姓名：{$name}\n手机：{$phone}\n邮箱：{$email}\n内容：{$content}",
        $name
    );
}

ytRecruitJson(200, '申请提交成功');
