const API_URL = "https://repairsys.th2.melon.cloud/api";  // ✅ แก้ให้ตรงกับ Backend ที่ Melon Cloud


// 🔹 Login
function login() {
    const username = document.getElementById("login-username").value;
    const password = document.getElementById("login-password").value;

    fetch(`${API_URL}/auth/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password })
    })
    .then(res => res.json())
    .then(data => {
        console.log("📌 Response:", data);
        if (data.token) {
            localStorage.setItem("token", data.token);
            window.location.href = "dashboard.html";
        } else {
            alert("Login failed! Please check your username and password.");
        }
    })
    .catch(error => {
        console.error("❌ Login Error:", error);
        alert("เกิดข้อผิดพลาดในการเข้าสู่ระบบ");
    });
}

// 🔹 Register
function register() {
    const username = document.getElementById("register-username").value;
    const password = document.getElementById("register-password").value;

    fetch(`${API_URL}/auth/register`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password })
    })
    .then(res => res.json())
    .then(data => {
        console.log("📌 Register Response:", data);
        if (data.message) {
            alert("สมัครสมาชิกสำเร็จ! โปรดเข้าสู่ระบบ");
            window.location.href = "index.html";
        } else {
            alert("สมัครสมาชิกไม่สำเร็จ!");
        }
    })
    .catch(error => {
        console.error("❌ Register Error:", error);
        alert("เกิดข้อผิดพลาดในการสมัครสมาชิก");
    });
}

// 🔹 ไปที่หน้า Register
function goToRegister() {
    window.location.href = "register.html";
}

// 🔹 กลับไปหน้า Login
function goToLogin() {
    window.location.href = "index.html";
}

// 🔹 Logout
function logout() {
    localStorage.removeItem("token");
    window.location.href = "index.html";
}

// 🔹 ไปยังหน้าสำหรับแจ้งซ่อม (report_form.html)
function goToReportForm() {
    window.location.href = "report_form.html";
}

// ====================
// ส่วนสำหรับหน้าการแจ้งซ่อม (report_form.html)
// ====================

// 🔹 โหลดห้องเรียนตามชั้นที่เลือก (สำหรับ report_form.html หรือ dashboard.html)
function loadRooms() {
    const floor = document.getElementById("floor").value;
    const roomSelect = document.getElementById("room");
    if (!floor) {
        roomSelect.innerHTML = '<option value="">-- กรุณาเลือกห้อง --</option>';
        return;
    }
    fetch(`${API_URL}/reports/rooms/${floor}`, {
        headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
    })
    .then(res => res.json())
    .then(data => {
        roomSelect.innerHTML = '<option value="">-- กรุณาเลือกห้อง --</option>';
        if (data && data.length > 0) {
            data.forEach(room => {
                roomSelect.innerHTML += `<option value="${room.id}">${room.room_name}</option>`;
            });
        } else {
            roomSelect.innerHTML = '<option value="">ไม่มีห้องในชั้นนี้</option>';
        }
    })
    .catch(error => console.error("❌ Load Rooms Error:", error));
}

// 🔹 โหลดรายการแจ้งซ่อม (กรองตาม search, floor, และ room)
function loadReports() {
    const searchTerm = document.getElementById("search") ? document.getElementById("search").value.toLowerCase() : "";
    const floor = document.getElementById("floor") ? document.getElementById("floor").value : "";
    const room = document.getElementById("room") ? document.getElementById("room").value : "";
    
    let queryParams = [];
    if (searchTerm) queryParams.push(`search=${encodeURIComponent(searchTerm)}`);
    if (floor) queryParams.push(`floor=${encodeURIComponent(floor)}`);
    if (room) queryParams.push(`room=${encodeURIComponent(room)}`);
    const queryString = queryParams.length ? "?" + queryParams.join("&") : "";
    
    fetch(`${API_URL}/reports${queryString}`, {
        headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
    })
    .then(res => res.json())
    .then(data => {
        let reportsHTML = "";
        data.forEach(report => {
            reportsHTML += `<div class="report-card">
                <h3>${report.title}</h3>
                <p><strong>รายละเอียด:</strong> ${report.description}</p>
                <p><strong>แจ้งโดย:</strong> ${report.username}</p>
                <p><strong>ห้อง:</strong> ${report.room_name}</p>
                <p><strong>ชั้น:</strong> ${report.floor}</p>
                ${report.image_url ? `<img src="${report.image_url}" width="200px" alt="Report Image" onerror="this.onerror=null; this.src='default.jpg';">` : ""}
                <button onclick="editReport(${report.id})">Edit</button>
                <button onclick="deleteReport(${report.id})">Delete</button>
            </div>`;
        });
        document.getElementById("reports").innerHTML = reportsHTML;
    })
    .catch(error => console.error("❌ Load Reports Error:", error));
}

// 🔹 ค้นหาแจ้งซ่อม (ใช้ loadReports())
function searchReports() {
    loadReports();
}

// 🔹 เมื่อเปิดหน้า dashboard.html ให้โหลดรายงานด้วย filter ปัจจุบัน
if (window.location.pathname.includes("dashboard.html")) {
    loadReports();
}

// ส่วนสำหรับการแก้ไข Report (edit_report.html) ยังคงเหมือนเดิม...
function editReport(id) {
    window.location.href = `edit_report.html?id=${id}`;
}

function deleteReport(id) {
    fetch(`${API_URL}/reports/${id}`, {
        method: "DELETE",
        headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        loadReports();
    })
    .catch(error => console.error("❌ Delete Report Error:", error));
}

// ฟังก์ชันสำหรับหน้าการแก้ไข (edit_report.html)
function loadEditReport() {
    const params = new URLSearchParams(window.location.search);
    const reportId = params.get("id");

    if (!reportId) {
        alert("ไม่พบรายการแจ้งซ่อม");
        window.location.href = "dashboard.html";
        return;
    }

    fetch(`${API_URL}/reports/${reportId}`, {
        headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
    })
    .then(res => res.json())
    .then(report => {
        document.getElementById("reportId").value = report.id;
        document.getElementById("editTitle").value = report.title;
        document.getElementById("editDescription").value = report.description;
    })
    .catch(error => console.error("❌ Load Report Error:", error));
}

document.getElementById("editReportForm")?.addEventListener("submit", function(event) {
    event.preventDefault();

    const reportId = document.getElementById("reportId").value;
    const title = document.getElementById("editTitle").value;
    const description = document.getElementById("editDescription").value;

    fetch(`${API_URL}/reports/${reportId}`, {
        method: "PUT",
        headers: { 
            "Content-Type": "application/json",
            "Authorization": `Bearer ${localStorage.getItem("token")}`
        },
        body: JSON.stringify({ title, description })
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        window.location.href = "dashboard.html";
    })
    .catch(error => console.error("❌ Update Report Error:", error));
});

function cancelEdit() {
    window.location.href = "dashboard.html";
}

if (window.location.pathname.includes("edit_report.html")) {
    loadEditReport();
}


// 🔹 ส่งข้อมูลแจ้งซ่อม (สำหรับ report_form.html)
// ไม่ส่ง user_id เพราะ Backend จะใช้ Token กำหนดให้เอง
function submitReport() {
    const title = document.getElementById("title").value;
    const description = document.getElementById("description").value;
    const room_id = document.getElementById("room").value; // รับค่าจาก dropdown
    const image = document.getElementById("image").files[0];

    if (!room_id) {
        alert("กรุณาเลือกห้องที่ต้องการแจ้งซ่อม");
        return;
    }

    const formData = new FormData();
    formData.append("title", title);
    formData.append("description", description);
    formData.append("room_id", room_id);
    if (image) formData.append("image", image);

    fetch(`${API_URL}/reports`, {
        method: "POST",
        headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` },
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        console.log("📌 Response:", data);
        if (data.message) {
            alert(data.message);
            window.location.href = "dashboard.html";
        } else {
            alert("เกิดข้อผิดพลาด กรุณาลองใหม่");
        }
    })
    .catch(error => console.error("❌ API Error:", error));
}

