<?php
$pageTitle = '老黄历';
require_once 'header.php';
require_once 'config.php';

$selected_date = $_GET['date'] ?? date('Y-m-d');
$timestamp = strtotime($selected_date);
if ($timestamp === false) {
    $timestamp = time();
    $selected_date = date('Y-m-d');
}
$year = (int)date('Y', $timestamp);
$month = (int)date('n', $timestamp);
$day = (int)date('j', $timestamp);

$lunar_info = get_lunar_info($year, $month, $day);

function lunar_data() {
    return [
        0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2,
        0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977,
        0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970,
        0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950,
        0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557,
        0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0,
        0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0,
        0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6,
        0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570,
        0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x05ac0,0x0ab60,0x096d5,0x092e0,
        0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5,
        0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930,
        0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530,
        0x05aa0,0x076a3,0x096d0,0x04afb,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45,
        0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0,
        0x14b63,0x09370,0x049f8,0x04970,0x064b0,0x168a6,0x0ea50,0x06b20,0x1a6c4,0x0aae0,
        0x092e0,0x0d2e3,0x0c960,0x0d557,0x0d4a0,0x0da50,0x05d55,0x056a0,0x0a6d0,0x055d4,
        0x052d0,0x0a9b8,0x0a950,0x0b4a0,0x0b6a6,0x0ad50,0x055a0,0x0aba4,0x0a5b0,0x052b0,
        0x0b273,0x06930,0x07337,0x06aa0,0x0ad50,0x14b55,0x04b60,0x0a570,0x054e4,0x0d160,
        0x0e968,0x0d520,0x0daa0,0x16aa6,0x056d0,0x04ae0,0x0a9d4,0x0a4d0,0x0d150,0x0f252,
        0x0d520
    ];
}

function lunar_leap_month($y) {
    return lunar_data()[$y - 1900] & 0xf;
}

function lunar_leap_days($y) {
    if (lunar_leap_month($y)) {
        return (lunar_data()[$y - 1900] & 0x10000) ? 30 : 29;
    }
    return 0;
}

function lunar_month_days($y, $m) {
    return (lunar_data()[$y - 1900] & (0x10000 >> $m)) ? 30 : 29;
}

function lunar_year_days($y) {
    $sum = 348;
    for ($j = 0x8000; $j > 0x8; $j >>= 1) {
        $sum += (lunar_data()[$y - 1900] & $j) ? 1 : 0;
    }
    return $sum + lunar_leap_days($y);
}

function lunar_calendar($year, $month, $day) {
    $base_date = mktime(0, 0, 0, 1, 31, 1900);
    $target_date = mktime(0, 0, 0, $month, $day, $year);
    $offset = (int)(($target_date - $base_date) / 86400);

    $lunar_year = 1900;
    for ($i = 1900; $i < 2101; $i++) {
        $year_days = lunar_year_days($i);
        if ($offset < $year_days) {
            $lunar_year = $i;
            break;
        }
        $offset -= $year_days;
    }

    $leap = lunar_leap_month($lunar_year);
    $is_leap = false;
    $lunar_month = 1;

    for ($i = 1; $i <= 12; $i++) {
        $month_days = lunar_month_days($lunar_year, $i);
        if ($offset < $month_days) {
            $lunar_month = $i;
            break;
        }
        $offset -= $month_days;

        if ($leap == $i) {
            $leap_days = lunar_leap_days($lunar_year);
            if ($offset < $leap_days) {
                $lunar_month = $i;
                $is_leap = true;
                break;
            }
            $offset -= $leap_days;
        }
    }

    $lunar_day = $offset + 1;

    return ['year' => $lunar_year, 'month' => $lunar_month, 'day' => $lunar_day, 'is_leap' => $is_leap];
}

