<?php
$pageTitle = '八字测算';
require_once 'header.php';

$result = null;
$hunyin_result = null;
$error = null;
$mode = $_POST['mode'] ?? ($_GET['mode'] ?? 'bazi');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mode = $_POST['mode'] ?? 'bazi';

    if ($mode === 'hunyin') {
        $name1 = trim($_POST['name1'] ?? '');
        $gender1 = $_POST['gender1'] ?? '男';
        $birth_date1 = $_POST['birth_date1'] ?? '';
        $birth_time1 = $_POST['birth_time1'] ?? '08:00';
        $name2 = trim($_POST['name2'] ?? '');
        $gender2 = $_POST['gender2'] ?? '女';
        $birth_date2 = $_POST['birth_date2'] ?? '';
        $birth_time2 = $_POST['birth_time2'] ?? '08:00';

        if (empty($name1) || empty($birth_date1) || empty($name2) || empty($birth_date2)) {
            $error = '请填写双方姓名和出生日期';
        } else {
            $bazi1 = calculate_bazi($name1, $gender1, $birth_date1, $birth_time1);
            $bazi2 = calculate_bazi($name2, $gender2, $birth_date2, $birth_time2);
            $hunyin_result = calculate_hunyin($bazi1, $bazi2);
        }
    } else {
        $name = trim($_POST['name'] ?? '');
        $gender = $_POST['gender'] ?? '男';
        $birth_date = $_POST['birth_date'] ?? '';
        $birth_time = $_POST['birth_time'] ?? '08:00';

        if (empty($name) || empty($birth_date)) {
            $error = '请填写姓名和出生日期';
        } else {
            $result = calculate_bazi($name, $gender, $birth_date, $birth_time);
        }
    }
}

function gregorian_to_jd($year, $month, $day) {
    $a = (int)((14 - $month) / 12);
    $y = $year + 4800 - $a;
    $m = $month + 12 * $a - 3;
    return $day + (int)((153 * $m + 2) / 5) + 365 * $y + (int)($y / 4) - (int)($y / 100) + (int)($y / 400) - 32045;
}