// 🔹 ยกเลิกการแจ้งซ่อม (สำหรับ report_form.html)
function cancelReport() {
    window.location.href = "dashboard.html";
}

// ====================
// ส่วนสำหรับหน้าดูและจัดการ Report (dashboard.html)
// ====================
// ฟังก์ชันนี้จะนำเอาค่า filter (search, floor, room) มาสร้าง query parameter
// 🔹 โหลดรายการแจ้งซ่อม (กรองตาม search, floor, และ room)
// 🔹 โหลดรายการแจ้งซ่อม (รวมชื่อผู้ใช้, ห้อง และชั้น) ในรูปแบบ Bootstrap card
function loadReports() {
    const searchTerm = document.getElementById("search") ? document.getElementById("search").value.toLowerCase() : "";
    const floor = document.getElementById("floor") ? document.getElementById("floor").value : "";
    const room = document.getElementById("room") ? document.getElementById("room").value : "";
    
    let queryParams = [];
    if (searchTerm) queryParams.push(`search=${encodeURIComponent(searchTerm)}`);
    if (floor) queryParams.push(`floor=${encodeURIComponent(floor)}`);
    if (room) queryParams.push(`room=${encodeURIComponent(room)}`);
    const queryString = queryParams.length ? "?" + queryParams.join("&") : "";

    fetch(`${API_URL}/reports${queryString}`, {
        headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
    })
    .then(res => res.json())
    .then(data => {
        let reportsHTML = "";
        data.forEach(report => {
            reportsHTML += `
                <div class="col-md-4 mb-3">
                  <div class="card h-100">
                    ${report.image_url ? `<img src="${report.image_url}" class="card-img-top" alt="Report Image" style="max-height:200px; object-fit: cover;">` : ""}
                    <div class="card-body">
                      <h5 class="card-title">${report.title}</h5>
                      <p class="card-text"><strong>รายละเอียด:</strong> ${report.description}</p>
                      <p class="card-text"><strong>แจ้งโดย:</strong> ${report.username}</p>
                      <p class="card-text"><strong>ห้อง:</strong> ${report.room_name} | <strong>ชั้น:</strong> ${report.floor}</p>
                    </div>
                    <div class="card-footer text-end">
                      <button onclick="editReport(${report.id})" class="btn btn-warning btn-sm me-2">Edit</button>
                      <button onclick="deleteReport(${report.id})" class="btn btn-danger btn-sm">Delete</button>
                    </div>
                  </div>
                </div>
            `;
        });
        document.getElementById("reports").innerHTML = `<div class="row">${reportsHTML}</div>`;
    })
    .catch(error => console.error("❌ Load Reports Error:", error));
}