function get_lunar_info($year, $month, $day) {
    $lunar_month_names = [
        1 => '正月', 2 => '二月', 3 => '三月', 4 => '四月',
        5 => '五月', 6 => '六月', 7 => '七月', 8 => '八月',
        9 => '九月', 10 => '十月', 11 => '冬月', 12 => '腊月'
    ];
    $lunar_day_names = [
        1 => '初一', 2 => '初二', 3 => '初三', 4 => '初四', 5 => '初五',
        6 => '初六', 7 => '初七', 8 => '初八', 9 => '初九', 10 => '初十',
        11 => '十一', 12 => '十二', 13 => '十三', 14 => '十四', 15 => '十五',
        16 => '十六', 17 => '十七', 18 => '十八', 19 => '十九', 20 => '二十',
        21 => '廿一', 22 => '廿二', 23 => '廿三', 24 => '廿四', 25 => '廿五',
        26 => '廿六', 27 => '廿七', 28 => '廿八', 29 => '廿九', 30 => '三十'
    ];
    $tian_gan = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
    $di_zhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
    $sheng_xiao_arr = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];

    $lunar = lunar_calendar($year, $month, $day);
    $lunar_year = $lunar['year'];
    $lunar_month = $lunar['month'];
    $lunar_day = $lunar['day'];

    $lunar_month_name = ($lunar['is_leap'] ? '闰' : '') . ($lunar_month_names[$lunar_month] ?? '');
    $lunar_day_name = $lunar_day_names[$lunar_day] ?? '初一';

    $tg_index = ($lunar_year - 4) % 10;
    $dz_index = ($lunar_year - 4) % 12;
    $year_tg = $tian_gan[$tg_index];
    $year_dz = $di_zhi[$dz_index];
    $sheng_xiao = $sheng_xiao_arr[$dz_index];

    $month_dz_index = ($month + 1) % 12;
    $month_tg_index = ($year % 5 * 2 + $month + 3) % 10;
    $month_tg = $tian_gan[$month_tg_index];
    $month_dz = $di_zhi[$month_dz_index];

    $jd = gregoriantojd($month, $day, $year);
    $day_tg_index = ($jd + 9) % 10;
    $day_dz_index = ($jd + 1) % 12;
    $day_tg = $tian_gan[$day_tg_index];
    $day_dz = $di_zhi[$day_dz_index];

    $yi_list_all = [
        '嫁娶', '纳采', '订盟', '祭祀', '祈福', '求嗣', '开光', '出行',
        '解除', '入宅', '移徙', '安床', '修造', '动土',
        '上梁', '竖柱', '安门', '作灶', '安葬', '破土', '启攒', '除服',
        '成服', '立碑', '开市', '交易', '立券', '纳财', '栽种', '牧养',
        '纳畜', '理发', '会亲友', '入学', '纳婿', '冠笄', '进人口', '经络'
    ];
    $ji_list_all = [
        '开市', '交易', '安葬', '行丧', '伐木', '作梁',
        '破土', '掘井', '词讼', '移徙', '入宅', '造桥', '开仓'
    ];

    $seed = $year * 10000 + $month * 100 + $day;
    mt_srand($seed);

    $yi_count = mt_rand(4, 8);
    $yi_keys = array_rand($yi_list_all, min($yi_count, count($yi_list_all)));
    $yi = [];
    foreach ((array)$yi_keys as $k) {
        $yi[] = $yi_list_all[$k];
    }

    $ji_count = mt_rand(2, 5);
    $ji_keys = array_rand($ji_list_all, min($ji_count, count($ji_list_all)));
    $ji = [];
    foreach ((array)$ji_keys as $k) {
        $ji[] = $ji_list_all[$k];
    }

    $chong_zodiacs = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];
    $chong_index = (array_search($sheng_xiao, $chong_zodiacs) + 6) % 12;
    $chong = $chong_zodiacs[$chong_index];

    $sha_map = [
        '子' => '南', '丑' => '东', '寅' => '北', '卯' => '西',
        '辰' => '南', '巳' => '东', '午' => '北', '未' => '西',
        '申' => '南', '酉' => '东', '戌' => '北', '亥' => '西'
    ];
    $sha = $sha_map[$day_dz] ?? '东';

    mt_srand();

    $jie_qi_list = [
        ['01', '05', '小寒'], ['01', '20', '大寒'], ['02', '04', '立春'], ['02', '19', '雨水'],
        ['03', '05', '惊蛰'], ['03', '20', '春分'], ['04', '05', '清明'], ['04', '20', '谷雨'],
        ['05', '05', '立夏'], ['05', '21', '小满'], ['06', '05', '芒种'], ['06', '21', '夏至'],
        ['07', '07', '小暑'], ['07', '22', '大暑'], ['08', '07', '立秋'], ['08', '23', '处暑'],
        ['09', '07', '白露'], ['09', '23', '秋分'], ['10', '08', '寒露'], ['10', '23', '霜降'],
        ['11', '07', '立冬'], ['11', '22', '小雪'], ['12', '07', '大雪'], ['12', '22', '冬至']
    ];

    $current_jieqi = '';
    $current_month = sprintf('%02d', $month);
    $current_day = sprintf('%02d', $day);
    foreach ($jie_qi_list as $jq) {
        if ($current_month == $jq[0] && $current_day == $jq[1]) {
            $current_jieqi = $jq[2];
            break;
        }
    }

    $jishen_pool = ['天德', '月德', '天喜', '天医', '天赦', '三合', '六合', '母仓', '生气', '时阳', '不将', '益后', '青龙', '明堂', '金匮', '天贵'];
    $xiongshen_pool = ['劫煞', '五虚', '重日', '月煞', '月刑', '月害', '四忌', '八专', '触水龙', '单阴', '纯阴', '纯阳', '孤辰', '天贼'];

    mt_srand($seed);
    $js_count = mt_rand(3, 5);
    $js_keys = array_rand($jishen_pool, min($js_count, count($jishen_pool)));
    $jishen = [];
    foreach ((array)$js_keys as $k) {
        $jishen[] = $jishen_pool[$k];
    }

    $xs_count = mt_rand(2, 4);
    $xs_keys = array_rand($xiongshen_pool, min($xs_count, count($xiongshen_pool)));
    $xiongshen = [];
    foreach ((array)$xs_keys as $k) {
        $xiongshen[] = $xiongshen_pool[$k];
    }
    mt_srand();

    return [
        'year_tg' => $year_tg,
        'year_dz' => $year_dz,
        'sheng_xiao' => $sheng_xiao,
        'month_tg' => $month_tg,
        'month_dz' => $month_dz,
        'day_tg' => $day_tg,
        'day_dz' => $day_dz,
        'lunar_month' => $lunar_month_name,
        'lunar_day' => $lunar_day_name,
        'yi' => $yi,
        'ji' => $ji,
        'chong' => $chong,
        'sha' => $sha,
        'jieqi' => $current_jieqi,
        'jishen' => $jishen,
        'xiongshen' => $xiongshen,
        'weekday' => ['日', '一', '二', '三', '四', '五', '六'][date('w', strtotime("$year-$month-$day"))]
    ];
}
?>