function calculate_bazi($name, $gender, $birth_date, $birth_time) {
    $timestamp = strtotime($birth_date);
    $year = (int)date('Y', $timestamp);
    $month = (int)date('n', $timestamp);
    $day = (int)date('j', $timestamp);
    $hour = (int)substr($birth_time, 0, 2);

    $tian_gan = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
    $di_zhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
    $wu_xing_tg = ['木', '木', '火', '火', '土', '土', '金', '金', '水', '水'];
    $wu_xing_dz = ['水', '土', '木', '木', '土', '火', '火', '土', '金', '金', '土', '水'];

    $jieqi_day = [0, 6, 4, 6, 5, 6, 6, 7, 8, 8, 8, 7, 7];
    $chinese_month = ($month - 2 + 12) % 12 + 1;
    if ($day < $jieqi_day[$month]) {
        $chinese_month = ($month - 3 + 12) % 12 + 1;
    }

    $year_for_pillar = $year;
    if ($month < 2 || ($month == 2 && $day < 4)) {
        $year_for_pillar = $year - 1;
    }

    $year_tg_idx = ($year_for_pillar + 6) % 10;
    $year_dz_idx = ($year_for_pillar + 8) % 12;

    $month_dz_idx = ($chinese_month + 1) % 12;
    $month_tg_idx = (($year_tg_idx % 5) * 2 + $chinese_month + 1) % 10;

    $jdn = gregorian_to_jd($year, $month, $day);
    $sexagenary_idx = ($jdn + 49) % 60;
    $day_tg_idx = $sexagenary_idx % 10;
    $day_dz_idx = $sexagenary_idx % 12;

    $hour_dz_idx = (int)(($hour + 1) / 2) % 12;
    $hour_tg_idx = ($day_tg_idx * 2 + $hour_dz_idx) % 10;

    $bazi = [
        'year' => ['tg' => $tian_gan[$year_tg_idx], 'dz' => $di_zhi[$year_dz_idx]],
        'month' => ['tg' => $tian_gan[$month_tg_idx], 'dz' => $di_zhi[$month_dz_idx]],
        'day' => ['tg' => $tian_gan[$day_tg_idx], 'dz' => $di_zhi[$day_dz_idx]],
        'hour' => ['tg' => $tian_gan[$hour_tg_idx], 'dz' => $di_zhi[$hour_dz_idx]]
    ];

    $day_master = $tian_gan[$day_tg_idx];
    $day_master_wx = $wu_xing_tg[$day_tg_idx];

    $wx_count = ['金' => 0, '木' => 0, '水' => 0, '火' => 0, '土' => 0];
    foreach ($bazi as $pillar) {
        $wx_count[$wu_xing_tg[array_search($pillar['tg'], $tian_gan)]]++;
        $wx_count[$wu_xing_dz[array_search($pillar['dz'], $di_zhi)]]++;
    }

    $wx_colors = ['金' => '#FFD700', '木' => '#228B22', '水' => '#1E90FF', '火' => '#FF4500', '土' => '#8B4513'];

    $shi_shen_map = [
        '甲' => ['甲' => '比肩', '乙' => '劫财', '丙' => '食神', '丁' => '伤官', '戊' => '偏财', '己' => '正财', '庚' => '七杀', '辛' => '正官', '壬' => '偏印', '癸' => '正印'],
        '乙' => ['甲' => '劫财', '乙' => '比肩', '丙' => '伤官', '丁' => '食神', '戊' => '正财', '己' => '偏财', '庚' => '正官', '辛' => '七杀', '壬' => '正印', '癸' => '偏印'],
        '丙' => ['甲' => '偏印', '乙' => '正印', '丙' => '比肩', '丁' => '劫财', '戊' => '食神', '己' => '伤官', '庚' => '偏财', '辛' => '正财', '壬' => '七杀', '癸' => '正官'],
        '丁' => ['甲' => '正印', '乙' => '偏印', '丙' => '劫财', '丁' => '比肩', '戊' => '伤官', '己' => '食神', '庚' => '正财', '辛' => '偏财', '壬' => '正官', '癸' => '七杀'],
        '戊' => ['甲' => '七杀', '乙' => '正官', '丙' => '偏印', '丁' => '正印', '戊' => '比肩', '己' => '劫财', '庚' => '食神', '辛' => '伤官', '壬' => '偏财', '癸' => '正财'],
        '己' => ['甲' => '正官', '乙' => '七杀', '丙' => '正印', '丁' => '偏印', '戊' => '劫财', '己' => '比肩', '庚' => '伤官', '辛' => '食神', '壬' => '正财', '癸' => '偏财'],
        '庚' => ['甲' => '偏财', '乙' => '正财', '丙' => '七杀', '丁' => '正官', '戊' => '偏印', '己' => '正印', '庚' => '比肩', '辛' => '劫财', '壬' => '食神', '癸' => '伤官'],
        '辛' => ['甲' => '正财', '乙' => '偏财', '丙' => '正官', '丁' => '七杀', '戊' => '正印', '己' => '偏印', '庚' => '劫财', '辛' => '比肩', '壬' => '伤官', '癸' => '食神'],
        '壬' => ['甲' => '食神', '乙' => '伤官', '丙' => '偏财', '丁' => '正财', '戊' => '七杀', '己' => '正官', '庚' => '偏印', '辛' => '正印', '壬' => '比肩', '癸' => '劫财'],
        '癸' => ['甲' => '伤官', '乙' => '食神', '丙' => '正财', '丁' => '偏财', '戊' => '正官', '己' => '七杀', '庚' => '正印', '辛' => '偏印', '壬' => '劫财', '癸' => '比肩'],
    ];

    $shi_shen = [];
    foreach ($bazi as $pillar_name => $pillar) {
        $shi_shen[$pillar_name] = $shi_shen_map[$day_master][$pillar['tg']] ?? '';
    }

    $zodiacs = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];
    $zodiac = $zodiacs[$year_dz_idx];

    $analysis = generate_analysis($day_master_wx, $wx_count, $name, $gender);

    return [
        'name' => $name,
        'gender' => $gender,
        'birth' => $birth_date . ' ' . $birth_time,
        'bazi' => $bazi,
        'day_master' => $day_master,
        'day_master_wx' => $day_master_wx,
        'shi_shen' => $shi_shen,
        'zodiac' => $zodiac,
        'wx_count' => $wx_count,
        'wx_colors' => $wx_colors,
        'analysis' => $analysis
    ];
}

function generate_analysis($day_master_wx, $wx_count, $name, $gender) {
    $wx_traits = [
        '金' => '性格刚毅果断，讲义气，做事有原则。为人正直，雷厉风行，适合从事管理、金融、法律等行业。',
        '木' => '性格仁慈善良，有上进心和创造力。思维活跃，善于规划，适合从事教育、艺术、设计等行业。',
        '水' => '性格聪明灵活，善于变通，有很强的交际能力。思维敏捷，适合从事传媒、贸易、咨询等行业。',
        '火' => '性格热情奔放，充满活力，富有感染力。行动力强，适合从事演艺、销售、公关等行业。',
        '土' => '性格稳重诚信，踏实可靠，有很强的责任感。为人厚道，适合从事房地产、建筑、农业等行业。'
    ];

    $love_tips = [
        '金' => ['男' => '适合与属土或属水的伴侣结合，性格温柔包容者为佳。', '女' => '适合与稳重可靠的伴侣结合，属土之人能给你安全感。'],
        '木' => ['男' => '适合与属水或属木的伴侣结合，志趣相投最为重要。', '女' => '适合与有上进心的伴侣结合，属水之人能滋养你的成长。'],
        '水' => ['男' => '适合与属金或属木的伴侣结合，互相支持理解。', '女' => '适合与聪明风趣的伴侣结合，属金之人能给你稳定感。'],
        '火' => ['男' => '适合与属木或属火的伴侣结合，热情与默契并重。', '女' => '适合与阳光开朗的伴侣结合，属木之人能激发你的活力。'],
        '土' => ['男' => '适合与属火或属金的伴侣结合，互补互成。', '女' => '适合与可靠踏实的伴侣结合，属火之人能温暖你的心。']
    ];

    $marriage_tips = [
        '金' => '婚姻中注意不要太强势，多些温柔和包容。选择秋冬季结婚更为有利。婚礼主色调可选白色、金色。',
        '木' => '婚姻中注意沟通方式，避免固执己见。选择春季结婚最为有利。婚礼主色调可选绿色、原木色。',
        '水' => '婚姻中注意情绪管理，多表达内心感受。选择冬季结婚最为有利。婚礼主色调可选蓝色、黑色。',
        '火' => '婚姻中注意控制脾气，多些耐心和体贴。选择夏季结婚最为有利。婚礼主色调可选红色、橙色。',
        '土' => '婚姻中注意不要过于保守，多些浪漫惊喜。四季皆宜，秋季更佳。婚礼主色调可选黄色、棕色。'
    ];

    $total_wx = array_sum($wx_count);
    $wx_balance = [];
    foreach ($wx_count as $wx => $count) {
        $pct = $total_wx > 0 ? round($count / $total_wx * 100, 1) : 0;
        $wx_balance[$wx] = $pct;
    }

    return [
        'trait' => $wx_traits[$day_master_wx] ?? '命运掌握在自己手中，积极乐观面对生活。',
        'love' => ($love_tips[$day_master_wx][$gender] ?? '真诚相待，理解包容是幸福婚姻的基石。'),
        'marriage' => $marriage_tips[$day_master_wx] ?? '择良辰吉日，办美满婚礼。',
        'wx_balance' => $wx_balance
    ];
}

