<?php

// ==========================================
// ตั้งค่า Session
// ==========================================
session_name('PLAN_HIGHWAY5_SESSID');
session_start();


// ==========================================
// ตรวจสอบการเข้าสู่ระบบ
// ==========================================
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}


// ==========================================
// 1. ตั้งค่าการเชื่อมต่อฐานข้อมูล
// ==========================================
$host = 'localhost';
$dbname = 'highways_planing';
$username = 'root';
$password = 'P@ssword1989';

try {

    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8",
        $username,
        $password
    );

    $pdo->setAttribute(
        PDO::ATTR_ERRMODE,
        PDO::ERRMODE_EXCEPTION
    );

    // เก็บ Log User
    $current_user_id = isset($_SESSION['user_id'])
        ? $_SESSION['user_id']
        : 0;

    $pdo->exec(
        "SET @current_user_id = " . (int)$current_user_id
    );

} catch (PDOException $e) {

    die(
        "เชื่อมต่อฐานข้อมูลล้มเหลว: "
        . $e->getMessage()
    );
}


// ==========================================
// 2. ดึงข้อมูลปีงบประมาณสำหรับ Dropdown
// ==========================================
$budget_years = array();

try {

    $stmt_year = $pdo->query("
        SELECT DISTINCT budget_year
        FROM import_plan
        WHERE budget_year IS NOT NULL
        AND budget_year != ''
        ORDER BY budget_year DESC
    ");

    $budget_years = $stmt_year->fetchAll(PDO::FETCH_COLUMN);

} catch (PDOException $e) {

    $budget_years = array();
}


// ==========================================
// 3. คำนวณปีงบประมาณปัจจุบัน
//
// ปีงบประมาณไทย
// 1 ต.ค. - 30 ก.ย.
//
// ตัวอย่าง
// 1 ต.ค. 2569 เป็นต้นไป = ปีงบประมาณ 2570
// 30 ก.ย. 2569 = ปีงบประมาณ 2569
// ==========================================

$current_year_ad = (int)date('Y');
$current_month   = (int)date('n');
$current_day     = (int)date('j');

$current_fiscal_year = $current_year_ad + 543;

// ถ้าเดือนตุลาคม - ธันวาคม
// ให้เป็นปีงบประมาณของปีถัดไป
if ($current_month >= 10) {
    $current_fiscal_year++;
}


// ==========================================
// 4. รับค่าจากฟอร์มค้นหา
// ==========================================

$search_id_code = isset($_GET['search_id_code'])
    ? trim($_GET['search_id_code'])
    : '';
// สำนักฯ
$search_bureau = isset($_GET['search_bureau'])
    ? trim($_GET['search_bureau'])
    : '';
// ⭐ Default = ปีงบประมาณปัจจุบัน
$search_budget_year = isset($_GET['search_budget_year'])
    ? trim($_GET['search_budget_year'])
    : (string)$current_fiscal_year;


$search_pro_account = isset($_GET['search_pro_account'])
    ? trim($_GET['search_pro_account'])
    : '';

$search_highway_district = isset($_GET['search_highway_district'])
    ? trim($_GET['search_highway_district'])
    : '';

$search_job_code = isset($_GET['search_job_code'])
    ? trim($_GET['search_job_code'])
    : '';

$search_highway_number = isset($_GET['search_highway_number'])
    ? trim($_GET['search_highway_number'])
    : '';

$search_section_name = isset($_GET['search_section_name'])
    ? trim($_GET['search_section_name'])
    : '';

$search_auth_work_type = isset($_GET['search_auth_work_type'])
    ? trim($_GET['search_auth_work_type'])
    : '';


$import_plans = array();


// ==========================================
// 5. ข้อมูลผู้ใช้จาก Session
// ==========================================

$department = isset($_SESSION['department'])
    ? $_SESSION['department']
    : 'ไม่ระบุ';

$full_name = isset($_SESSION['full_name'])
    ? $_SESSION['full_name']
    : 'ผู้ดูแลระบบ';


// ==========================================
// 6. ดึงข้อมูลจากตารางทั้งหมด
// ==========================================

try {

    $sql = "
        SELECT
            p.*,

            t.branch_send_doc_no,
            t.sent_to_wb_date,
            t.received_from_wb_date,
            t.branch_send_date,
            t.wp_pass_doc_no,
            t.wp_pass_date,
            t.dir_approve_doc_no,
            t.dir_approve_date,
            t.central_approve_doc_no,
            t.central_approve_date,
            t.core_ftp_plan,
            t.core_upload_date,
            t.estimator_name,
            t.branch_send_median_doc,
            t.issue_median_date,
            t.median_price,
            t.approve_median_date,
            t.is_median_approved,
            t.auth_work_type,
            t.announce_by,
            t.tor_drafted_by,

            pt.district_send_tor_date,
            pt.pw_check_tor_date,
            pt.wb_check_tor_date,
            pt.ww_check_tor_date,
            pt.approve_tor_date,
            pt.set_tor_date,
            pt.tor_published_date,
            pt.announce_date,
            pt.bid_submission_due_date,
            pt.bid_submission_actual_date,
            pt.bidder_count,
            pt.evaluate_bids_date,
            pt.receive_price_date,
            pt.bid_result_status,
            pt.bid_result_amount,
            pt.winner_type,
            pt.winner_name,
            pt.appeal_end_date,
            pt.has_appellant,
            pt.price_received_date,
            pt.expected_signing_date,
            pt.contract_no,
            pt.contract_start_date,
            pt.contract_end_date,
            pt.is_contract_extended,
            pt.contract_extended_date,
            pt.contract_extended_remark,
            pt.contract_extended_approve_doc_no,
            pt.contract_extended_approve_date,
            pt.contract_value,
            pt.contractor_type,
            pt.contractor_name,
            pt.remark AS pt_remark,

            wb.design_by,
            wb.designer_name,
            wb.design_status,
            wb.core_ftp_design,
            wb.remark,
            wb.core_upload_date AS wb_core_upload_date

        FROM import_plan p

        LEFT JOIN plan_status_tracking t
            ON p.id = t.plan_id

        LEFT JOIN procurement_tracking pt
            ON p.id = pt.plan_id

        LEFT JOIN wb_plan_details wb
            ON p.id = wb.import_plan_id
    ";


    $conditions = array();
    $params = array();


    // ==========================================
    // กรองเฉพาะข้อมูลของแขวงตัวเอง
    // ==========================================

    if (
        $department !== 'ไม่ระบุ'
        && $department !== 'Admin'
        && $department !== 'ส่วนกลาง'
        && $department !== 'IT'
        && $department !== 'วผ.'
    ) {

        $clean_dept = str_replace(
            ['แขวงทางหลวง', 'แขวง', 'ขท.'],
            '',
            $department
        );

        $clean_dept = trim($clean_dept);

        $clean_dept = str_replace(
            ' ',
            '%',
            $clean_dept
        );

        $conditions[] =
            "p.highway_district LIKE :user_district";

        $params[':user_district'] =
            "%" . $clean_dept . "%";
    }


    // ==========================================
    // ค้นหา ID CODE
    // ==========================================

    if ($search_id_code !== '') {

        $conditions[] =
            "p.id_code LIKE :id_code";

        $params[':id_code'] =
            "%" . $search_id_code . "%";
    }


    // ==========================================
    // ⭐ กรองปีงบประมาณ
    // ==========================================

    if ($search_budget_year !== '') {

        $conditions[] =
            "p.budget_year LIKE :budget_year";

        $params[':budget_year'] =
            "%" . $search_budget_year . "%";
    }
    // ==========================================
    // สำนักฯ
    // ==========================================
if ($search_bureau !== '') {

    switch ($search_bureau) {

        case 'สร':
            $conditions[] = "p.bureau = 'สร.'";
            break;

        case 'สร_อาคาร':
            $conditions[] = "p.bureau = 'สร.(งานอาคาร)'";
            break;

        case 'สผ':
            $conditions[] = "p.bureau = 'สผ.'";
            break;

        case 'สป':
            $conditions[] = "p.bureau = 'สป.'";
            break;
    }
}
    // ==========================================
    // บัญชีแผนงาน
    // ==========================================

    if ($search_pro_account !== '') {

        $conditions[] =
            "p.pro_account LIKE :pro_account";

        $params[':pro_account'] =
            "%" . $search_pro_account . "%";
    }


    // ==========================================
    // แขวงทางหลวง
    // ==========================================

    if ($search_highway_district !== '') {

        $conditions[] =
            "p.highway_district LIKE :highway_district";

        $params[':highway_district'] =
            "%" . $search_highway_district . "%";
    }


    // ==========================================
    // รหัสงาน
    // ==========================================

    if ($search_job_code !== '') {

        $conditions[] =
            "p.job_code LIKE :job_code";

        $params[':job_code'] =
            "%" . $search_job_code . "%";
    }


    // ==========================================
    // ทางหลวงหมายเลข
    // ==========================================

    if ($search_highway_number !== '') {

        $conditions[] =
            "p.highway_number LIKE :highway_number";

        $params[':highway_number'] =
            "%" . $search_highway_number . "%";
    }


    // ==========================================
    // ชื่อตอน
    // ==========================================

    if ($search_section_name !== '') {

        $conditions[] =
            "p.section_name LIKE :section_name";

        $params[':section_name'] =
            "%" . $search_section_name . "%";
    }


    // ==========================================
    // งานอำนาจ
    // ==========================================

    if ($search_auth_work_type !== '') {

        $conditions[] =
            "t.auth_work_type LIKE :auth_work_type";

        $params[':auth_work_type'] =
            "%" . $search_auth_work_type . "%";
    }


    // ==========================================
    // WHERE
    // ==========================================

    if (count($conditions) > 0) {

        $sql .=
            " WHERE "
            . implode(' AND ', $conditions);
    }


    // ==========================================
    // ORDER BY
    // ==========================================

    $sql .= "
        ORDER BY

        CASE
            WHEN p.bureau LIKE '%สผ%' THEN 1
            WHEN p.bureau LIKE '%สร%' THEN 2
            WHEN p.bureau LIKE '%สป%' THEN 3
            ELSE 4
        END ASC,

        p.id DESC
    ";


    // ==========================================
    // Execute
    // ==========================================

    $stmt = $pdo->prepare($sql);

    $stmt->execute($params);

    $import_plans =
        $stmt->fetchAll(PDO::FETCH_ASSOC);


} catch (PDOException $e) {

    $error_msg =
        "เกิดข้อผิดพลาดฐานข้อมูล: "
        . $e->getMessage();
}

?>


<!DOCTYPE html>

<html lang="th">

<head>

<meta charset="UTF-8">

<meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
>

<title>
ระบบติดตามสถานะแผน สทล.5
</title>


<link
    href="https://fonts.googleapis.com/css2?family=Prompt:wght@300;400;500;600&display=swap"
    rel="stylesheet"
>


<style>

/* ==========================================
   BODY
========================================== */

body {

    font-family: 'Prompt', sans-serif;

    background-color: #f0f4f8;

    color: #333;

    margin: 0;

    padding: 20px;
}


/* ==========================================
   CONTAINER
========================================== */

.container {

    width: 100%;

    max-width: 1800px;

    margin: auto;

    background: #ffffff;

    padding: 30px 40px;

    border-radius: 12px;

    box-shadow:
        0 8px 24px rgba(0,0,0,0.05);
}


/* ==========================================
   HEADER
========================================== */

.header-main {

    display: flex;

    justify-content: space-between;

    align-items: center;

    background-color: #f8fafc;

    border: 1px solid #e2e8f0;

    padding: 15px 25px;

    border-radius: 10px;

    margin-bottom: 20px;
}


.brand {

    display: flex;

    align-items: center;

    gap: 15px;
}


.brand img {

    width: 55px;

    height: 55px;

    object-fit: contain;
}


.brand h1 {

    margin: 0;

    font-size: 24px;

    color: #1e293b;

    font-weight: 600;
}


.user-panel {

    display: flex;

    align-items: center;

    gap: 20px;

    font-size: 14px;

    color: #475569;
}


.user-panel span {

    font-weight: 600;

    color: #0f172a;
}


.btn-logout {

    background-color: #ef4444;

    color: #ffffff;

    text-decoration: none;

    padding: 8px 16px;

    border-radius: 6px;

    font-weight: 500;

    transition: background 0.2s;
}


.btn-logout:hover {

    background-color: #dc2626;
}


/* ==========================================
   NAV
========================================== */

.nav-menu {

    display: flex;

    gap: 10px;

    margin-bottom: 25px;

    border-bottom: 2px solid #e2e8f0;

    padding-bottom: 15px;
}


.nav-link {

    text-decoration: none;

    padding: 10px 20px;

    border-radius: 8px;

    font-weight: 500;

    color: #64748b;

    background-color: #f1f5f9;

    transition: all 0.2s;
}


.nav-link:hover {

    background-color: #e2e8f0;
}


.nav-link.active {

    background-color: #3b82f6;

    color: #ffffff;
}


.nav-link.upload {

    background-color: #10b981;

    color: white;

    margin-left: auto;
}


.nav-link.upload:hover {

    background-color: #059669;
}


/* ==========================================
   SEARCH
========================================== */

.search-box {

    background-color: #f8fafc;

    border: 1px solid #e2e8f0;

    padding: 20px;

    border-radius: 8px;

    margin-bottom: 25px;
}


.search-grid {

    display: grid;

    grid-template-columns:
        repeat(auto-fit, minmax(180px, 1fr));

    gap: 15px;

    margin-bottom: 15px;
}


.search-group {

    display: flex;

    flex-direction: column;
}


.search-group label {

    font-size: 13px;

    color: #475569;

    margin-bottom: 5px;
}


.search-group input,
.search-group select {

    padding: 8px 12px;

    border: 1px solid #cbd5e1;

    border-radius: 4px;

    font-family: inherit;

    background-color: #fff;

    width: 100%;

    box-sizing: border-box;
}


.search-actions {

    display: flex;

    gap: 10px;

    align-items: center;

    margin-top: 10px;
}


.btn-search {

    background-color: #3b82f6;

    color: white;

    border: none;

    padding: 9px 20px;

    border-radius: 6px;

    cursor: pointer;
}


.btn-clear {

    color: #64748b;

    text-decoration: none;

    font-size: 14px;

    margin-right: 15px;
}


.btn-excel {

    background-color: #10b981;

    color: white;

    border: none;

    padding: 9px 20px;

    border-radius: 6px;

    cursor: pointer;
}


.btn-manage {

    background-color: #f59e0b;

    color: #fff;

    padding: 6px 12px;

    font-size: 13px;

    text-decoration: none;

    border-radius: 6px;
}


/* ==========================================
   TABLE
========================================== */

.table-responsive {

    overflow-x: auto;

    overflow-y: auto;

    max-height: 700px;

    border: 1px solid #000;

    position: relative;

    -webkit-overflow-scrolling: touch;

    scrollbar-width: auto;

    scrollbar-color:
        #64748b
        #e2e8f0;
}


.table-responsive::-webkit-scrollbar {

    width: 14px;

    height: 18px;
}


.table-responsive::-webkit-scrollbar-track {

    background: #e2e8f0;
}


.table-responsive::-webkit-scrollbar-thumb {

    background: #64748b;

    border-radius: 10px;

    border: 3px solid #e2e8f0;
}


table {

    width: max-content;

    min-width: 100%;

    border-collapse: separate;

    border-spacing: 0;

    font-size: 12px;
}


th,
td {

    padding: 5px 7px;

    border: 1px solid #000;

    text-align: center;

    vertical-align: middle;
}


th {

    position: sticky;

    top: 0;

    z-index: 10;

    font-weight: 600;

    color: #000;

    white-space: normal;

    line-height: 1.25;

    min-width: 58px;

    max-width: 125px;

    word-break: break-word;
}


td {

    white-space: nowrap;
}


/* ==========================================
   TABLE COLORS
========================================== */

.th-gray {

    background-color:
        #e5e7eb !important;
}


.th-lightgreen {

    background-color:
        #bdf285 !important;
}


.th-lightpink {

    background-color:
        #ffe6f9 !important;
}


.th-green {

    background-color:
        #a9d08e !important;
}


.th-blue {

    background-color:
        #0070c0 !important;

    color: #fff !important;
}


.th-purple {

    background-color:
        #d100ff !important;

    color: #000 !important;
}


.th-pink {

    background-color:
        #ffb3ff !important;
}


.text-red {

    color: #ff0000 !important;

    font-weight: bold;
}


.btn-save-qr {

    margin-top: 5px;

    font-size: 11px;

    padding: 4px 8px;

    background-color: #3b82f6;

    color: #fff;

    border: none;

    border-radius: 4px;

    cursor: pointer;
}


tbody tr:hover {

    background: #f8fafc;
}


.truncate {
    max-width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* ลักษณะงานโดยสังเขป: แสดงหลายบรรทัดและไม่ตัดข้อความ */
td.description-cell {
    white-space: normal !important;
    overflow: visible !important;
    text-overflow: clip !important;
    overflow-wrap: anywhere !important;
    word-break: normal !important;
    min-width: 240px !important;
    width: 300px;
    max-width: 340px !important;
    line-height: 1.6;
    vertical-align: top !important;
    padding: 8px 10px !important;
}


.loading-text {

    color: #3b82f6;

    font-size: 16px;

    font-weight: 500;

    padding: 40px;

    text-align: center;
}


.wrap-km {

    white-space: normal !important;

    min-width: 75px !important;

    max-width: 105px !important;

    word-wrap: break-word;

    line-height: 1.35;
}


.wrap-section-name {

    white-space: normal !important;

    min-width: 65px !important;

    max-width: 100px !important;

    word-wrap: break-word;

    line-height: 1.35;
}




/* ==========================================
   FLOATING HORIZONTAL SCROLLBAR
   Scrollbar ลอยตามตารางขณะเลื่อนขึ้น/ลง
========================================== */

.floating-scrollbar {
    position: fixed;
    left: 15px;
    right: 30px;
    bottom: 8px;
    height: 24px;
    overflow-x: auto;
    overflow-y: hidden;
    z-index: 99999;
    background: #e2e8f0;
    border: 1px solid #94a3b8;
    border-radius: 14px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    display: none;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: auto;
    scrollbar-color: #64748b #e2e8f0;
}

.floating-scrollbar-inner {
    height: 1px;
}

.floating-scrollbar::-webkit-scrollbar {
    height: 18px;
}

.floating-scrollbar::-webkit-scrollbar-track {
    background: #e2e8f0;
    border-radius: 10px;
}

.floating-scrollbar::-webkit-scrollbar-thumb {
    background: #64748b;
    border-radius: 10px;
    border: 3px solid #e2e8f0;
}

@media (max-width:768px) {
    .floating-scrollbar {
        left: 5px;
        right: 5px;
        bottom: 5px;
        height: 22px;
    }
}

/* ==========================================
   STICKY COLUMN
========================================== */

.sticky-col {

    position: sticky !important;

    background: #fff;

    z-index: 5;
}


th.sticky-col {

    z-index: 20 !important;

    background: #e5e7eb !important;
}


tbody tr:hover td.sticky-col {

    background: #f8fafc;
}


.sticky-last {

    border-right:
        2px solid #000 !important;
}


/* ==========================================
   DESKTOP
========================================== */

@media (min-width:1025px) {

    .table-responsive {

        max-height:
            calc(100vh - 260px);
    }
}


/* ==========================================
   TABLET
========================================== */

@media (min-width:769px)
and (max-width:1024px) {

    body {

        padding: 10px;
    }


    .container {

        padding: 15px;
    }


    .table-responsive {

        max-height:
            calc(100vh - 240px);
    }


    th,
    td {

        padding: 5px 6px;

        font-size: 11px;
    }


    th {

        min-width: 52px;

        max-width: 105px;
    }
}


/* ==========================================
   MOBILE
========================================== */

@media (max-width:768px) {

    body {

        padding: 6px;
    }


    .container {

        padding: 8px;

        border-radius: 8px;
    }


    .header-main {

        flex-direction: column;

        align-items: flex-start;

        gap: 10px;

        padding: 10px;
    }


    .brand h1 {

        font-size: 17px;
    }


    .brand img {

        width: 40px;

        height: 40px;
    }


    .user-panel {

        width: 100%;

        flex-wrap: wrap;

        gap: 8px;

        font-size: 11px;
    }


    .nav-menu {

        overflow-x: auto;

        flex-wrap: nowrap;

        padding-bottom: 8px;

        margin-bottom: 12px;
    }


    .nav-link {

        white-space: nowrap;

        padding: 8px 12px;

        font-size: 12px;
    }


    .search-box {

        padding: 10px;

        margin-bottom: 12px;
    }


    .search-grid {

        grid-template-columns:
            1fr 1fr;

        gap: 8px;
    }


    .search-group label {

        font-size: 11px;
    }


    .search-group input,
    .search-group select {

        padding: 7px 8px;

        font-size: 12px;
    }


    .table-responsive {

        max-height:
            calc(100vh - 270px);

        width: 100%;

        overflow-x: auto;

        overflow-y: auto;

        touch-action: pan-x pan-y;
    }


    table {

        font-size: 11px;
    }


    th {

        font-size: 10px;

        min-width: 48px;

        max-width: 90px;

        padding: 4px 5px;
    }


    td {

        padding: 5px 6px;
    }


    .sticky-col {

        position: static !important;

        left: auto !important;
    }


    th.sticky-col {

        position: sticky !important;

        top: 0;

        z-index: 10 !important;
    }


    .sticky-last {

        border-right:
            1px solid #000 !important;
    }
}


/* ==========================================
   ซ่อนคอลัมน์บนหน้าเว็บ
========================================== */

.hide-col {

    display: none !important;
}

</style>

</head>


<body>


<div class="container">


<!-- ==========================================
     HEADER
========================================== -->

<div class="header-main">

    <div class="brand">

        <img
            src="http://www.itooh5.synology.me/joomla/highways_plan/image/S__3375147.png"
            alt="โลโก้ สทล.5"
        >

        <h1>
            ระบบติดตามสถานะแผน สทล.5
        </h1>

    </div>


    <div class="user-panel">

        <div>

            ผู้ใช้งาน:
            <span>
                <?php
                echo htmlspecialchars($full_name);
                ?>
            </span>

            |

            สังกัด:
            <span>
                <?php
                echo htmlspecialchars($department);
                ?>
            </span>

        </div>


        <a
            href="logout.php"
            class="btn-logout"
        >
            ออกจากระบบ
        </a>

    </div>

</div>


<!-- ==========================================
     NAVIGATION
========================================== -->
<div class="nav-menu">

    <a href="index.php" class="nav-link active">หน้าหลัก</a>
    <a href="tracking.php" class="nav-link">ติดตาสถานะแผน</a>
    <a href="summary.php" class="nav-link">ติดตามจัดซื้อจัดจ้าง</a>
  <!--  <a href="summary_progress.php" class="nav-link">ติดตามจัดซื้อจัดจ้าง</a>  -->
    <a href="designer_das.php" class="nav-link">ติดตามสถานะแบบ</a>
    <a href="import.php" class="nav-link upload">+ อัปโหลดไฟล์ CSV</a>
</div>
<!-- ==========================================
     SEARCH BOX
========================================== -->
<div class="search-box">
<form
    method="GET"
    action=""
>
<div class="search-grid">
<!-- ID CODE -->
<div class="search-group">
    <label>
        ID CODE
    </label>
    <input
        type="text"
        name="search_id_code"
        value="<?php
            echo htmlspecialchars(
                $search_id_code
            );
        ?>"
        autocomplete="off"
    >

</div>


<!-- ⭐ ปีงบประมาณ -->

<div class="search-group">

    <label>
        ปีงบประมาณ
    </label>

    <select name="search_budget_year">

        <option value="">
            -- ทั้งหมด --
        </option>


        <?php foreach ($budget_years as $b_year): ?>

            <option
                value="<?php
                    echo htmlspecialchars($b_year);
                ?>"
                <?php

                if (
                    (string)$search_budget_year
                    ===
                    (string)$b_year
                ) {

                    echo 'selected';
                }

                ?>
            >

                <?php
                echo htmlspecialchars($b_year);
                ?>

            </option>

        <?php endforeach; ?>

    </select>

</div>


<!-- สำนักฯ -->

<div class="search-group">

    <label>
        สำนักฯ
    </label>

    <select name="search_bureau" id="search_bureau">

        <option value=""
            <?php echo ($search_bureau === '') ? 'selected' : ''; ?>
        >
            -- ทั้งหมด --
        </option>

        <option value="สร"
            <?php echo ($search_bureau === 'สร') ? 'selected' : ''; ?>
        >
            สร.
        </option>

        <option value="สผ"
            <?php echo ($search_bureau === 'สผ') ? 'selected' : ''; ?>
        >
            สผ.
        </option>

        <option value="สป"
            <?php echo ($search_bureau === 'สป') ? 'selected' : ''; ?>
        >
            สป.
        </option>

        <option value="สร_อาคาร"
            <?php echo ($search_bureau === 'สร_อาคาร') ? 'selected' : ''; ?>
        >
            สร.(งานอาคาร)
        </option>

    </select>

</div>


<!-- บัญชีแผนงาน -->

<div class="search-group">

    <label>
        บัญชีแผนงาน
    </label>

    <select name="search_pro_account" id="search_pro_account">

        <option value=""
            <?php echo ($search_pro_account === '') ? 'selected' : ''; ?>
        >
            -- ทั้งหมด --
        </option>

        <option value="รายการตาม พ.ร.บ."
            <?php echo ($search_pro_account === 'รายการตาม พ.ร.บ.') ? 'selected' : ''; ?>
        >
            รายการตาม พ.ร.บ.
        </option>

        <option value="งบจังหวัด/กลุ่มจังหวัด"
            <?php echo ($search_pro_account === 'งบจังหวัด/กลุ่มจังหวัด') ? 'selected' : ''; ?>
        >
            งบจังหวัด/กลุ่มจังหวัด
        </option>

        <option value="งบกลางฯ"
            <?php echo ($search_pro_account === 'งบกลางฯ') ? 'selected' : ''; ?>
        >
            งบกลางฯ
        </option>

    </select>

</div>


<!-- แขวงทางหลวง -->

<div class="search-group">

    <label>
        แขวงทางหลวง
    </label>

    <select name="search_highway_district">

        <option value="">
            -- ทั้งหมด --
        </option>
        <option
            value="สทล.5"
            <?php
            if (
                $search_highway_district
                ==
                'สทล.5'
            ) echo 'selected';
            ?>
        >
            สทล.5
        </option>
        <option
            value="พิษณุโลกที่ 1"
            <?php
            if (
                $search_highway_district
                ==
                'พิษณุโลกที่ 1'
            ) echo 'selected';
            ?>
        >
            พิษณุโลกที่ 1
        </option>


        <option
            value="พิษณุโลกที่ 2"
            <?php
            if (
                $search_highway_district
                ==
                'พิษณุโลกที่ 2'
            ) echo 'selected';
            ?>
        >
            พิษณุโลกที่ 2 (วังทอง)
        </option>


        <option
            value="พิจิตร"
            <?php
            if (
                $search_highway_district
                ==
                'พิจิตร'
            ) echo 'selected';
            ?>
        >
            พิจิตร
        </option>


        <option
            value="อุตรดิตถ์ที่ 1"
            <?php
            if (
                $search_highway_district
                ==
                'อุตรดิตถ์ที่ 1'
            ) echo 'selected';
            ?>
        >
            อุตรดิตถ์ที่ 1
        </option>


        <option
            value="อุตรดิตถ์ที่ 2"
            <?php
            if (
                $search_highway_district
                ==
                'อุตรดิตถ์ที่ 2'
            ) echo 'selected';
            ?>
        >
            อุตรดิตถ์ที่ 2
        </option>

    </select>

</div>


<!-- รหัสงาน -->

<div class="search-group">

    <label>
        รหัสงาน
    </label>

    <input
        type="text"
        name="search_job_code"
        value="<?php
            echo htmlspecialchars(
                $search_job_code
            );
        ?>"
        autocomplete="off"
    >

</div>


<!-- ทางหลวงหมายเลข -->

<div class="search-group">

    <label>
        ทางหลวงหมายเลข
    </label>

    <input
        type="text"
        name="search_highway_number"
        value="<?php
            echo htmlspecialchars(
                $search_highway_number
            );
        ?>"
        autocomplete="off"
    >

</div>


<!-- ชื่อตอน -->

<div class="search-group">

    <label>
        ชื่อตอน
    </label>

    <input
        type="text"
        name="search_section_name"
        value="<?php
            echo htmlspecialchars(
                $search_section_name
            );
        ?>"
        autocomplete="off"
    >

</div>


<!-- งานอำนาจ -->

<div class="search-group">

    <label>
        งานอำนาจ (เขต/แขวง)
    </label>

    <select name="search_auth_work_type">

        <option value="">
            -- ทั้งหมด --
        </option>


        <option
            value="เขต"
            <?php
            if (
                $search_auth_work_type
                ==
                'เขต'
            ) echo 'selected';
            ?>
        >
            เขต
        </option>


        <option
            value="แขวง"
            <?php
            if (
                $search_auth_work_type
                ==
                'แขวง'
            ) echo 'selected';
            ?>
        >
            แขวง
        </option>

    </select>

</div>


</div>


<!-- ==========================================
     SEARCH ACTIONS
========================================== -->

<div class="search-actions">

    <button
        type="submit"
        class="btn-search"
        style="display:none;"
    >
        ค้นหา
    </button>


    <a
        href="index.php"
        class="btn-clear"
    >
        ล้างค่า
    </a>


    <button
        type="button"
        class="btn-excel"
        onclick="
            exportTableToExcel(
                'planTable',
                'Plan_Data',
                true
            )
        "
    >
        โหลด Excel
    </button>

</div>


</form>

</div>

<!-- เพิ่มส่วนแสดงผลจำนวนรายการทั้งหมดตรงนี้ -->
<div style="display: flex; justify-content: flex-end; align-items: center; margin-bottom: 10px; font-size: 15px; font-weight: 600; color: #1e293b;">
    พบข้อมูลทั้งหมด: <span id="total-count" style="color: #ef4444; font-size: 18px; margin: 0 5px;"><?php echo count($import_plans); ?></span> รายการ
</div>

<!-- ==========================================
     TABLE
========================================== -->

<div class="table-responsive">

<table id="planTable">


<thead>

<tr>

<th class="th-gray">
    ลำดับ
</th>

<th class="th-gray">
    จัดการ
</th>

<th class="th-gray">
    ID CODE
</th>

<th class="th-gray text-red hide-col">
    QR Code
</th>

<th class="th-gray">
    สำนักฯ
</th>

<th class="th-gray">
    ปีงบประมาณ
</th>

<th class="th-gray">
    บัญชีแผนงาน
</th>

<th class="th-gray">
    แขวงทางหลวง
</th>

<th class="th-gray">
    รหัสงาน
</th>

<th class="th-gray">
    ทางหลวงหมายเลข
</th>

<th class="th-gray">
    ตอนควบคุม
</th>

<th class="th-gray wrap-section-name">
    ชื่อตอน
</th>

<th class="th-gray wrap-km">
    ช่วง กม.-กม.<br>
    ตาม List.
</th>

<th class="th-gray">
    วงเงิน ตาม List (บาท)
</th>


<th class="th-lightgreen wrap-km">
    ช่วง กม. - กม.<br>
    ตามเล่มแผน
</th>

<th class="th-lightgreen">
    วงเงิน ตามเล่มแผน (บาท)
</th>

<th class="th-lightgreen">
    ลักษณะงานโดยสังเขป
</th>

<th class="th-lightgreen">
    สถานะ
</th>

<th class="th-lightgreen">
    วันทำการ
</th>

<th class="th-lightgreen">
    ปริมาณงาน
</th>

<th class="th-lightgreen">
    หน่วย
</th>

<th class="th-lightgreen">
    ชนิดผิวทาง
</th>

<th class="th-lightgreen">
    ค่าธรรมเนียมการไฟฟ้า
</th>


<th class="th-lightpink">
    หมายเหตุ
</th>


<th class="th-green">
    เลขหนังสือแขวงฯส่งแผน
</th>

<th class="th-green">
    ส่งวบ.ตรวจสอบแผน
</th>

<th class="th-green">
    รับจากวบ.ตรวจสอบ
</th>

<th class="th-green">
    วันที่แขวงฯ ส่งแผน
</th>

<th class="th-green">
    วผ.ผ่านแผน เลขหนังสือ
</th>

<th class="th-green">
    วผ.ผ่านแผน ลงวันที่
</th>

<th class="th-green">
    ผส.อนุมัติแผน เลขหนังสือ
</th>

<th class="th-green">
    ผส.อนุมัติแผน ลงวันที่
</th>

<th class="th-green">
    ส่วนกลางเห็นชอบแผน เลขหนังสือ
</th>

<th class="th-green">
    ส่วนกลางเห็นชอบแผน วันที่
</th>

<th class="th-green">
    ลงไฟล์ CORE FTP
</th>

<th class="th-green">
    วันที่ลงไฟล์ CORE
</th>

<th class="th-green">
    ผู้คิดราคากลาง
</th>

<th class="th-green">
    เขต/แขวง ส่ง (ราคากลาง)
</th>

<th class="th-green">
    ออกราคากลางวันที่
</th>

<th class="th-green">
    ราคากลาง (บาท)
</th>

<th class="th-green">
    อนุมัติราคากลางวันที่
</th>

<th class="th-green">
    สถานะราคากลาง
</th>


<th class="th-blue">
    ทำแบบโดย เขต/แขวง
</th>

<th class="th-blue">
    ชื่อผู้ออกแบบ
</th>

<th class="th-blue">
    สถานะแบบ
</th>

<th class="th-blue">
    ลงแบบใน CORE FTP
</th>

<th class="th-blue">
    วันที่ลงแบบใน CORE FTP
</th>

<th class="th-blue">
    หมายเหตุวบ.
</th>

<th class="th-green">
    งานอำนาจ เขต/แขวง
</th>

<th class="th-green text-red">
    ออกประกาศโดย เขต/แขวง
</th>

<th class="th-green text-red">
    TOR ร่างโดย เขต/แขวงฯ
</th>


<th class="th-purple">
    แขวงฯ ส่ง TOR ให้พัสดุเขต (วันที่)
</th>

<th class="th-purple">
    วผ. ตรวจร่าง TOR แล้ววันที่
</th>

<th class="th-purple">
    วบ. ตรวจร่าง TOR แล้ววันที่
</th>

<th class="th-purple">
    วว. ตรวจร่าง TOR แล้ววันที่
</th>

<th class="th-purple">
    อนุมัติร่าง TOR วันที่
</th>

<th class="th-purple">
    กำหนดลง TOR วันที่ (คาดการณ์)
</th>

<th class="th-purple">
    ลง TOR แล้ว วันที่
</th>

<th class="th-purple">
    ออกประกาศวันที่ / ออกหนังสือเชิญชวน
</th>

<th class="th-purple">
    กำหนดเสนอราคาวันที่ (คาดการณ์)
</th>

<th class="th-purple">
    เสนอราคาแล้ว (วันที่)
</th>

<th class="th-purple">
    จำนวนผู้ยื่นเสนอราคา
</th>

<th class="th-purple">
    พิจารณาผล
</th>

<th class="th-purple">
    วันที่รับราคา (อนุมัติรับราคา)
</th>

<th class="th-purple">
    ประกาศผลประกวดราคา
</th>

<th class="th-purple">
    ผลประกวดราคา (บาท)
</th>

<th class="th-purple">
    ผู้ชนะการประกวดราคา (หจก./บจก./อื่นๆ)
</th>

<th class="th-purple">
    ชื่อผู้ชนะการประกวดราคา (ใส่เฉพาะชื่อ)
</th>

<th class="th-purple">
    สิ้นสุดอุทธรณ์วันที่
</th>

<th class="th-purple">
    มี/ไม่มี ผู้อุทธรณ์
</th>

<th class="th-purple">
    วันที่ได้รับเงินงวด
</th>

<th class="th-purple">
    วันที่คาดการณ์ลงนามสัญญา
</th>

<th class="th-purple">
    สัญญาเลขที่
</th>

<th class="th-purple">
    ลงนามในสัญญา (วันที่)
</th>

<th class="th-purple">
    วันเริ่มต้นสัญญา
</th>

<th class="th-purple">
    วันสิ้นสุดสัญญา
</th>

<th class="th-purple">
    ค่างานตามสัญญา (บาท)
</th>

<th class="th-purple">
    ผู้รับจ้าง (หจก./บจก./อื่นๆ)
</th>

<th class="th-purple">
    ชื่อผู้รับจ้าง
</th>

<th class="th-pink text-red">
    หมายเหตุ-3
</th>

<th class="th-purple">
    มีการขยายสัญญา
</th>

<th class="th-purple">
    เลขหนังสือ อนุมัติขยายอายุสัญญา
</th>

<th class="th-purple">
    วันที่อนุมัติขยายอายุสัญญา
</th>

<th class="th-purple">
    วันที่ขยายสัญญา (ใหม่)
</th>

<th class="th-purple">
    หมายเหตุแก้ไขอายุสัญญา
</th>

</tr>

</thead>


<tbody>


<?php if (count($import_plans) > 0): ?>


<?php

$counter = 1;

foreach ($import_plans as $row):

?>


<tr>


<td>
    <?php
    echo $counter++;
    ?>
</td>


<td>

<a
    href="manage.php?id=<?php
        echo $row['id'];
    ?>"
    class="btn-manage"
>
    แก้ไข
</a>

</td>


<td>

<strong>

<?php

echo isset($row['id_code'])
    ? htmlspecialchars(
        $row['id_code']
      )
    : '-';

?>

</strong>

</td>


<td class="hide-col">

<?php

if (
    !empty($row['id_code'])
    &&
    trim($row['id_code']) !== '-'
):


$detail_url =
    "http://"
    . $_SERVER['HTTP_HOST']
    . rtrim(
        dirname($_SERVER['PHP_SELF']),
        '/\\'
      )
    . "/view.php?id="
    . $row['id'];


$qr_url =
    "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data="
    . urlencode($detail_url);


$filename =
    "QR_"
    . preg_replace(
        '/[^a-zA-Z0-9_-]/',
        '_',
        $row['id_code']
      )
    . ".png";

?>


<div
    style="
        display:flex;
        flex-direction:column;
        align-items:center;
        gap:4px;
    "
>


<a
    href="<?php
        echo htmlspecialchars($detail_url);
    ?>"
    target="_blank"
>

<img
    src="<?php
        echo $qr_url;
    ?>"
    alt="QR"
    style="
        width:45px;
        height:45px;
        display:block;
    "
>

</a>


<button
    type="button"
    class="btn-save-qr"
    onclick="
        downloadQRCode(
            '<?php echo $qr_url; ?>',
            '<?php echo $filename; ?>'
        )
    "
>
    Save QR
</button>


</div>


<?php else: ?>

    -

<?php endif; ?>

</td>


<td>
<?php
echo isset($row['bureau'])
    ? htmlspecialchars($row['bureau'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['budget_year'])
    ? htmlspecialchars($row['budget_year'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['pro_account'])
    ? htmlspecialchars($row['pro_account'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['highway_district'])
    ? htmlspecialchars($row['highway_district'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['job_code'])
    ? htmlspecialchars($row['job_code'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['highway_number'])
    ? htmlspecialchars($row['highway_number'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['control_section'])
    ? htmlspecialchars($row['control_section'])
    : '-';
?>
</td>


<td class="wrap-section-name">
<?php
echo isset($row['section_name'])
    ? htmlspecialchars($row['section_name'])
    : '-';
?>
</td>


<td class="wrap-km">
<?php
echo isset($row['km_range'])
    ? htmlspecialchars($row['km_range'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['budget_list'])
    ? htmlspecialchars($row['budget_list'])
    : '-';
?>
</td>


<td class="wrap-km">
<?php
echo isset($row['plan_km_range'])
    ? htmlspecialchars($row['plan_km_range'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['budget'])
    ? htmlspecialchars($row['budget'])
    : '-';
?>
</td>


<td class="description-cell">
<?php
echo isset($row['job_description'])
    && trim((string)$row['job_description']) !== ''
    ? nl2br(htmlspecialchars(
        (string)$row['job_description'],
        ENT_QUOTES,
        'UTF-8'
      ))
    : '-';
?>
</td>


<td>
<?php
echo isset($row['status'])
    ? htmlspecialchars($row['status'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['working_days'])
    ? htmlspecialchars($row['working_days'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['work_qty'])
    ? htmlspecialchars($row['work_qty'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['unit'])
    ? htmlspecialchars($row['unit'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['surface_type'])
    ? htmlspecialchars($row['surface_type'])
    : '-';
?>
</td>


<td>
<?php
echo isset($row['electricity_fee'])
    ? htmlspecialchars($row['electricity_fee'])
    : '-';
?>
</td>


<td class="truncate">
<?php
echo isset($row['remark'])
    ? htmlspecialchars($row['remark'])
    : '-';
?>
</td>


<!-- ==========================================
     GREEN AREA
========================================== -->


<td>
<?php
echo isset($row['branch_send_doc_no'])
    ? htmlspecialchars(
        $row['branch_send_doc_no']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['sent_to_wb_date'])
    &&
    $row['sent_to_wb_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['sent_to_wb_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['received_from_wb_date'])
    &&
    $row['received_from_wb_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['received_from_wb_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['branch_send_date'])
    &&
    $row['branch_send_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['branch_send_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['wp_pass_doc_no'])
    ? htmlspecialchars(
        $row['wp_pass_doc_no']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['wp_pass_date'])
    &&
    $row['wp_pass_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['wp_pass_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['dir_approve_doc_no'])
    ? htmlspecialchars(
        $row['dir_approve_doc_no']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['dir_approve_date'])
    &&
    $row['dir_approve_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['dir_approve_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['central_approve_doc_no'])
    ? htmlspecialchars(
        $row['central_approve_doc_no']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['central_approve_date'])
    &&
    $row['central_approve_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['central_approve_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['core_ftp_plan'])
    ? htmlspecialchars(
        $row['core_ftp_plan']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['core_upload_date'])
    &&
    $row['core_upload_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['core_upload_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['estimator_name'])
    ? htmlspecialchars(
        $row['estimator_name']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['branch_send_median_doc'])
    ? htmlspecialchars(
        $row['branch_send_median_doc']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['issue_median_date'])
    &&
    $row['issue_median_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['issue_median_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['median_price'])
    ? htmlspecialchars(
        $row['median_price']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['approve_median_date'])
    &&
    $row['approve_median_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['approve_median_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['is_median_approved'])
    ? htmlspecialchars(
        $row['is_median_approved']
      )
    : '-';
?>
</td>


<!-- ==========================================
     BLUE AREA
========================================== -->


<td>
<?php
echo isset($row['design_by'])
    ? htmlspecialchars(
        $row['design_by']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['designer_name'])
    ? htmlspecialchars(
        $row['designer_name']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['design_status'])
    ? htmlspecialchars(
        $row['design_status']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['core_ftp_design'])
    ? htmlspecialchars(
        $row['core_ftp_design']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['wb_core_upload_date'])
    &&
    $row['wb_core_upload_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['wb_core_upload_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['remark'])
    ? htmlspecialchars(
        $row['remark']
      )
    : '-';
?>
</td>


<!-- ==========================================
     GREEN AREA 2
========================================== -->


<td>
<?php
echo isset($row['auth_work_type'])
    ? htmlspecialchars(
        $row['auth_work_type']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['announce_by'])
    ? htmlspecialchars(
        $row['announce_by']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['tor_drafted_by'])
    ? htmlspecialchars(
        $row['tor_drafted_by']
      )
    : '-';
?>
</td>


<!-- ==========================================
     PROCUREMENT
========================================== -->


<td>
<?php
echo !empty($row['district_send_tor_date'])
    &&
    $row['district_send_tor_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['district_send_tor_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['pw_check_tor_date'])
    &&
    $row['pw_check_tor_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['pw_check_tor_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['wb_check_tor_date'])
    &&
    $row['wb_check_tor_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['wb_check_tor_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['ww_check_tor_date'])
    &&
    $row['ww_check_tor_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['ww_check_tor_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['approve_tor_date'])
    &&
    $row['approve_tor_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['approve_tor_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['set_tor_date'])
    &&
    $row['set_tor_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['set_tor_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['tor_published_date'])
    &&
    $row['tor_published_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['tor_published_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['announce_date'])
    &&
    $row['announce_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['announce_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['bid_submission_due_date'])
    &&
    $row['bid_submission_due_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['bid_submission_due_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['bid_submission_actual_date'])
    &&
    $row['bid_submission_actual_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['bid_submission_actual_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['bidder_count'])
    &&
    $row['bidder_count'] != ''
    ? htmlspecialchars(
        $row['bidder_count']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['evaluate_bids_date'])
    &&
    $row['evaluate_bids_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['evaluate_bids_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['receive_price_date'])
    &&
    $row['receive_price_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['receive_price_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['bid_result_status'])
    ? htmlspecialchars(
        $row['bid_result_status']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['bid_result_amount'])
    ? htmlspecialchars(
        $row['bid_result_amount']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['winner_type'])
    ? htmlspecialchars(
        $row['winner_type']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['winner_name'])
    ? htmlspecialchars(
        $row['winner_name']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['appeal_end_date'])
    &&
    $row['appeal_end_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['appeal_end_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['has_appellant'])
    ? htmlspecialchars(
        $row['has_appellant']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['price_received_date'])
    &&
    $row['price_received_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['price_received_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['expected_signing_date'])
    &&
    $row['expected_signing_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['expected_signing_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['contract_no'])
    ? htmlspecialchars(
        $row['contract_no']
      )
    : '-';
?>
</td>


<td>
    -
</td>


<td>
<?php
echo !empty($row['contract_start_date'])
    &&
    $row['contract_start_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['contract_start_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo !empty($row['contract_end_date'])
    &&
    $row['contract_end_date'] != '0000-00-00'
    ? htmlspecialchars(
        $row['contract_end_date']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['contract_value'])
    ? htmlspecialchars(
        $row['contract_value']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['contractor_type'])
    ? htmlspecialchars(
        $row['contractor_type']
      )
    : '-';
?>
</td>


<td>
<?php
echo isset($row['contractor_name'])
    ? htmlspecialchars(
        $row['contractor_name']
      )
    : '-';
?>
</td>


<td class="truncate text-red">
<?php
echo isset($row['pt_remark'])
    ? htmlspecialchars(
        $row['pt_remark']
      )
    : '-';
?>
</td>
<!-- ==========================================
     ขยายอายุสัญญา
========================================== -->
<td>
<?php
echo (
    isset($row['is_contract_extended'])
    &&
    $row['is_contract_extended'] == 1
)
    ? '✔ มี'
    : '-';
?>
</td>
<td>
<?php
echo isset(
    $row['contract_extended_approve_doc_no']
)
&&
$row['contract_extended_approve_doc_no'] !== ''
    ? htmlspecialchars(
        $row['contract_extended_approve_doc_no']
      )
    : '-';

?>
</td>
<td>
<?php
echo !empty(
    $row['contract_extended_approve_date']
)
&&
$row['contract_extended_approve_date']
    != '0000-00-00'

    ? htmlspecialchars(
        $row['contract_extended_approve_date']
      )
    : '-';
?>
</td>
<td>
<?php
echo !empty(
    $row['contract_extended_date']
)
&&
$row['contract_extended_date']
    != '0000-00-00'

    ? htmlspecialchars(
        $row['contract_extended_date']
      )
    : '-';
?>
</td>
<td class="truncate">
<?php
echo !empty(
    $row['contract_extended_remark']
)
    ? htmlspecialchars(
        $row['contract_extended_remark']
      )
    : '-';
?>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td
    colspan="85"
    class="text-center"
    style="padding:40px 0;"
>
    ไม่พบข้อมูล
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>

<!-- ==========================================
     FLOATING HORIZONTAL SCROLLBAR
========================================== -->
<div id="floatingScrollbar" class="floating-scrollbar">
    <div id="floatingScrollbarInner" class="floating-scrollbar-inner"></div>
</div>

</div>
<script>
// ==========================================
// Floating Horizontal Scrollbar
// ==========================================

let floatingScrollbarReady = false;

function updateFloatingScrollbarWidth() {
    const tableContainer =
        document.querySelector('.table-responsive');

    const floatingScrollbar =
        document.getElementById('floatingScrollbar');

    const floatingInner =
        document.getElementById('floatingScrollbarInner');

    const table =
        document.getElementById('planTable');

    if (!tableContainer || !floatingScrollbar || !floatingInner || !table) {
        return;
    }

    floatingInner.style.width =
        Math.max(table.scrollWidth, tableContainer.clientWidth) + 'px';

    if (Math.abs(floatingScrollbar.scrollLeft - tableContainer.scrollLeft) > 1) {
        floatingScrollbar.scrollLeft = tableContainer.scrollLeft;
    }
}

function updateFloatingScrollbarVisibility() {
    const tableContainer =
        document.querySelector('.table-responsive');

    const floatingScrollbar =
        document.getElementById('floatingScrollbar');

    if (!tableContainer || !floatingScrollbar) {
        return;
    }

    const rect = tableContainer.getBoundingClientRect();
    const viewportHeight = window.innerHeight;

    const visible =
        rect.bottom > 0 &&
        rect.top < viewportHeight &&
        tableContainer.scrollWidth > tableContainer.clientWidth;

    floatingScrollbar.style.display = visible ? 'block' : 'none';
}

function initFloatingScrollbar() {
    const tableContainer =
        document.querySelector('.table-responsive');

    const floatingScrollbar =
        document.getElementById('floatingScrollbar');

    if (!tableContainer || !floatingScrollbar) {
        return;
    }

    if (!floatingScrollbarReady) {
        floatingScrollbarReady = true;

        tableContainer.addEventListener('scroll', function() {
            if (
                Math.abs(
                    floatingScrollbar.scrollLeft -
                    tableContainer.scrollLeft
                ) > 1
            ) {
                floatingScrollbar.scrollLeft =
                    tableContainer.scrollLeft;
            }
        }, { passive: true });

        floatingScrollbar.addEventListener('scroll', function() {
            if (
                Math.abs(
                    tableContainer.scrollLeft -
                    floatingScrollbar.scrollLeft
                ) > 1
            ) {
                tableContainer.scrollLeft =
                    floatingScrollbar.scrollLeft;
            }
        }, { passive: true });

        window.addEventListener('scroll', function() {
            updateFloatingScrollbarVisibility();
        }, { passive: true });

        window.addEventListener('resize', function() {
            updateFloatingScrollbarWidth();
            updateFloatingScrollbarVisibility();
        });
    }

    setTimeout(function() {
        updateFloatingScrollbarWidth();
        updateFloatingScrollbarVisibility();
    }, 100);
}

// ==========================================
// Sticky Columns
// ==========================================
function applyStickyColumns() {
    const table =
        document.getElementById(
            'planTable'
        );
    if (!table) return;
    const width =
        window.innerWidth;
    const numSticky =
        width <= 768
            ? 0
            : (
                width <= 1024
                    ? 3
                    : 10
              );
    const rows =
        table.querySelectorAll('tr');
    rows.forEach(row => {
        Array.from(
            row.children
        ).forEach(cell => {

            cell.classList.remove(
                'sticky-col',
                'sticky-last'
            );
            cell.style.left = '';
        });
    });
    if (numSticky === 0) return;
    setTimeout(() => {
        const headerCells =
            rows[0]
                ? rows[0].children
                : [];
        let leftOffsets = [];
        let currentLeft = 0;
        for (
            let i = 0;
            i < numSticky;
            i++
        ) {
            leftOffsets.push(
                currentLeft
            );
            if (headerCells[i]) {
                currentLeft +=
                    headerCells[i]
                        .offsetWidth;
            }
        }
        rows.forEach(row => {
            const cells =
                row.children;
            for (
                let i = 0;
                i < numSticky;
                i++
            ) {
                if (cells[i]) {
                    cells[i]
                        .classList
                        .add('sticky-col');
                    cells[i]
                        .style
                        .left =
                        leftOffsets[i]
                        + 'px';
                    if (
                        i ===
                        numSticky - 1
                    ) {

                        cells[i]
                            .classList
                            .add('sticky-last');
                    }
                }
            }
        });

    }, 30);
}
// ==========================================
// Live Search
// ==========================================
document.addEventListener(
    "DOMContentLoaded",
    function() {
        const searchForm =
            document.querySelector(
                '.search-box form'
            );
        const searchInputs =
            searchForm.querySelectorAll(
                'input, select'
            );
        const tableBody =
            document.querySelector(
                '#planTable tbody'
            );
        let typingTimer;
        const doneTypingInterval =
            400;
        applyStickyColumns();
        initFloatingScrollbar();
        window.addEventListener(
            'resize',
            applyStickyColumns
        );
        function fetchLiveResults() {
            const formData =
                new FormData(
                    searchForm
                );
            const params =
                new URLSearchParams(
                    formData
                ).toString();
            tableBody.innerHTML = `
                <tr>
                    <td
                        colspan="85"
                        class="loading-text"
                    >
                        กำลังค้นหาข้อมูล... ⏳
                    </td>
                </tr>
            `;
            fetch(
                window.location.pathname
                + '?'
                + params
            )
            .then(
                response =>
                    response.text()
            )
            .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                
                const newTableBody = doc.querySelector('#planTable tbody');
                
                // ดึงยอดรวมรายการจากหน้าที่โหลดมาใหม่
                const newTotalCount = doc.querySelector('#total-count');

                if (newTableBody) {
                    tableBody.innerHTML = newTableBody.innerHTML;
                    applyStickyColumns();
                    updateFloatingScrollbarWidth();
                    updateFloatingScrollbarVisibility();
                }
                
                // อัปเดตตัวเลขยอดรวมบนหน้าจอ
                if (newTotalCount) {
                    const currentTotalElement = document.getElementById('total-count');
                    if (currentTotalElement) {
                        currentTotalElement.innerText = newTotalCount.innerText;
                    }
                }
            })
            .catch(error => {
                console.error(
                    'Error:',
                    error
                );
                tableBody.innerHTML = `
                    <tr>
                        <td
                            colspan="85"
                            class="
                                text-center
                                text-red
                            "
                            style="
                                padding:40px 0;
                            "
                        >
                            ❌ เกิดข้อผิดพลาด
                            ในการดึงข้อมูล
                        </td>
                    </tr>
                `;
            });
        }
        searchInputs.forEach(
            input => {
                if (
                    input.tagName
                        .toLowerCase()
                    === 'input'
                    &&
                    input.type === 'text'
                ) {
                    input.addEventListener(
                        'input',
                        function() {
                            clearTimeout(
                                typingTimer
                            );
                            typingTimer =
                                setTimeout(
                                    fetchLiveResults,
                                    doneTypingInterval
                                );
                        }
                    );
                } else {
                    input.addEventListener(
                        'change',
                        function() {
                            clearTimeout(
                                typingTimer
                            );
                            fetchLiveResults();
                        }
                    );
                }
            }
        );
        searchForm.addEventListener(
            'submit',
            function(e) {
                e.preventDefault();
                clearTimeout(
                    typingTimer
                );
                fetchLiveResults();
            }
        );
    }
);
// ==========================================
// Export Excel
// ==========================================
function exportTableToExcel(
    tableID,
    filename = '',
    exportAll = true
) {
    let table =
        document.getElementById(
            tableID
        );
    let cloneTable =
        table.cloneNode(true);
    let hiddenElements =
        cloneTable.querySelectorAll(
            '.hide-col'
        );
    hiddenElements.forEach(
        el => {
            el.classList.remove(
                'hide-col'
            );
            el.style.display = '';
        }
    );
    let rows =
        cloneTable.rows;
    for (
        let i = 0;
        i < rows.length;
        i++
    ) {
        if (rows[i].cells[1]) {

            rows[i].deleteCell(1);
        }
    }
    let html = `
        <html
            xmlns:o="
            urn:schemas-microsoft-com:office:office"
            xmlns:x="
            urn:schemas-microsoft-com:office:excel"
            xmlns="
            http://www.w3.org/TR/REC-html40"
        >
        <head>
            <meta charset="UTF-8">
            <style>
                table {
                    border-collapse: collapse;
                }
                th,
                td {
                    border: 1px solid black;
                    padding: 5px;
                }
                .th-gray {
                    background-color:
                        #e5e7eb;
                }
                .th-lightgreen {
                    background-color:
                        #bdf285;
                }
                .th-lightpink {
                    background-color:
                        #ffe6f9;
                }

                .th-green {
                    background-color:
                        #a9d08e;
                }
                .th-blue {
                    background-color:
                        #0070c0;
                    color: white;
                }
                .th-purple {
                    background-color:
                        #d100ff;

                    color: black;
                }
                .th-pink {
                    background-color:
                        #ffb3ff;
                    color: red;
                }
                .text-red {
                    color: red;

                    font-weight: bold;
                }
            </style>
        </head>
        <body>
            ${cloneTable.outerHTML}
        </body>
        </html>
    `;

    let blob =
        new Blob(
            [html],
            {
                type:
                    'application/vnd.ms-excel'
            }
        );
    let downloadLink =
        document.createElement(
            "a"
        );
    document.body.appendChild(
        downloadLink
    );
    downloadLink.href =
        URL.createObjectURL(
            blob
        );
    downloadLink.download =
        filename
            ? filename + '.xls'
            : 'excel_data.xls';
    downloadLink.click();
    document.body.removeChild(
        downloadLink
    );
}
// ==========================================
// Download QR Code
// ==========================================

function downloadQRCode(
    url,
    filename
) {
    fetch(url)
    .then(
        response =>
            response.blob()
    )
    .then(blob => {
        let link =
            document.createElement(
                'a'
            );
        link.href =
            URL.createObjectURL(
                blob
            );
        link.download =
            filename;
        document.body.appendChild(
            link
        );
        link.click();
        document.body.removeChild(
            link
        );
    })

    .catch(
        err =>
            console.error(
                'Error downloading QR code:',
                err
            )
    );
}
</script>
</body>
</html>