<?php
declare(strict_types=1);
include("../priviate/connectdb.inc");
include("spe2.php");
include("lang-ch.php");

// 获取和验证参数
$specialty_id = $_GET["specialty_id"] ?? '';
$zip_code = $_GET["zipcode"] ?? '';
$miles = (int)($_GET["miles"] ?? 10);
$page = (int)($_GET["page"] ?? 1);
$page = max(1, $page);

$records_per_page = 15;
$doctors = [];
$total_records = 0;
$total_pages = 0;
$specialty_name = '';
$search_performed = false;

// 如果有搜索参数
if (!empty($specialty_id) && !empty($zip_code)) {
    // 验证邮编格式
    if (!preg_match('/^[0-9]{5}([- ]?[0-9]{4})?$/', $zip_code)) {
        $search_performed = true;
    } else {
        $search_performed = true;

        // 获取邮编范围（安全处理）
        $zip_list_json = @file_get_contents("https://cdoc101.com/zip.php?zip=" . urlencode($zip_code) . "&miles=" . (int)$miles);
        if ($zip_list_json) {
            $zip_data = json_decode($zip_list_json, true);
            $zip_codes = $zip_data['data']['zip_codes'] ?? [];

            if (!empty($zip_codes)) {
                // 安全构造 SQL - 使用占位符
                $zip_placeholders = implode(',', array_fill(0, count($zip_codes), '?'));
                $spec_id = (int)$specialty_id;

                // 获取专科名称
                $spec_result = mysqli_query($con, "SELECT speciaties_ch FROM specialties WHERE specialty_id=$spec_id");
                if ($spec_result && $row = $spec_result->fetch_assoc()) {
                    $specialty_name = $row['speciaties_ch'];
                }

                // 构建基础查询
                $base_query = "
                    SELECT cmg.id, cmg.last, cmg.first, cmg.lang, cmg.cname,
                           specialties.speciaties_ch, school.school_ch,
                           cmg.states, cmg.city, cmg.specialty2_id,
                           cmg.clinic_ch, tbl_state.state_ch, tbl_state.state_name
                    FROM cmg
                    LEFT JOIN specialties ON cmg.specialty_id = specialties.specialty_id
                    LEFT JOIN school ON cmg.gradschool_id = school.gradschool_id
                    LEFT JOIN tbl_state ON cmg.state_id = tbl_state.state_id
                    WHERE cmg.specialty_id = $spec_id
                    AND cmg.zipcode IN ($zip_placeholders)
                    AND cmg.specialty2_id != 70
                    AND cmg.death < 1
                    ORDER BY cmg.ct DESC
                ";

                // 获取总记录数
                $stmt = $con->prepare(str_replace('SELECT cmg.id, cmg.last, cmg.first, cmg.lang, cmg.cname, specialties.speciaties_ch, school.school_ch, cmg.states, cmg.city, cmg.specialty2_id, cmg.clinic_ch, tbl_state.state_ch, tbl_state.state_name', 'SELECT COUNT(*) as cnt', $base_query));
                if ($stmt) {
                    $stmt->bind_param(str_repeat('i', count($zip_codes)), ...$zip_codes);
                    $stmt->execute();
                    $count_result = $stmt->get_result();
                    if ($count_row = $count_result->fetch_assoc()) {
                        $total_records = (int)$count_row['cnt'];
                    }
                    $stmt->close();
                }

                if ($total_records > 0) {
                    // 分页查询
                    $offset = ($page - 1) * $records_per_page;
                    $total_pages = ceil($total_records / $records_per_page);

                    $paginated_query = $base_query . " LIMIT $records_per_page OFFSET $offset";
                    $stmt = $con->prepare($paginated_query);
                    if ($stmt) {
                        $stmt->bind_param(str_repeat('i', count($zip_codes)), ...$zip_codes);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        while ($row = $result->fetch_assoc()) {
                            $doctors[] = $row;
                        }
                        $stmt->close();
                    }
                }
            }
        }
    }
}

// 生成 Meta 标签
if ($search_performed && $specialty_name) {
    $page_title = $specialty_name . '医生（' . ($total_records > 0 ? $total_records : '0') . '位）邮编' . htmlspecialchars($zip_code) . ' | CDoc101';
    $page_description = '查询' . $specialty_name . '医生，邮编' . htmlspecialchars($zip_code) . '范围内共有' . $total_records . '位讲中文医生。可查看医生资料、诊所地址、电话等信息，免费查询，无需注册。';
    $page_keywords = $specialty_name . '医生,' . htmlspecialchars($zip_code) . '医生,讲中文医生,华人医生,医生查询';
} else {
    $page_title = '按专科和邮编查询讲中文医生 | CDoc101';
    $page_description = '按医生专科和邮编查询讲中文的医生。可查看诊所地址、电话、工作时间及专业背景，免费查询，无需注册。';
    $page_keywords = '医生查询,按专科查询,按邮编查询,讲中文医生,华人医生';
}