function calculate_hunyin($bazi1, $bazi2) {
    $tian_gan = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
    $di_zhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
    $wu_xing_tg = ['木', '木', '火', '火', '土', '土', '金', '金', '水', '水'];
    $wu_xing_dz = ['水', '土', '木', '木', '土', '火', '火', '土', '金', '金', '土', '水'];

    $tg_wuhe = [
        ['甲', '己'], ['乙', '庚'], ['丙', '辛'], ['丁', '壬'], ['戊', '癸']
    ];

    $dz_liuhe = [
        ['子', '丑'], ['寅', '亥'], ['卯', '戌'], ['辰', '酉'], ['巳', '申'], ['午', '未']
    ];

    $dz_liuchong = [
        ['子', '午'], ['丑', '未'], ['寅', '申'], ['卯', '酉'], ['辰', '戌'], ['巳', '亥']
    ];

    $dz_sanhe = [
        ['申', '子', '辰'], ['寅', '午', '戌'], ['巳', '酉', '丑'], ['亥', '卯', '未']
    ];

    $wx_sheng = ['金' => '水', '木' => '火', '水' => '木', '火' => '土', '土' => '金'];
    $wx_ke = ['金' => '木', '木' => '土', '水' => '火', '火' => '金', '土' => '水'];

    $zodiac1 = $bazi1['zodiac'];
    $zodiac2 = $bazi2['zodiac'];
    $dz1 = $bazi1['bazi']['year']['dz'];
    $dz2 = $bazi2['bazi']['year']['dz'];

    $zodiac_score = 10;
    $zodiac_detail = '';

    foreach ($dz_liuhe as $pair) {
        if (($dz1 === $pair[0] && $dz2 === $pair[1]) || ($dz1 === $pair[1] && $dz2 === $pair[0])) {
            $zodiac_score = 25;
            $zodiac_detail = "属{$zodiac1}与属{$zodiac2}地支六合（{$dz1}{$dz2}合），生肖般配，天生有缘！";
            break;
        }
    }
    if ($zodiac_score === 10) {
        foreach ($dz_sanhe as $group) {
            if (in_array($dz1, $group) && in_array($dz2, $group)) {
                $zodiac_score = 20;
                $zodiac_detail = "属{$zodiac1}与属{$zodiac2}同属三合局（" . implode('', $group) . "），缘分深厚！";
                break;
            }
        }
    }
    if ($zodiac_score === 10) {
        foreach ($dz_liuchong as $pair) {
            if (($dz1 === $pair[0] && $dz2 === $pair[1]) || ($dz1 === $pair[1] && $dz2 === $pair[0])) {
                $zodiac_score = 5;
                $zodiac_detail = "属{$zodiac1}与属{$zodiac2}地支六冲（{$dz1}{$dz2}冲），性格需多磨合，但冲亦有激发之意。";
                break;
            }
        }
    }
    if ($zodiac_score === 10) {
        $zodiac_detail = "属{$zodiac1}与属{$zodiac2}生肖无特殊合冲，属普通搭配，缘分看个人修为。";
    }

    $tg1 = $bazi1['day_master'];
    $tg2 = $bazi2['day_master'];
    $tg1_idx = array_search($tg1, $tian_gan);
    $tg2_idx = array_search($tg2, $tian_gan);
    $wx1 = $wu_xing_tg[$tg1_idx];
    $wx2 = $wu_xing_tg[$tg2_idx];

    $tgan_score = 10;
    $tgan_detail = '';

    foreach ($tg_wuhe as $pair) {
        if (($tg1 === $pair[0] && $tg2 === $pair[1]) || ($tg1 === $pair[1] && $tg2 === $pair[0])) {
            $tgan_score = 25;
            $tgan_detail = "日干{$tg1}与{$tg2}天干五合，情投意合，心意相通！";
            break;
        }
    }
    if ($tgan_score === 10) {
        if ($wx_sheng[$wx1] === $wx2) {
            $tgan_score = 18;
            $tgan_detail = "日干{$tg1}（{$wx1}）生{$tg2}（{$wx2}），五行相生，感情中有一方付出较多，但和谐融洽。";
        } elseif ($wx_sheng[$wx2] === $wx1) {
            $tgan_score = 18;
            $tgan_detail = "日干{$tg2}（{$wx2}）生{$tg1}（{$wx1}），五行相生，对方对你关爱有加。";
        } elseif ($wx_ke[$wx1] === $wx2) {
            $tgan_score = 8;
            $tgan_detail = "日干{$tg1}（{$wx1}）克{$tg2}（{$wx2}），五行相克，相处中需多包容忍让。";
        } elseif ($wx_ke[$wx2] === $wx1) {
            $tgan_score = 8;
            $tgan_detail = "日干{$tg2}（{$wx2}）克{$tg1}（{$wx1}），五行相克，对方性格较强，需互相体谅。";
        } elseif ($wx1 === $wx2) {
            $tgan_score = 15;
            $tgan_detail = "日干{$tg1}与{$tg2}同属{$wx1}，五行相同，志趣相投，默契十足。";
        } else {
            $tgan_detail = "日干{$tg1}（{$wx1}）与{$tg2}（{$wx2}）五行关系平和，相处无大碍。";
        }
    }

    $day_dz1 = $bazi1['bazi']['day']['dz'];
    $day_dz2 = $bazi2['bazi']['day']['dz'];

    $dzhi_score = 10;
    $dzhi_detail = '';

    foreach ($dz_liuhe as $pair) {
        if (($day_dz1 === $pair[0] && $day_dz2 === $pair[1]) || ($day_dz1 === $pair[1] && $day_dz2 === $pair[0])) {
            $dzhi_score = 25;
            $dzhi_detail = "日支{$day_dz1}与{$day_dz2}六合，夫妻宫相合，婚姻根基稳固！";
            break;
        }
    }
    if ($dzhi_score === 10) {
        foreach ($dz_sanhe as $group) {
            if (in_array($day_dz1, $group) && in_array($day_dz2, $group)) {
                $dzhi_score = 20;
                $dzhi_detail = "日支{$day_dz1}与{$day_dz2}同属三合局，夫妻宫有缘，感情和谐。";
                break;
            }
        }
    }
    if ($dzhi_score === 10) {
        foreach ($dz_liuchong as $pair) {
            if (($day_dz1 === $pair[0] && $day_dz2 === $pair[1]) || ($day_dz1 === $pair[1] && $day_dz2 === $pair[0])) {
                $dzhi_score = 5;
                $dzhi_detail = "日支{$day_dz1}与{$day_dz2}六冲，夫妻宫相冲，婚后需多沟通协调。";
                break;
            }
        }
    }
    if ($dzhi_score === 10) {
        $dzhi_detail = "日支{$day_dz1}与{$day_dz2}无特殊合冲，夫妻宫平和，婚姻平稳。";
    }

    $wx1_count = $bazi1['wx_count'];
    $wx2_count = $bazi2['wx_count'];
    $total1 = array_sum($wx1_count);
    $total2 = array_sum($wx2_count);

    $wx_score = 10;
    $wx_detail = '';
    $complement_count = 0;
    $conflict_count = 0;

    foreach (['金', '木', '水', '火', '土'] as $wx) {
        $pct1 = $total1 > 0 ? $wx1_count[$wx] / $total1 : 0;
        $pct2 = $total2 > 0 ? $wx2_count[$wx] / $total2 : 0;
        if ($pct1 < 0.08 && $pct2 > 0.15) $complement_count++;
        if ($pct2 < 0.08 && $pct1 > 0.15) $complement_count++;
        if ($pct1 > 0.25 && $pct2 > 0.25) $conflict_count++;
    }

    if ($complement_count >= 3) {
        $wx_score = 25;
        $wx_detail = "双方五行高度互补，你缺的对方有，对方缺的你补，天作之合！";
    } elseif ($complement_count >= 2) {
        $wx_score = 20;
        $wx_detail = "双方五行较为互补，能互相弥补不足，相处融洽。";
    } elseif ($complement_count >= 1) {
        $wx_score = 15;
        $wx_detail = "双方五行有一定互补性，部分不足可互相弥补。";
    } elseif ($conflict_count >= 2) {
        $wx_score = 8;
        $wx_detail = "双方五行有较多重叠，缺乏互补，需注意性格碰撞。";
    } else {
        $wx_detail = "双方五行分布较为均衡，无大冲突也无强互补，属中等搭配。";
    }

    $total_score = $zodiac_score + $tgan_score + $dzhi_score + $wx_score;

    if ($total_score >= 80) {
        $level = '天作之合';
        $level_desc = '八字高度契合，缘分深厚，是天赐良缘！婚姻幸福美满，白头偕老。';
        $level_color = '#e74c3c';
    } elseif ($total_score >= 65) {
        $level = '良缘佳配';
        $level_desc = '八字较为相合，感情基础扎实，是难得的好姻缘！用心经营，必能幸福。';
        $level_color = '#e67e22';
    } elseif ($total_score >= 50) {
        $level = '中上之缘';
        $level_desc = '八字有一定契合度，缘分不浅。相互理解包容，婚姻可成美事。';
        $level_color = '#f1c40f';
    } elseif ($total_score >= 35) {
        $level = '中等姻缘';
        $level_desc = '八字有合有冲，属普通搭配。需要双方多沟通磨合，用真心化解分歧。';
        $level_color = '#3498db';
    } else {
        $level = '需多磨合';
        $level_desc = '八字相克较多，相处挑战较大。但命理仅供参考，真心相爱亦可破局，关键是相互尊重与包容。';
        $level_color = '#95a5a6';
    }

    return [
        'person1' => $bazi1,
        'person2' => $bazi2,
        'zodiac_score' => $zodiac_score,
        'zodiac_detail' => $zodiac_detail,
        'tgan_score' => $tgan_score,
        'tgan_detail' => $tgan_detail,
        'dzhi_score' => $dzhi_score,
        'dzhi_detail' => $dzhi_detail,
        'wx_score' => $wx_score,
        'wx_detail' => $wx_detail,
        'total_score' => $total_score,
        'level' => $level,
        'level_desc' => $level_desc,
        'level_color' => $level_color
    ];
}
?>

