<?php
// 加载主系统配置（必须先加载，才能使用 $db）
require_once dirname(__DIR__) . '/config.php';

// 加密网站配置
define('ENCRYPT_SITE_NAME', 'PHP文件加密工具');

// 会话配置
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 检查登录状态
function isEncryptLoggedIn() {
    return isset($_SESSION['encrypt_user_id']);
}

// 获取当前登录用户
function getEncryptUser() {
    if (!isEncryptLoggedIn()) return null;
    global $db;
    $id = intval($_SESSION['encrypt_user_id']);
    $result = $db->query("SELECT * FROM users WHERE id = $id");
    if ($result && $result->num_rows > 0) {
        return $result->fetch_assoc();
    }
    return null;
}

// 检查用户是否有加密权限
function hasEncryptPermission($user = null) {
    global $db;
    if (!$user) $user = getEncryptUser();
    if (!$user) return false;
    
    // 管理员或代理商直接免费
    if ($user['role'] == 'admin' || $user['is_agent'] == 1) {
        return true;
    }
    
    // 普通用户检查是否购买过加密服务且未过期（包括永久）
    $service = getUserEncryptService($user);
    return !empty($service);
}

// 获取用户的有效服务信息（包括永久服务）
function getUserEncryptService($user = null) {
    global $db;
    if (!$user) $user = getEncryptUser();
    if (!$user) return null;
    
    // 查询未过期或永久（expire_date IS NULL）的服务
    $result = $db->query("SELECT * FROM encrypt_services WHERE user_id = {$user['id']} AND status = 1 AND (expire_date IS NULL OR expire_date > NOW())");
    if ($result && $result->num_rows > 0) {
        return $result->fetch_assoc();
    }
    return null;
}

// 获取服务剩余天数
function getServiceRemainingDays($service) {
    if (!$service) return 0;
    if (is_null($service['expire_date'])) return -1; // 永久
    
    $now = new DateTime();
    $expire = new DateTime($service['expire_date']);
    $diff = $now->diff($expire);
    return $diff->days;
}

// 要求登录
function requireEncryptLogin() {
    if (!isEncryptLoggedIn()) {
        header('Location: /encrypt/login.php');
        exit;
    }
}

// 要求有加密权限
function requireEncryptPermission() {
    requireEncryptLogin();
    $user = getEncryptUser();
    if (!hasEncryptPermission($user)) {
        header('Location: /encrypt/buy.php');
        exit;
    }
}

// 获取所有可用套餐
function getEncryptPackages() {
    global $db;
    return $db->fetchAll("SELECT * FROM encrypt_packages WHERE status = 1 ORDER BY sort_order, price ASC");
}

// 获取指定套餐信息
function getPackageById($id) {
    global $db;
    return $db->fetchOne("SELECT * FROM encrypt_packages WHERE id = $id AND status = 1");
}

// 获取加密公告
function getEncryptAnnouncement() {
    $announcement = getSiteConfig('encrypt_announcement');
    return $announcement !== null ? $announcement : '';
}
// ========== 优惠码相关函数 ==========

// 验证优惠码并返回优惠信息
function validateCoupon($code, $user_id, $amount) {
    global $db;
    
    $code = trim($code);
    if (empty($code)) return null;
    
    // 查询优惠码
    $coupon = $db->fetchOne("SELECT * FROM encrypt_coupons WHERE code = '$code' AND status = 1");
    
    if (!$coupon) {
        return ['valid' => false, 'message' => '优惠码不存在'];
    }
    
    // 检查是否过期
    if ($coupon['expire_date'] && strtotime($coupon['expire_date']) < time()) {
        return ['valid' => false, 'message' => '优惠码已过期'];
    }
    
    // 检查使用次数
    if ($coupon['usage_limit'] > 0 && $coupon['used_count'] >= $coupon['usage_limit']) {
        return ['valid' => false, 'message' => '优惠码已使用完'];
    }
    
    // 检查最低消费
    if ($coupon['min_amount'] > 0 && $amount < $coupon['min_amount']) {
        return ['valid' => false, 'message' => '订单金额不足 ¥' . number_format($coupon['min_amount'], 2)];
    }
    
    // 检查用户是否已使用过该优惠码
    $used = $db->fetchOne("SELECT id FROM encrypt_coupon_usage WHERE coupon_id = {$coupon['id']} AND user_id = $user_id");
    if ($used) {
        return ['valid' => false, 'message' => '您已使用过此优惠码'];
    }
    
    // 计算优惠金额
    $discount = 0;
    if ($coupon['type'] == 'fixed') {
        $discount = min($coupon['value'], $amount);
    } else {
        $discount = $amount * ($coupon['value'] / 100);
        if ($coupon['max_discount'] && $discount > $coupon['max_discount']) {
            $discount = $coupon['max_discount'];
        }
    }
    
    return [
        'valid' => true,
        'coupon_id' => $coupon['id'],
        'code' => $coupon['code'],
        'name' => $coupon['name'],
        'type' => $coupon['type'],
        'value' => $coupon['value'],
        'discount' => round($discount, 2),
        'final_amount' => round($amount - $discount, 2),
        'message' => '优惠 ¥' . number_format($discount, 2)
    ];
}