<main class="site-main">

    <section class="page-banner">
        <div class="container">
            <h1>📅 老黄历</h1>
            <p>查阅吉日宜忌，择良辰吉日</p>
        </div>
    </section>

    <section class="almanac-section">
        <div class="container">
            <div class="almanac-date-picker">
                <form method="get" action="almanac.php" class="almanac-form">
                    <input type="date" name="date" value="<?php echo htmlspecialchars($selected_date); ?>" onchange="this.form.submit()" class="almanac-input">
                    <span class="almanac-nav">
                        <a href="?date=<?php echo date('Y-m-d', strtotime('-1 day', $timestamp)); ?>" class="almanac-arrow" title="前一天">◀</a>
                        <a href="?date=<?php echo date('Y-m-d'); ?>" class="btn-today">今天</a>
                        <a href="?date=<?php echo date('Y-m-d', strtotime('+1 day', $timestamp)); ?>" class="almanac-arrow" title="后一天">▶</a>
                    </span>
                </form>
            </div>

            <div class="almanac-main-card">
                <div class="almanac-header">
                    <div class="almanac-date-display">
                        <div class="gregorian-date">
                            <span class="year"><?php echo date('Y年', $timestamp); ?></span>
                            <span class="month-day"><?php echo date('m月d日', $timestamp); ?></span>
                            <span class="weekday">星期<?php echo $lunar_info['weekday']; ?></span>
                        </div>
                        <div class="lunar-date">
                            <span class="lunar-text">农历<?php echo $lunar_info['lunar_month'] . $lunar_info['lunar_day']; ?></span>
                            <?php if ($lunar_info['jieqi']): ?>
                            <span class="jieqi-tag"><?php echo $lunar_info['jieqi']; ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="almanac-ganzhi">
                    <div class="ganzhi-item">
                        <span class="ganzhi-label">年柱</span>
                        <span class="ganzhi-value"><?php echo $lunar_info['year_tg'] . $lunar_info['year_dz']; ?>年</span>
                        <span class="ganzhi-shengxiao">属<?php echo $lunar_info['sheng_xiao']; ?></span>
                    </div>
                    <div class="ganzhi-item">
                        <span class="ganzhi-label">月柱</span>
                        <span class="ganzhi-value"><?php echo $lunar_info['month_tg'] . $lunar_info['month_dz']; ?>月</span>
                    </div>
                    <div class="ganzhi-item">
                        <span class="ganzhi-label">日柱</span>
                        <span class="ganzhi-value"><?php echo $lunar_info['day_tg'] . $lunar_info['day_dz']; ?>日</span>
                    </div>
                </div>

                <div class="almanac-yi-ji">
                    <div class="yi-section">
                        <h3>✅ 宜</h3>
                        <div class="yi-ji-tags">
                            <?php foreach ($lunar_info['yi'] as $item): ?>
                            <span class="yi-tag"><?php echo $item; ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="ji-section">
                        <h3>❌ 忌</h3>
                        <div class="yi-ji-tags">
                            <?php foreach ($lunar_info['ji'] as $item): ?>
                            <span class="ji-tag"><?php echo $item; ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="almanac-extra">
                    <div class="extra-item">
                        <span class="extra-label">🐲 冲煞</span>
                        <span class="extra-value">冲<?php echo $lunar_info['chong']; ?> · 煞<?php echo $lunar_info['sha']; ?></span>
                    </div>
                    <div class="extra-item">
                        <span class="extra-label">⭐ 吉神</span>
                        <span class="extra-value"><?php echo implode('、', $lunar_info['jishen']); ?></span>
                    </div>
                    <div class="extra-item">
                        <span class="extra-label">💀 凶神</span>
                        <span class="extra-value"><?php echo implode('、', $lunar_info['xiongshen']); ?></span>
                    </div>
                </div>
            </div>

            <div class="almanac-tips-section">
                <div class="almanac-tip-card">
                    <h3>💡 择日小贴士</h3>
                    <ul>
                        <li>结婚择日以"嫁娶"为宜，避开冲煞新人生肖的日子。</li>
                        <li>阳泉本地习俗中，双数日期（农历）更为吉利。</li>
                        <li>最好同时参考双方父母的生肖，避免相冲。</li>
                        <li>节气交接日一般不宜举行重大仪式。</li>
                    </ul>
                </div>
            </div>
        </div>
    </section>

</main>

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