<style>
.bazi-tabs { display:flex; gap:0; margin-bottom:24px; border-radius:12px; overflow:hidden; box-shadow:0 2px 12px rgba(0,0,0,0.08); }
.bazi-tab { flex:1; padding:14px 0; text-align:center; font-size:16px; font-weight:600; cursor:pointer; background:#f8f5f0; color:#8b7355; border:none; transition:all .3s; }
.bazi-tab.active { background:linear-gradient(135deg,#c0392b,#e74c3c); color:#fff; }
.bazi-tab:hover:not(.active) { background:#efe8df; }
.bazi-tab-content { display:none; }
.bazi-tab-content.active { display:block; }
.hunyin-couple { display:grid; grid-template-columns:1fr auto 1fr; gap:16px; align-items:start; }
.hunyin-vs { display:flex; align-items:center; justify-content:center; font-size:28px; font-weight:900; color:#c0392b; padding-top:80px; }
.hunyin-score-ring { width:160px; height:160px; border-radius:50%; display:flex; flex-direction:column; align-items:center; justify-content:center; margin:0 auto 20px; position:relative; }
.hunyin-score-ring::before { content:''; position:absolute; inset:0; border-radius:50%; border:8px solid #f0e6d8; }
.hunyin-score-num { font-size:42px; font-weight:900; line-height:1; }
.hunyin-score-label { font-size:13px; margin-top:4px; }
.hunyin-dimension { display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-bottom:20px; }
.hunyin-dim-card { background:#fff; border-radius:12px; padding:18px; box-shadow:0 2px 8px rgba(0,0,0,0.06); }
.hunyin-dim-card h4 { margin:0 0 8px; font-size:15px; color:#5a4a3a; }
.hunyin-dim-card .dim-score { font-size:24px; font-weight:800; color:#c0392b; }
.hunyin-dim-card .dim-max { font-size:13px; color:#aaa; }
.hunyin-dim-card p { margin:8px 0 0; font-size:13px; color:#7a6a5a; line-height:1.6; }
.hunyin-level-badge { display:inline-block; padding:6px 20px; border-radius:20px; font-size:18px; font-weight:700; color:#fff; margin-bottom:12px; }
.hunyin-compare-pillars { display:grid; grid-template-columns:1fr 1fr; gap:24px; margin-bottom:20px; }
.hunyin-person-pillars { text-align:center; }
.hunyin-person-pillars h4 { margin:0 0 12px; font-size:15px; color:#5a4a3a; }
.hunyin-person-pillars .bazi-pillars { justify-content:center; }
@media(max-width:768px) {
    .hunyin-couple { grid-template-columns:1fr; }
    .hunyin-vs { padding-top:0; font-size:22px; }
    .hunyin-dimension { grid-template-columns:1fr; }
    .hunyin-compare-pillars { grid-template-columns:1fr; }
}
</style>

<main class="site-main">

    <section class="page-banner">
        <div class="container">
            <h1>🔮 八字测算</h1>
            <p>解读命理八字，洞悉姻缘契合，为美满婚姻保驾护航</p>
        </div>
    </section>

    <section class="bazi-section">
        <div class="container">
            <div class="bazi-tabs">
                <div class="bazi-tab <?php echo $mode !== 'hunyin' ? 'active' : ''; ?>" onclick="switchBaziTab('bazi')">🔮 八字测算</div>
                <div class="bazi-tab <?php echo $mode === 'hunyin' ? 'active' : ''; ?>" onclick="switchBaziTab('hunyin')">💕 八字合婚</div>
            </div>

            <div id="tab-bazi" class="bazi-tab-content <?php echo $mode !== 'hunyin' ? 'active' : ''; ?>">
            <div class="bazi-layout">
                <div class="bazi-form-card">
                    <h2>📝 输入信息</h2>
                    <form method="post" action="bazi.php" class="bazi-calc-form">
                        <input type="hidden" name="mode" value="bazi">
                        <?php if ($error): ?>
                        <div class="form-error"><?php echo htmlspecialchars($error); ?></div>
                        <?php endif; ?>
                        <div class="form-group">
                            <label>姓名</label>
                            <input type="text" name="name" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>" placeholder="请输入姓名" required>
                        </div>
                        <div class="form-group">
                            <label>性别</label>
                            <select name="gender" class="form-select">
                                <option value="男" <?php echo ($_POST['gender'] ?? '') === '男' ? 'selected' : ''; ?>>男</option>
                                <option value="女" <?php echo ($_POST['gender'] ?? '') === '女' ? 'selected' : ''; ?>>女</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>出生日期（公历）</label>
                            <input type="date" name="birth_date" value="<?php echo htmlspecialchars($_POST['birth_date'] ?? ''); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>出生时间</label>
                            <select name="birth_time" class="form-select">
                                <option value="00:00" <?php echo ($_POST['birth_time'] ?? '') === '00:00' ? 'selected' : ''; ?>>子时 (23:00-00:59)</option>
                                <option value="02:00" <?php echo ($_POST['birth_time'] ?? '') === '02:00' ? 'selected' : ''; ?>>丑时 (01:00-02:59)</option>
                                <option value="04:00" <?php echo ($_POST['birth_time'] ?? '') === '04:00' ? 'selected' : ''; ?>>寅时 (03:00-04:59)</option>
                                <option value="06:00" <?php echo ($_POST['birth_time'] ?? '') === '06:00' ? 'selected' : ''; ?>>卯时 (05:00-06:59)</option>
                                <option value="08:00" <?php echo ($_POST['birth_time'] ?? '08:00') === '08:00' ? 'selected' : ''; ?>>辰时 (07:00-08:59)</option>
                                <option value="10:00" <?php echo ($_POST['birth_time'] ?? '') === '10:00' ? 'selected' : ''; ?>>巳时 (09:00-10:59)</option>
                                <option value="12:00" <?php echo ($_POST['birth_time'] ?? '') === '12:00' ? 'selected' : ''; ?>>午时 (11:00-12:59)</option>
                                <option value="14:00" <?php echo ($_POST['birth_time'] ?? '') === '14:00' ? 'selected' : ''; ?>>未时 (13:00-14:59)</option>
                                <option value="16:00" <?php echo ($_POST['birth_time'] ?? '') === '16:00' ? 'selected' : ''; ?>>申时 (15:00-16:59)</option>
                                <option value="18:00" <?php echo ($_POST['birth_time'] ?? '') === '18:00' ? 'selected' : ''; ?>>酉时 (17:00-18:59)</option>
                                <option value="20:00" <?php echo ($_POST['birth_time'] ?? '') === '20:00' ? 'selected' : ''; ?>>戌时 (19:00-20:59)</option>
                                <option value="22:00" <?php echo ($_POST['birth_time'] ?? '') === '22:00' ? 'selected' : ''; ?>>亥时 (21:00-22:59)</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary bazi-submit">🔮 开始测算</button>
                    </form>
                </div>

                <?php if ($result): ?>
                <div class="bazi-result-area">
                    <div class="bazi-result-header">
                        <h2>📊 <?php echo htmlspecialchars($result['name']); ?>的八字命盘</h2>
                        <span class="bazi-badge"><?php echo $result['gender']; ?> · 属<?php echo $result['zodiac']; ?></span>
                    </div>

                    <div class="bazi-pillars">
                        <div class="bazi-pillar">
                            <div class="pillar-label">年柱</div>
                            <div class="pillar-tg"><?php echo $result['bazi']['year']['tg']; ?></div>
                            <div class="pillar-dz"><?php echo $result['bazi']['year']['dz']; ?></div>
                            <div class="pillar-shishen"><?php echo $result['shi_shen']['year']; ?></div>
                        </div>
                        <div class="bazi-pillar">
                            <div class="pillar-label">月柱</div>
                            <div class="pillar-tg"><?php echo $result['bazi']['month']['tg']; ?></div>
                            <div class="pillar-dz"><?php echo $result['bazi']['month']['dz']; ?></div>
                            <div class="pillar-shishen"><?php echo $result['shi_shen']['month']; ?></div>
                        </div>
                        <div class="bazi-pillar bazi-pillar-master">
                            <div class="pillar-label">日柱（日元）</div>
                            <div class="pillar-tg"><?php echo $result['bazi']['day']['tg']; ?></div>
                            <div class="pillar-dz"><?php echo $result['bazi']['day']['dz']; ?></div>
                            <div class="pillar-shishen">日元</div>
                        </div>
                        <div class="bazi-pillar">
                            <div class="pillar-label">时柱</div>
                            <div class="pillar-tg"><?php echo $result['bazi']['hour']['tg']; ?></div>
                            <div class="pillar-dz"><?php echo $result['bazi']['hour']['dz']; ?></div>
                            <div class="pillar-shishen"><?php echo $result['shi_shen']['hour']; ?></div>
                        </div>
                    </div>

                    <div class="bazi-daymaster">
                        <span class="daymaster-label">日元：</span>
                        <span class="daymaster-value"><?php echo $result['day_master']; ?></span>
                        <span class="daymaster-wx" style="color:<?php echo $result['wx_colors'][$result['day_master_wx']]; ?>">五行属<?php echo $result['day_master_wx']; ?></span>
                    </div>

                    <div class="bazi-wuxing-bar">
                        <h3>五行分布</h3>
                        <div class="wuxing-bars">
                            <?php foreach (['金', '木', '水', '火', '土'] as $wx): ?>
                            <div class="wuxing-bar-item">
                                <span class="wuxing-name" style="color:<?php echo $result['wx_colors'][$wx]; ?>"><?php echo $wx; ?></span>
                                <div class="wuxing-bar-track">
                                    <div class="wuxing-bar-fill" style="width:<?php echo $result['analysis']['wx_balance'][$wx]; ?>%; background:<?php echo $result['wx_colors'][$wx]; ?>"></div>
                                </div>
                                <span class="wuxing-pct"><?php echo $result['analysis']['wx_balance'][$wx]; ?>%</span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="bazi-analysis">
                        <div class="analysis-card">
                            <h3>🎭 性格特征</h3>
                            <p><?php echo $result['analysis']['trait']; ?></p>
                        </div>
                        <div class="analysis-card">
                            <h3>💕 姻缘建议</h3>
                            <p><?php echo $result['analysis']['love']; ?></p>
                        </div>
                        <div class="analysis-card">
                            <h3>💒 婚姻指南</h3>
                            <p><?php echo $result['analysis']['marriage']; ?></p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            </div>

            <div id="tab-hunyin" class="bazi-tab-content <?php echo $mode === 'hunyin' ? 'active' : ''; ?>">
            <div class="bazi-layout">
                <div class="bazi-form-card" style="max-width:100%">
                    <h2>💕 双方信息</h2>
                    <form method="post" action="bazi.php" class="bazi-calc-form">
                        <input type="hidden" name="mode" value="hunyin">
                        <?php if ($error && $mode === 'hunyin'): ?>
                        <div class="form-error"><?php echo htmlspecialchars($error); ?></div>
                        <?php endif; ?>
                        <div class="hunyin-couple">
                            <div>
                                <h3 style="text-align:center;color:#c0392b;margin:0 0 12px">👰 方</h3>
                                <div class="form-group">
                                    <label>姓名</label>
                                    <input type="text" name="name1" value="<?php echo htmlspecialchars($_POST['name1'] ?? ''); ?>" placeholder="请输入姓名" required>
                                </div>
                                <div class="form-group">
                                    <label>性别</label>
                                    <select name="gender1" class="form-select">
                                        <option value="男" <?php echo ($_POST['gender1'] ?? '男') === '男' ? 'selected' : ''; ?>>男</option>
                                        <option value="女" <?php echo ($_POST['gender1'] ?? '') === '女' ? 'selected' : ''; ?>>女</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>出生日期（公历）</label>
                                    <input type="date" name="birth_date1" value="<?php echo htmlspecialchars($_POST['birth_date1'] ?? ''); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label>出生时间</label>
                                    <select name="birth_time1" class="form-select">
                                        <?php
                                        $time_options = [
                                            '00:00' => '子时 (23:00-00:59)', '02:00' => '丑时 (01:00-02:59)',
                                            '04:00' => '寅时 (03:00-04:59)', '06:00' => '卯时 (05:00-06:59)',
                                            '08:00' => '辰时 (07:00-08:59)', '10:00' => '巳时 (09:00-10:59)',
                                            '12:00' => '午时 (11:00-12:59)', '14:00' => '未时 (13:00-14:59)',
                                            '16:00' => '申时 (15:00-16:59)', '18:00' => '酉时 (17:00-18:59)',
                                            '20:00' => '戌时 (19:00-20:59)', '22:00' => '亥时 (21:00-22:59)'
                                        ];
                                        $sel1 = $_POST['birth_time1'] ?? '08:00';
                                        foreach ($time_options as $val => $label): ?>
                                        <option value="<?php echo $val; ?>" <?php echo $sel1 === $val ? 'selected' : ''; ?>><?php echo $label; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="hunyin-vs">VS</div>
                            <div>
                                <h3 style="text-align:center:#c0392b;margin:0 0 12px">🤵 方</h3>
                                <div class="form-group">
                                    <label>姓名</label>
                                    <input type="text" name="name2" value="<?php echo htmlspecialchars($_POST['name2'] ?? ''); ?>" placeholder="请输入姓名" required>
                                </div>
                                <div class="form-group">
                                    <label>性别</label>
                                    <select name="gender2" class="form-select">
                                        <option value="男" <?php echo ($_POST['gender2'] ?? '') === '男' ? 'selected' : ''; ?>>男</option>
                                        <option value="女" <?php echo ($_POST['gender2'] ?? '女') === '女' ? 'selected' : ''; ?>>女</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>出生日期（公历）</label>
                                    <input type="date" name="birth_date2" value="<?php echo htmlspecialchars($_POST['birth_date2'] ?? ''); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label>出生时间</label>
                                    <select name="birth_time2" class="form-select">
                                        <?php
                                        $sel2 = $_POST['birth_time2'] ?? '08:00';
                                        foreach ($time_options as $val => $label): ?>
                                        <option value="<?php echo $val; ?>" <?php echo $sel2 === $val ? 'selected' : ''; ?>><?php echo $label; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary bazi-submit" style="width:100%;margin-top:16px">💕 开始合婚</button>
                    </form>
                </div>

                <?php if ($hunyin_result): ?>
                <div class="bazi-result-area">
                    <div class="bazi-result-header" style="text-align:center">
                        <h2>💕 <?php echo htmlspecialchars($hunyin_result['person1']['name']); ?> & <?php echo htmlspecialchars($hunyin_result['person2']['name']); ?> 合婚结果</h2>
                    </div>

                    <div class="hunyin-compare-pillars">
                        <div class="hunyin-person-pillars">
                            <h4><?php echo htmlspecialchars($hunyin_result['person1']['name']); ?>（属<?php echo $hunyin_result['person1']['zodiac']; ?>）</h4>
                            <div class="bazi-pillars">
                                <?php foreach (['year','month','day','hour'] as $p): ?>
                                <div class="bazi-pillar">
                                    <div class="pillar-label"><?php echo ['year'=>'年柱','month'=>'月柱','day'=>'日柱','hour'=>'时柱'][$p]; ?></div>
                                    <div class="pillar-tg"><?php echo $hunyin_result['person1']['bazi'][$p]['tg']; ?></div>
                                    <div class="pillar-dz"><?php echo $hunyin_result['person1']['bazi'][$p]['dz']; ?></div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="hunyin-person-pillars">
                            <h4><?php echo htmlspecialchars($hunyin_result['person2']['name']); ?>（属<?php echo $hunyin_result['person2']['zodiac']; ?>）</h4>
                            <div class="bazi-pillars">
                                <?php foreach (['year','month','day','hour'] as $p): ?>
                                <div class="bazi-pillar">
                                    <div class="pillar-label"><?php echo ['year'=>'年柱','month'=>'月柱','day'=>'日柱','hour'=>'时柱'][$p]; ?></div>
                                    <div class="pillar-tg"><?php echo $hunyin_result['person2']['bazi'][$p]['tg']; ?></div>
                                    <div class="pillar-dz"><?php echo $hunyin_result['person2']['bazi'][$p]['dz']; ?></div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <div style="text-align:center;margin-bottom:24px">
                        <div class="hunyin-score-ring" style="border:8px solid <?php echo $hunyin_result['level_color']; ?>">
                            <div class="hunyin-score-num" style="color:<?php echo $hunyin_result['level_color']; ?>"><?php echo $hunyin_result['total_score']; ?></div>
                            <div class="hunyin-score-label">总分/100</div>
                        </div>
                        <div class="hunyin-level-badge" style="background:<?php echo $hunyin_result['level_color']; ?>"><?php echo $hunyin_result['level']; ?></div>
                        <p style="color:#7a6a5a;line-height:1.8;max-width:500px;margin:8px auto"><?php echo $hunyin_result['level_desc']; ?></p>
                    </div>

                    <div class="hunyin-dimension">
                        <div class="hunyin-dim-card">
                            <h4>🐾 生肖配对</h4>
                            <div><span class="dim-score"><?php echo $hunyin_result['zodiac_score']; ?></span><span class="dim-max">/25</span></div>
                            <p><?php echo $hunyin_result['zodiac_detail']; ?></p>
                        </div>
                        <div class="hunyin-dim-card">
                            <h4>☀️ 日干相合</h4>
                            <div><span class="dim-score"><?php echo $hunyin_result['tgan_score']; ?></span><span class="dim-max">/25</span></div>
                            <p><?php echo $hunyin_result['tgan_detail']; ?></p>
                        </div>
                        <div class="hunyin-dim-card">
                            <h4>🏠 日支关系</h4>
                            <div><span class="dim-score"><?php echo $hunyin_result['dzhi_score']; ?></span><span class="dim-max">/25</span></div>
                            <p><?php echo $hunyin_result['dzhi_detail']; ?></p>
                        </div>
                        <div class="hunyin-dim-card">
                            <h4>⚖️ 五行互补</h4>
                            <div><span class="dim-score"><?php echo $hunyin_result['wx_score']; ?></span><span class="dim-max">/25</span></div>
                            <p><?php echo $hunyin_result['wx_detail']; ?></p>
                        </div>
                    </div>

                    <div class="analysis-card" style="text-align:center;background:#fff9f5">
                        <p style="color:#aaa;font-size:13px;margin:0">💡 八字合婚仅供参考，真心相爱、相互尊重才是幸福婚姻的根本。命理之说，信而不迷。</p>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            </div>
        </div>
    </section>

</main>

<script>
function switchBaziTab(tab) {
    document.querySelectorAll('.bazi-tab').forEach(function(t, i) {
        t.classList.toggle('active', (tab === 'bazi' && i === 0) || (tab === 'hunyin' && i === 1));
    });
    document.getElementById('tab-bazi').classList.toggle('active', tab === 'bazi');
    document.getElementById('tab-hunyin').classList.toggle('active', tab === 'hunyin');
    history.replaceState(null, '', '?mode=' + tab);
}
<?php if ($mode === 'hunyin'): ?>
switchBaziTab('hunyin');
<?php endif; ?>
</script>

<?php require_once 'footer.php'; ?>