// 记录优惠码使用
function recordCouponUsage($coupon_id, $user_id, $amount, $discount) {
    global $db;
    
    // 插入使用记录
    $db->query("INSERT INTO encrypt_coupon_usage (coupon_id, user_id, order_amount, discount_amount) VALUES ($coupon_id, $user_id, $amount, $discount)");
    
    // 更新使用次数
    $db->query("UPDATE encrypt_coupons SET used_count = used_count + 1 WHERE id = $coupon_id");
}

// 获取用户可用的优惠码列表
function getUserCoupons($user_id) {
    global $db;
    return $db->fetchAll("
        SELECT c.* FROM encrypt_coupons c
        WHERE c.status = 1 
        AND (c.expire_date IS NULL OR c.expire_date > NOW())
        AND (c.usage_limit IS NULL OR c.used_count < c.usage_limit)
        AND NOT EXISTS (SELECT 1 FROM encrypt_coupon_usage u WHERE u.coupon_id = c.id AND u.user_id = $user_id)
        ORDER BY c.expire_date ASC
    ");
}
// ========== 邮件配置函数 ==========
function getMailConfig() {
    return [
        'host' => getSiteConfig('smtp_host') ?: 'smtp.qq.com',
        'port' => getSiteConfig('smtp_port') ?: 465,
        'user' => getSiteConfig('smtp_user') ?: '',
        'pass' => getSiteConfig('smtp_pass') ?: '',
        'from' => getSiteConfig('smtp_from') ?: '',
        'name' => getSiteConfig('smtp_name') ?: 'PHP加密工具',
    ];
}

// 发送邮件函数
function sendMail($to, $subject, $content) {
    $config = getMailConfig();
    
    if (empty($config['user']) || empty($config['pass'])) {
        error_log("邮件配置未设置");
        return false;
    }
    
    $autoloadPath = __DIR__ . '/vendor/autoload.php';
    if (!file_exists($autoloadPath)) {
        error_log("Composer autoload not found: " . $autoloadPath);
        return false;
    }
    
    require_once $autoloadPath;
    
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
    
    try {
        $mail->isSMTP();
        $mail->Host = $config['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $config['user'];
        $mail->Password = $config['pass'];
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $config['port'];
        $mail->setFrom($config['from'] ?: $config['user'], $config['name']);
        $mail->addAddress($to);
        
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        
        $mail->isHTML(true);
        $mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
        $mail->Body = $content;
        $mail->AltBody = strip_tags($content);
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("邮件发送失败: " . $mail->ErrorInfo);
        return false;
    }
}

// 发送购买成功通知
function sendPurchaseNotification($user, $package_name, $expire_date, $price, $discount = 0) {
    $subject = "购买成功 - " . ENCRYPT_SITE_NAME;
    
    $expire_text = $expire_date ? date('Y-m-d H:i:s', strtotime($expire_date)) : '永久有效';
    
    $content = '
    <html>
    <head><meta charset="UTF-8"></head>
    <body style="font-family: Arial, sans-serif;">
        <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <div style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0;">
                <h2>✅ 购买成功</h2>
            </div>
            <div style="background: #f9fafb; padding: 20px; border: 1px solid #e5e7eb;">
                <p>尊敬的用户，您好！</p>
                <p>您已成功购买 <strong>' . $package_name . '</strong> 加密服务。</p>
                <p>📅 有效期至：<strong>' . $expire_text . '</strong></p>
                <p>💰 支付金额：<strong>¥' . number_format($price, 2) . '</strong></p>
                ' . ($discount > 0 ? '<p>🎁 优惠：-¥' . number_format($discount, 2) . '</p>' : '') . '
                <p>现在就可以使用加密功能保护您的PHP代码了！</p>
                <p><a href="' . getSiteConfig('site_url') . '/encrypt/encrypt.php" style="display: inline-block; padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 8px;">立即加密</a></p>
            </div>
            <div style="background: #f3f4f6; padding: 15px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 10px 10px;">
                <p>此邮件由系统自动发送，请勿回复</p>
                <p>&copy; ' . date('Y') . ' ' . ENCRYPT_SITE_NAME . '</p>
            </div>
        </div>
    </body>
    </html>';
    
    return sendMail($user['email'], $subject, $content);
}
// 发送到期提醒
function sendExpireNotification($user, $remaining_days) {
    $subject = "服务到期提醒 - " . ENCRYPT_SITE_NAME;
    
    $content = '
    <html>
    <head><meta charset="UTF-8"></head>
    <body style="font-family: Arial, sans-serif;">
        <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <div style="background: linear-gradient(135deg, #f59e0b, #ef4444); color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0;">
                <h2>⚠️ 服务即将到期</h2>
            </div>
            <div style="background: #f9fafb; padding: 20px; border: 1px solid #e5e7eb;">
                <p>尊敬的用户 ' . htmlspecialchars($user['username']) . '，您好！</p>
                <p>您的加密服务即将到期，剩余 <strong style="font-size: 24px; color: #ef4444;">' . $remaining_days . '</strong> 天。</p>
                <p>到期后将无法继续使用加密功能，请及时续费以免影响使用。</p>
                <p><a href="' . getSiteConfig('site_url') . '/encrypt/buy.php" style="display: inline-block; padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 8px;">立即续费</a></p>
            </div>
            <div style="background: #f3f4f6; padding: 15px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 10px 10px;">
                <p>此邮件由系统自动发送，请勿回复</p>
                <p>&copy; ' . date('Y') . ' ' . ENCRYPT_SITE_NAME . '</p>
            </div>
        </div>
    </body>
    </html>';
    
    return sendMail($user['email'], $subject, $content);
}

?>