// 使用 ob_start() 确保 meta 标签在正确位置
ob_start();
include "header.html";
$header_content = ob_get_clean();

// 检查是否已有 description meta 标签，如果没有则插入
if (strpos($header_content, '<meta name="description"') === false) {
    $meta_tags = '<meta name="description" content="' . htmlspecialchars($page_description, ENT_QUOTES, 'UTF-8') . '">' . "\n"
        . '<meta name="keywords" content="' . htmlspecialchars($page_keywords, ENT_QUOTES, 'UTF-8') . '">' . "\n"
        . '<title>' . htmlspecialchars($page_title, ENT_QUOTES, 'UTF-8') . '</title>' . "\n";

    $header_content = str_replace('</head>', $meta_tags . '</head>', $header_content);
}

echo $header_content;

echo "<style>
.search-results-table td { text-align: left; }
</style>";

echo "<div class=\"container\" style=\"margin-top: 20px;\">";

// 如果未进行搜索，显示搜索表单
if (!$search_performed) {
    echo "<div class=\"jumbotron\">";
    echo "<h2>按专科和邮编查询医生</h2>";
    echo "<p>输入医生专科和所在地邮编，查询附近讲中文的医生</p>";
    echo "</div>";

    echo "<form class=\"form-inline\" method=\"GET\" style=\"margin: 20px 0;\">";
    echo "<div class=\"form-group\" style=\"margin-right: 10px;\">";
    echo "<label for=\"specialty_id\">专科:</label>";
    echo "<select name=\"specialty_id\" id=\"specialty_id\" class=\"form-control\" required>";
    echo "<option value=\"\">请选择</option>";

    $spec_result = mysqli_query($con, "SELECT specialty_id, speciaties_ch FROM specialties ORDER BY speciaties_ch");
    if ($spec_result) {
        while ($row = $spec_result->fetch_assoc()) {
            $selected = ($specialty_id == $row['specialty_id']) ? 'selected' : '';
            echo "<option value=\"" . htmlspecialchars($row['specialty_id']) . "\" $selected>" . htmlspecialchars($row['speciaties_ch']) . "</option>";
        }
    }

    echo "</select>";
    echo "</div>";

    echo "<div class=\"form-group\" style=\"margin-right: 10px;\">";
    echo "<label for=\"zipcode\">邮编:</label>";
    echo "<input type=\"text\" name=\"zipcode\" id=\"zipcode\" class=\"form-control\" placeholder=\"5位数字\" value=\"" . htmlspecialchars($zip_code) . "\" required>";
    echo "</div>";

    echo "<button type=\"submit\" class=\"btn btn-primary\">搜索</button>";
    echo "</form>";

} elseif ($total_records < 1) {
    echo "<br><br>";
    echo "<div class=\"alert alert-warning\" role=\"alert\">";
    echo "<h2>未找到医生</h2>";
    echo "<p>在邮编 " . htmlspecialchars($zip_code) . " 范围内暂无 " . htmlspecialchars($specialty_name) . " 医生</p>";
    echo "</div>";
    echo "<p><a href=\"?specialty_id=" . htmlspecialchars($specialty_id) . "&zipcode=" . htmlspecialchars($zip_code) . "&miles=100\" class=\"btn btn-primary\">";
    echo "扩大到100迈再搜搜看";
    echo "</a></p>";
    echo "<br><br>";

    if ($fp = fopen("nullzip.txt", "a")) {
        fwrite($fp, $zip_code . "\n");
        fclose($fp);
    }
} else {
    // 显示结果信息
    echo "<div class=\"alert alert-info\">";
    echo "<strong>找到 " . $total_records . " 位医生</strong> | ";
    if ($total_pages > 1) {
        echo "第 " . $page . " / " . $total_pages . " 页";
    }
    echo "</div>";

    // 显示医生列表
    echo "<table class=\"table table-striped table-hover search-results-table\">";

    foreach ($doctors as $index => $row) {
        $id = (int)$row["id"];
        $cname = htmlspecialchars($row["cname"] ?? '');
        $lastname = htmlspecialchars($row["last"] ?? '');
        $firstname = htmlspecialchars($row["first"] ?? '');
        $specialties = htmlspecialchars($row["speciaties_ch"] ?? '');
        $lang = $row["lang"] ?? '';
        $clinic = htmlspecialchars($row["clinic_ch"] ?? '');
        $city = htmlspecialchars($row["city"] ?? '');
        $states = htmlspecialchars($row["states"] ?? '');
        $spe2 = $row["specialty2_id"] ?? '';

        // 检查照片是否存在
        $photo_path = "/var/www/html/physician/foto/{$id}.jpg";
        $has_photo = is_file($photo_path);
        $photo_src = $has_photo ? "/foto/{$id}.jpg" : "/images/no_foto.jpg";

        echo "<tr onclick=\"window.location='https://cdoc101.com/foto.php?id={$id}';\" style='cursor: pointer;'>";
        echo "<td style=\"width: 1%; padding: 5px;\"><img src=\"" . htmlspecialchars($photo_src) . "\" width=\"50\" height=\"70\" alt=\"" . $cname . "\"></td>";
        echo "<td><strong>" . $cname . "</strong></td>";
        echo "<td>" . $lastname . ", " . $firstname . "</td>";

        echo "<td>";
        echo $specialties;
        if ($spe2) {
            echo ", ";
            spe2($spe2);
        }
        echo "</td>";

        echo "<td>";
        language($lang);
        echo "</td>";

        echo "<td>" . $clinic . ", " . $city . ", " . $states . "</td>";
        echo "</tr>";

        // 每 5 个医生后插入广告行
        if (($index + 1) % 5 == 0) {
            echo "<tr>";
            echo "<td colspan=\"6\" style=\"padding: 12px 0; text-align: center;\">";
            echo '<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-6867265085889194" data-ad-slot="8381512262" data-ad-format="horizontal" data-full-width-responsive="true"></ins>';
            echo '<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>';
            echo "</td>";
            echo "</tr>";
        }
    }

    echo "</table>";

    // 分页导航
    if ($total_pages > 1) {
        echo "<nav aria-label=\"Page navigation\" style=\"text-align: center;\">";
        echo "<ul class=\"pagination\">";

        // 上一页
        if ($page > 1) {
            $prev_page = $page - 1;
            echo "<li><a href=\"?" . http_build_query(['specialty_id' => $specialty_id, 'zipcode' => $zip_code, 'miles' => $miles, 'page' => $prev_page]) . "\" aria-label=\"Previous\">";
            echo "<span aria-hidden=\"true\">&laquo;</span> 上一页</a></li>";
        } else {
            echo "<li class=\"disabled\"><span>&laquo; 上一页</span></li>";
        }

        // 页码
        $start_page = max(1, $page - 2);
        $end_page = min($total_pages, $page + 2);

        if ($start_page > 1) {
            echo "<li><a href=\"?" . http_build_query(['specialty_id' => $specialty_id, 'zipcode' => $zip_code, 'miles' => $miles, 'page' => 1]) . "\">1</a></li>";
            if ($start_page > 2) {
                echo "<li class=\"disabled\"><span>...</span></li>";
            }
        }

        for ($i = $start_page; $i <= $end_page; $i++) {
            if ($i == $page) {
                echo "<li class=\"active\"><span>$i</span></li>";
            } else {
                echo "<li><a href=\"?" . http_build_query(['specialty_id' => $specialty_id, 'zipcode' => $zip_code, 'miles' => $miles, 'page' => $i]) . "\">$i</a></li>";
            }
        }

        if ($end_page < $total_pages) {
            if ($end_page < $total_pages - 1) {
                echo "<li class=\"disabled\"><span>...</span></li>";
            }
            echo "<li><a href=\"?" . http_build_query(['specialty_id' => $specialty_id, 'zipcode' => $zip_code, 'miles' => $miles, 'page' => $total_pages]) . "\">" . $total_pages . "</a></li>";
        }

        // 下一页
        if ($page < $total_pages) {
            $next_page = $page + 1;
            echo "<li><a href=\"?" . http_build_query(['specialty_id' => $specialty_id, 'zipcode' => $zip_code, 'miles' => $miles, 'page' => $next_page]) . "\" aria-label=\"Next\">下一页 <span aria-hidden=\"true\">&raquo;</span></a></li>";
        } else {
            echo "<li class=\"disabled\"><span>下一页 &raquo;</span></li>";
        }

        echo "</ul>";
        echo "</nav>";
    }
}

echo "</div>";

include("footer.html");
?>

