<?php
// ตั้งค่าการเชื่อมต่อฐานข้อมูล
$host = 'localhost';
$db = 'u66301280015';
$user = 'u66301280015';
$pass = '@2566';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// รับค่าจากตัวเลือกและการค้นหา
$search = isset($_GET['search']) ? $_GET['search'] : '';
$province_id = isset($_GET['province']) ? $_GET['province'] : null;
$district_id = isset($_GET['district']) ? $_GET['district'] : null;

// ดึงข้อมูลจังหวัด
$provinces = $conn->query("SELECT id, name_in_thai FROM provinces ORDER BY name_in_thai");
$provinces_data = [];
while ($row = $provinces->fetch_assoc()) {
    $provinces_data[] = $row;
}

// ดึงข้อมูลอำเภอ (ถ้าเลือกจังหวัด)
$districts = null;
if ($province_id) {
    $districts = $conn->query("SELECT id, name_in_thai FROM districts WHERE province_id = $province_id ORDER BY name_in_thai");
}

// ดึงข้อมูลตำบลพร้อมจังหวัดและอำเภอ สำหรับทุกจังหวัด
function getSubdistrictsByProvince($conn, $province_id, $search) {
    $query = "
        SELECT 
            subdistricts.name_in_thai AS subdistrict_name,
            subdistricts.zip_code,
            districts.name_in_thai AS district_name,
            provinces.name_in_thai AS province_name
        FROM subdistricts
        JOIN districts ON subdistricts.district_id = districts.id
        JOIN provinces ON districts.province_id = provinces.id
        WHERE districts.province_id = ?
    ";
    
    if (!empty($search)) {
        $query .= " AND (
            subdistricts.name_in_thai LIKE ? OR
            districts.name_in_thai LIKE ? OR
            provinces.name_in_thai LIKE ? OR
            subdistricts.zip_code LIKE ?
        )";
    }
    
    $query .= " ORDER BY districts.name_in_thai, subdistricts.name_in_thai";
    
    $stmt = $conn->prepare($query);
    
    if (!empty($search)) {
        $search_param = "%$search%";
        $stmt->bind_param("issss", $province_id, $search_param, $search_param, $search_param, $search_param);
    } else {
        $stmt->bind_param("i", $province_id);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    return $result;
}

function closeConnection($conn) {
    $conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>จังหวัด อำเภอ ตำบล</title>
    <link href="https://fonts.googleapis.com/css2?family=K2D:wght@300;400;500;600&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'K2D', sans-serif;
            background-color: #f9f9f9;
            margin: 0;
            padding: 20px;
        }

        .search-container {
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            margin-bottom: 30px;
            text-align: center;
            position: relative;
        }

        .search-input {
            padding: 10px;
            width: 300px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
            font-family: 'K2D', sans-serif;
        }

        .search-results {
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            width: 320px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            max-height: 300px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }

        .search-results div {
            padding: 10px;
            cursor: pointer;
            text-align: left;
        }

        .search-results div:hover {
            background-color: #f5f5f5;
        }

        .search-button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-family: 'K2D', sans-serif;
        }

        .search-button:hover {
            background-color: #45a049;
        }

        .province-dashboard {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
            overflow: hidden;
        }

        .province-header {
            background-color: #2196F3;
            color: white;
            padding: 15px;
            font-size: 1.2em;
            font-weight: 500;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px;
            text-align: center;
            border-bottom: 1px solid #ddd;
            width: 33%;
        }

        th {
            background-color: #969696;
            font-weight: 500;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        .no-data {
            padding: 20px;
            text-align: center;
            color: #666;
        }

        @media (max-width: 768px) {
            .search-input {
                width: 100%;
                margin-bottom: 10px;
            }

            .search-button {
                width: 100%;
            }

            .search-results {
                width: 90%;
            }
        }
    </style>
</head>
<body>
    <div class="search-container">
        <form method="GET" action="" id="searchForm">
            <input type="text" 
                   name="search" 
                   class="search-input" 
                   placeholder="ค้นหาข้อมูล..." 
                   value="<?= htmlspecialchars($search) ?>"
                   autocomplete="off"
                   id="searchInput">
            <div class="search-results" id="searchResults"></div>
            <button type="submit" class="search-button">ค้นหา</button>
        </form>
    </div>

    <?php foreach ($provinces_data as $province): ?>
        <?php 
        $subdistricts = getSubdistrictsByProvince($conn, $province['id'], $search);
        if ($subdistricts->num_rows > 0):
        ?>
        <div class="province-dashboard">
            <div class="province-header">
                <?= $province['name_in_thai'] ?>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>อำเภอ</th>
                        <th>ตำบล</th>
                        <th>รหัสไปรษณีย์</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $subdistricts->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row['district_name'] ?></td>
                            <td><?= $row['subdistrict_name'] ?></td>
                            <td><?= $row['zip_code'] ?></td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    <?php endforeach; ?>

    <script>
        const searchInput = document.getElementById('searchInput');
        const searchResults = document.getElementById('searchResults');
        let currentFocus = -1;

        searchInput.addEventListener('input', function(e) {
            const value = this.value;
            if (value.length < 2) {
                searchResults.style.display = 'none';
                return;
            }

            // ส่ง AJAX request ไปยัง endpoint สำหรับค้นหา
            fetch(`search_suggestions.php?term=${encodeURIComponent(value)}`)
                .then(response => response.json())
                .then(data => {
                    searchResults.innerHTML = '';
                    if (data.length > 0) {
                        data.forEach(item => {
                            const div = document.createElement('div');
                            div.textContent = item;
                            div.addEventListener('click', function() {
                                searchInput.value = this.textContent;
                                searchResults.style.display = 'none';
                                document.getElementById('searchForm').submit();
                            });
                            searchResults.appendChild(div);
                        });
                        searchResults.style.display = 'block';
                    } else {
                        searchResults.style.display = 'none';
                    }
                });
        });

        // ปิด dropdown เมื่อคลิกที่อื่น
        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
                searchResults.style.display = 'none';
            }
        });

        // จัดการการกดปุ่มลูกศรและ Enter
        searchInput.addEventListener('keydown', function(e) {
            const items = searchResults.getElementsByTagName('div');
            
            if (e.keyCode === 40) { // ลูกศรลง
                currentFocus++;
                addActive(items);
            } else if (e.keyCode === 38) { // ลูกศรขึ้น
                currentFocus--;
                addActive(items);
            } else if (e.keyCode === 13) { // Enter
                e.preventDefault();
                if (currentFocus > -1) {
                    if (items) items[currentFocus].click();
                }
            }
        });

        function addActive(items) {
            if (!items) return false;
            removeActive(items);
            if (currentFocus >= items.length) currentFocus = 0;
            if (currentFocus < 0) currentFocus = (items.length - 1);
            items[currentFocus].classList.add('active');
            searchInput.value = items[currentFocus].textContent;
        }

        function removeActive(items) {
            for (let i = 0; i < items.length; i++) {
                items[i].classList.remove('active');
            }
        }
    </script>
</body>
</html>