// 🔹 ค้นหาแจ้งซ่อม (รวมชื่อผู้ใช้, ห้อง และชั้น)
// สำหรับค้นหา เราให้เรียกใช้ loadReports() อีกครั้ง
function searchReports() {
    loadReports();
}

// 🔹 โหลดรายการแจ้งซ่อมเมื่อเปิด dashboard.html
if (window.location.pathname.includes("dashboard.html")) {
    loadReports();
}

// 🔹 กด Edit แล้วไปหน้า edit_report.html พร้อมส่ง ID ไปด้วย (สำหรับ dashboard.html)
function editReport(id) {
    window.location.href = `edit_report.html?id=${id}`;
}

// ====================
// ส่วนสำหรับหน้าการแก้ไข Report (edit_report.html)
// ====================

// 🔹 โหลดข้อมูล Report ในหน้า edit_report.html
function loadEditReport() {
    const params = new URLSearchParams(window.location.search);
    const reportId = params.get("id");

    if (!reportId) {
        alert("ไม่พบรายการแจ้งซ่อม");
        window.location.href = "dashboard.html";
        return;
    }

    fetch(`${API_URL}/reports/${reportId}`, {
        headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
    })
    .then(res => res.json())
    .then(report => {
        document.getElementById("reportId").value = report.id;
        document.getElementById("editTitle").value = report.title;
        document.getElementById("editDescription").value = report.description;
    })
    .catch(error => console.error("❌ Load Report Error:", error));
}

// 🔹 ส่งข้อมูลที่แก้ไขไปอัปเดตในฐานข้อมูล (สำหรับ edit_report.html)
document.getElementById("editReportForm")?.addEventListener("submit", function(event) {
    event.preventDefault();

    const reportId = document.getElementById("reportId").value;
    const title = document.getElementById("editTitle").value;
    const description = document.getElementById("editDescription").value;

    fetch(`${API_URL}/reports/${reportId}`, {
        method: "PUT",
        headers: { 
            "Content-Type": "application/json",
            "Authorization": `Bearer ${localStorage.getItem("token")}` 
        },
        body: JSON.stringify({ title, description })
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        window.location.href = "dashboard.html";
    })
    .catch(error => console.error("❌ Update Report Error:", error));
});

// 🔹 ยกเลิกการแก้ไข (สำหรับ edit_report.html)
function cancelEdit() {
    window.location.href = "dashboard.html";
}

// 🔹 โหลดข้อมูลเมื่อเปิดหน้า edit_report.html
if (window.location.pathname.includes("edit_report.html")) {
    loadEditReport();
}