<?php
require_once __DIR__ . '/../base_api.php';

class EmailVerifyAPI extends BaseAPI {
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * 发送邮箱验证码
     */
    public function sendVerifyCode() {
        global $conf, $DB;
        
        $email = isset($_POST['email']) ? trim($_POST['email']) : '';
        
        if (empty($email)) {
            $this->error('请输入邮箱地址');
        }
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error('邮箱格式不正确');
        }
        
        // 检查邮箱是否已被其他用户使用
        $email_escaped = $DB->escape($email);
        $user_id_escaped = intval($this->user['id']);
        $existing = $DB->get_row("SELECT * FROM `zj` WHERE `email`='{$email_escaped}' AND `id`!='{$user_id_escaped}'");
        if ($existing) {
            $this->error('该邮箱已被其他用户使用');
        }
        
        // 生成6位验证码
        $code = rand(100000, 999999);
        
        // 存储验证码到session
        $_SESSION['email_verify_code'] = $code;
        $_SESSION['email_verify_email'] = $email;
        $_SESSION['email_verify_time'] = time();
        
        // 发送邮件
        $subject = '邮箱验证 - ' . $conf['name'];
        $content = "<h3>邮箱验证</h3>
        <p>您的验证码是：<strong style='font-size:24px;color:#188038;'>{$code}</strong></p>
        <p>验证码有效期为10分钟，请勿泄露给他人。</p>
        <p>如非本人操作，请忽略此邮件。</p>";
        
        $result = sendEmail($email, $subject, $content);
        
        // sendEmail成功时返回true，失败时返回数组
        if ($result === true || (is_array($result) && isset($result['success']) && $result['success'])) {
            $this->success(array('msg' => '验证码已发送，请查收邮件'));
        } else {
            $error_msg = is_array($result) && isset($result['error']) ? $result['error'] : '邮件发送失败';
            $this->error('邮件发送失败：' . $error_msg);
        }
    }
    
    /**
     * 验证邮箱验证码
     */
    public function verifyEmail() {
        global $DB;
        
        $email = isset($_POST['email']) ? trim($_POST['email']) : '';
        $code = isset($_POST['code']) ? trim($_POST['code']) : '';
        
        if (empty($email) || empty($code)) {
            $this->error('请输入邮箱和验证码');
        }
        
        // 检查验证码
        if (!isset($_SESSION['email_verify_code']) || 
            !isset($_SESSION['email_verify_email']) ||
            $_SESSION['email_verify_email'] != $email ||
            $_SESSION['email_verify_code'] != $code) {
            $this->error('验证码错误或已过期');
        }
        
        // 检查验证码是否过期（10分钟）
        if (time() - $_SESSION['email_verify_time'] > 600) {
            unset($_SESSION['email_verify_code']);
            unset($_SESSION['email_verify_email']);
            unset($_SESSION['email_verify_time']);
            $this->error('验证码已过期，请重新获取');
        }
        
        // 更新用户邮箱
        $email_escaped = $DB->escape($email);
        $user_id_escaped = intval($this->user['id']);
        $DB->query("UPDATE `zj` SET `email`='{$email_escaped}' WHERE `id`='{$user_id_escaped}'");
        
        // 清除验证码
        unset($_SESSION['email_verify_code']);
        unset($_SESSION['email_verify_email']);
        unset($_SESSION['email_verify_time']);
        
        $this->log('邮箱验证', '绑定邮箱: ' . $email);
        $this->success(array('msg' => '邮箱验证成功'));
    }
}
