ค้นหาแหล่งเรียนรู้ (ทั้งระบบ)
ค้นหาแหล่งเรียนรู้
ค้นหาแหล่งเรียนรู้
โปรดแก้ไขตามข้อเสนอแนะและส่งอนุมัติอีกครั้ง
prepare("SELECT * FROM learning_resources WHERE id = ?"); $stmt->execute([$_GET['id']]); $record = $stmt->fetch(); if ($record && canDeleteRecord($user, $record)) { $upload_dir = 'upload/'; // ลบรูปภาพปก if (!empty($record['cover_image'])) { $cover_path = $upload_dir . $record['cover_image']; if (file_exists($cover_path)) { unlink($cover_path); } } // ลบรูปภาพหลัก (JSON array) if (!empty($record['image_url'])) { $images = json_decode($record['image_url'], true) ?: []; foreach ($images as $img) { $img_path = $upload_dir . $img; if (file_exists($img_path)) { unlink($img_path); } } } // ลบข้อมูลจากฐานข้อมูล $stmt = $pdo->prepare("DELETE FROM learning_resources WHERE id = ?"); $stmt->execute([$_GET['id']]); $message = "ลบข้อมูลและไฟล์ที่เกี่ยวข้องเรียบร้อยแล้ว"; } else { $message = "ไม่มีสิทธิ์ลบข้อมูล"; } $action = 'list'; } // ตรวจสอบการอนุมัติ if ($action == 'approve' && isset($_GET['id'])) { $stmt = $pdo->prepare("SELECT * FROM learning_resources WHERE id = ?"); $stmt->execute([$_GET['id']]); $record = $stmt->fetch(); if ($record && canApproveRecord($pdo, $user, $record)) { $stmt = $pdo->prepare("UPDATE learning_resources SET status = 'approved', approved_by = ?, approved_date = NOW() WHERE id = ?"); $stmt->execute([$user['username'], $_GET['id']]); $message = "อนุมัติแหล่งเรียนรู้เรียบร้อยแล้ว"; } else { $message = "ไม่มีสิทธิ์อนุมัติแหล่งเรียนรู้"; } $action = 'list'; } // ยกเลิกการอนุมัติ (เฉพาะผู้ที่อนุมัติเท่านั้น) if ($action == 'unapprove' && isset($_GET['id'])) { $stmt = $pdo->prepare("SELECT * FROM learning_resources WHERE id = ?"); $stmt->execute([$_GET['id']]); $record = $stmt->fetch(); if ($record && $record['status'] === 'approved' && $record['approved_by'] === $user['username']) { $stmt = $pdo->prepare("UPDATE learning_resources SET status = 'pending', approved_by = NULL, approved_date = NULL WHERE id = ?"); $stmt->execute([$_GET['id']]); $message = "ยกเลิกการอนุมัติเรียบร้อยแล้ว"; } else { $message = "ไม่มีสิทธิ์ยกเลิกการอนุมัติ"; } $action = 'list'; } // ตรวจสอบการปฏิเสธ if ($action == 'reject' && isset($_GET['id'])) { $stmt = $pdo->prepare("SELECT * FROM learning_resources WHERE id = ?"); $stmt->execute([$_GET['id']]); $record = $stmt->fetch(); if ($record && canApproveRecord($pdo, $user, $record)) { $stmt = $pdo->prepare("UPDATE learning_resources SET status = 'rejected' WHERE id = ?"); $stmt->execute([$_GET['id']]); $message = "ปฏิเสธแหล่งเรียนรู้เรียบร้อยแล้ว"; } else { $message = "ไม่มีสิทธิ์ปฏิเสธแหล่งเรียนรู้"; } $action = 'list'; } // ฟังก์ชันสำหรับย่อขนาดรูปภาพและรักษาระดับขนาดไฟล์ไม่ให้เกิน 500KB function compressAndSaveImage($sourcePath, $destinationPath, $maxFileSize = 512000) { list($width, $height, $type) = getimagesize($sourcePath); // สร้างภาพต้นฉบับตามประเภทไฟล์ switch ($type) { case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($sourcePath); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($sourcePath); break; case IMAGETYPE_WEBP: $image = imagecreatefromwebp($sourcePath); break; default: return false; // ไม่รองรับประเภทอื่น } // จัดการค่าโปร่งใสสำหรับไฟล์ PNG/WEBP if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_WEBP) { imagealphablending($image, true); imagesavealpha($image, true); } // ถ้ารูปใหญ่เกินไป ให้ปรับสัดส่วนความกว้างให้เหมาะสมก่อน (เช่น ไม่เกิน 1200px) เพื่อลดขนาดไฟล์เชิงลึก $maxDim = 1200; if ($width > $maxDim || $height > $maxDim) { $ratio = $width / $height; if ($ratio > 1) { $new_width = $maxDim; $new_height = $maxDim / $ratio; } else { $new_height = $maxDim; $new_width = $maxDim * $ratio; } $dst = imagecreatetruecolor($new_width, $new_height); if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_WEBP) { imagealphablending($dst, false); imagesavealpha($dst, true); } imagecopyresampled($dst, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagedestroy($image); $image = $dst; } // ทำการเซฟไฟล์เป็น JPEG และสุ่มปรับ Quality จนกว่าขนาดไฟล์ต่ำกว่า 500KB $quality = 85; do { ob_start(); imagejpeg($image, null, $quality); $imageData = ob_get_clean(); $currentSize = strlen($imageData); $quality -= 5; } while ($currentSize > $maxFileSize && $quality > 10); // บันทึกไฟล์ลงปลายทางจริง $result = file_put_contents($destinationPath, $imageData); imagedestroy($image); return $result ? true : false; } // Handle Add/Edit if ($_SERVER['REQUEST_METHOD'] == 'POST') { // บล็อกการบันทึกข้อมูลใหม่ถ้าแอดมินปิดสวิตช์ if (empty($_POST['id']) && $user['user_type_id'] == '4' && !isAddAllowed($pdo, 'resources')) { $message = "ขณะนี้ระบบปิดการเพิ่มข้อมูลแหล่งเรียนรู้ชั่วคราว"; $action = 'list'; } else { $name = $_POST['name']; $detail = $_POST['knowledge_detail']; $geo = $_POST['geo']; $province = $_POST['province']; $district = $_POST['district']; $sub_district = $_POST['sub_district']; $zip_code = $_POST['zip_code']; $phone = $_POST['phone']; $subject = $_POST['subject']; $type = $_POST['type']; $wisdom_branch = $_POST['wisdom_branch']; $video_url = $_POST['video_url']; $latitude = $_POST['latitude'] ?? ''; $longitude = $_POST['longitude'] ?? ''; $uploaded_images = []; $cover_image = ''; if (isset($_POST['id']) && !empty($_POST['id'])) { $stmt_old = $pdo->prepare("SELECT image_url, cover_image FROM learning_resources WHERE id = ?"); $stmt_old->execute([$_POST['id']]); $old_data = $stmt_old->fetch(); if ($old_data && !empty($old_data['image_url'])) { $db_images = json_decode($old_data['image_url'], true) ?: []; // ถ้ามีการส่งรูปภาพเดิมกลับมา (รูปที่ยังไม่ถูกลบจาก UI) if (isset($_POST['existing_images'])) { foreach ($_POST['existing_images'] as $img) { if (in_array($img, $db_images)) { $uploaded_images[] = $img; } } } // ลบรูปภาพหลักที่ถูกผู้ใช้กากบาททิ้งออกจากเซิร์ฟเวอร์ $deleted_images = array_diff($db_images, $uploaded_images); foreach ($deleted_images as $del_img) { $del_path = 'upload/' . $del_img; if (file_exists($del_path) && is_file($del_path)) { unlink($del_path); } } } if ($old_data && !empty($old_data['cover_image'])) { $cover_image = $old_data['cover_image']; } } // ตรวจสอบการอัปโหลดไฟล์ใหม่ (รูปภาพหลัก - จำกัดสูงสุด 4 รูป โดยรวมกับของเดิม) if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) { $upload_dir = 'upload/'; $existing_count = count($uploaded_images); $allowed_new = 4 - $existing_count; if ($allowed_new < 0) $allowed_new = 0; $added_new = 0; // วนลูปเช็คไฟล์ foreach ($_FILES['images']['name'] as $key => $val) { if ($added_new >= $allowed_new) break; // ตัดถ้าเกินโควต้า 4 รูป if ($_FILES['images']['error'][$key] == 0) { $tmp_name = $_FILES['images']['tmp_name'][$key]; $extension = pathinfo($_FILES['images']['name'][$key], PATHINFO_EXTENSION); // ตั้งชื่อไฟล์ใหม่ป้องกันชื่อซ้ำ (บันทึกเป็นสกุล .jpg ทั้งหมดเพราะถูกแปลงผ่านฟังก์ชันย่อภาพ) $new_filename = 'img_' . uniqid() . '_' . time() . '.jpg'; $destination = $upload_dir . $new_filename; // เรียกใช้ฟังก์ชันย่อไฟล์และบันทึก if (compressAndSaveImage($tmp_name, $destination)) { $uploaded_images[] = $new_filename; $added_new++; } } } } // ตรวจสอบการอัปโหลดรูปภาพปก (ภาพเดี่ยว) if (isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] == 0) { $upload_dir = 'upload/'; $tmp_name = $_FILES['cover_image']['tmp_name']; $cover_filename = 'cover_' . uniqid() . '_' . time() . '.jpg'; $destination = $upload_dir . $cover_filename; if (compressAndSaveImage($tmp_name, $destination)) { // ลบรูปภาพปกเดิมทิ้งถ้ามีการอัปโหลดใหม่ if (isset($old_data) && !empty($old_data['cover_image'])) { $old_cover_path = $upload_dir . $old_data['cover_image']; if (file_exists($old_cover_path) && is_file($old_cover_path)) { unlink($old_cover_path); } } $cover_image = $cover_filename; } } // แปลงอาเรย์รายชื่อไฟล์รูปภาพให้เป็น JSON String เพื่อนำไปลงฐานข้อมูล $image_url_json = json_encode($uploaded_images, JSON_UNESCAPED_UNICODE); if (isset($_POST['id']) && !empty($_POST['id'])) { // 1. แก้ไขฝั่ง Update: ตรวจสอบสถานะ ถ้า rejected ให้เปลี่ยนเป็น pending $username_owner = $_SESSION['user_data']['username'] ?? ''; // ดึงสถานะปัจจุบัน $stmt_check = $pdo->prepare("SELECT status FROM learning_resources WHERE id = ?"); $stmt_check->execute([$_POST['id']]); $current = $stmt_check->fetch(); $current_status = $current['status'] ?? 'pending'; // ถ้าสถานะเป็น rejected ให้เปลี่ยนเป็น pending สำหรับการอนุมัติอีกครั้ง $new_status = ($current_status === 'rejected') ? 'pending' : $current_status; $stmt = $pdo->prepare("UPDATE learning_resources SET name=?, knowledge_detail=?, geo=?, province=?, district=?, sub_district=?, zip_code=?, phone=?, subject=?, type=?, wisdom_branch=?, video_url=?, image_url=?, cover_image=?, status=?, latitude=?, longitude=? WHERE id=? AND created_by=?"); $stmt->execute([$name, $detail, $geo, $province, $district, $sub_district, $zip_code, $phone, $subject, $type, $wisdom_branch, $video_url, $image_url_json, $cover_image, $new_status, $latitude, $longitude, $_POST['id'], $username_owner]); $message = "แก้ไขข้อมูลเรียบร้อยแล้ว" . ($current_status === 'rejected' ? " - ส่งอนุมัติอีกครั้ง" : ""); } else { // 2. แก้ไขฝั่ง Insert: เพิ่มคอลัมน์ cover_image $username_owner = $_SESSION['user_data']['username'] ?? ''; $stmt = $pdo->prepare("INSERT INTO learning_resources (created_by, name, knowledge_detail, geo, province, district, sub_district, zip_code, phone, subject, type, wisdom_branch, video_url, image_url, cover_image, latitude, longitude) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmt->execute([$username_owner, $name, $detail, $geo, $province, $district, $sub_district, $zip_code, $phone, $subject, $type, $wisdom_branch, $video_url, $image_url_json, $cover_image, $latitude, $longitude]); $message = "เพิ่มข้อมูลเรียบร้อยแล้ว"; } $action = 'list'; } // end else (permission check) } // ดึงข้อมูล สถานศึกษา (schools) สำหรับ user_type_id = 1 (จังหวัด) $schools = []; $selected_school = $_GET['school_filter'] ?? ''; if ($user['user_type_id'] == '1') { // จังหวัด user สามารถค้นหา/กรองตามสถานศึกษาในจังหวัด $province = $user['province'] ?? ''; if (!empty($province)) { $stmt = $pdo->prepare("SELECT username, firstname, title_name FROM users WHERE user_type_id = '2' AND province = ? ORDER BY firstname ASC"); $stmt->execute([$province]); $schools = $stmt->fetchAll(); } } elseif ($user['user_type_id'] == '9') { // ผู้ดูแลระบบ — เห็นสถานศึกษาทุกจังหวัด $schools = $pdo->query("SELECT username, firstname, title_name, province FROM users WHERE user_type_id = '2' ORDER BY province ASC, firstname ASC")->fetchAll(); } // ดึงข้อมูล ตำบล (subdistricts) สำหรับ user_type_id = 2 (สถานศึกษา) $subdistricts = []; if ($user['user_type_id'] == '2') { // สถานศึกษา user สามารถค้นหาตามตำบลที่อยู่ใต้สังกัด $username = $user['username'] ?? ''; if (!empty($username)) { $stmt = $pdo->prepare("SELECT DISTINCT tumbon FROM users WHERE user_type_id = '4' AND leader = ? ORDER BY tumbon ASC"); $stmt->execute([$username]); $subdistricts = $stmt->fetchAll(PDO::FETCH_COLUMN); } } // ดึงข้อมูล search parameters $search_name = $_GET['search_name'] ?? ''; $search_subdistrict = $_GET['search_subdistrict'] ?? ''; $search_type = $_GET['search_type'] ?? ''; // ดึงประเภทแหล่งเรียนรู้ทั้งหมด $resource_types = []; try { $resource_types = $pdo->query("SELECT * FROM resource_types ORDER BY name ASC")->fetchAll(); } catch (Exception $e) { // ตารางยังไม่ถูกสร้าง } // === Filter ตามภาค/จังหวัด/อำเภอ/ตำบล (สำหรับ admin type 9) === $REGION_LABELS = [ 1 => 'ภาคเหนือ', 2 => 'ภาคตะวันออกเฉียงเหนือ', 3 => 'ภาคตะวันออก', 4 => 'ภาคกลาง', 5 => 'ภาคใต้', ]; $filter_region = isset($_GET['filter_region']) && $_GET['filter_region'] !== '' ? (int)$_GET['filter_region'] : ''; $filter_province = $_GET['filter_province'] ?? ''; $filter_district = $_GET['filter_district'] ?? ''; $filter_subdistrict = $_GET['filter_subdistrict'] ?? ''; $all_provinces = $all_districts = $all_subdistricts = []; if ($user['user_type_id'] == '9') { // จังหวัด — ดึงจาก learning_resources โดยตรง (มี geo) if ($filter_region !== '') { $stmt = $pdo->prepare("SELECT DISTINCT province FROM learning_resources WHERE geo = ? AND province IS NOT NULL AND province != '' ORDER BY province ASC"); $stmt->execute([$filter_region]); $all_provinces = $stmt->fetchAll(PDO::FETCH_COLUMN); } else { $all_provinces = $pdo->query("SELECT DISTINCT province FROM learning_resources WHERE province IS NOT NULL AND province != '' ORDER BY province ASC")->fetchAll(PDO::FETCH_COLUMN); } if ($filter_province !== '') { $stmt = $pdo->prepare("SELECT DISTINCT district FROM learning_resources WHERE province = ? AND district IS NOT NULL AND district != '' ORDER BY district ASC"); $stmt->execute([$filter_province]); $all_districts = $stmt->fetchAll(PDO::FETCH_COLUMN); } if ($filter_province !== '' && $filter_district !== '') { $stmt = $pdo->prepare("SELECT DISTINCT sub_district FROM learning_resources WHERE province = ? AND district = ? AND sub_district IS NOT NULL AND sub_district != '' ORDER BY sub_district ASC"); $stmt->execute([$filter_province, $filter_district]); $all_subdistricts = $stmt->fetchAll(PDO::FETCH_COLUMN); } // Cascade reset if ($filter_province !== '' && !in_array($filter_province, $all_provinces, true)) { $filter_province = $filter_district = $filter_subdistrict = ''; $all_districts = $all_subdistricts = []; } if ($filter_district !== '' && !in_array($filter_district, $all_districts, true)) { $filter_district = $filter_subdistrict = ''; $all_subdistricts = []; } if ($filter_subdistrict !== '' && !in_array($filter_subdistrict, $all_subdistricts, true)) { $filter_subdistrict = ''; } } // Fetch resources for list ตามสิทธิ์ // === DB-level pagination + filtering === require_once '../includes/pagination.php'; ensureIndexes($pdo); // แปลง school_filter เป็นรายการ usernames $school_creators = null; if (in_array($user['user_type_id'], ['1', '9']) && !empty($selected_school)) { $stmt_sc = $pdo->prepare("SELECT username FROM users WHERE username = ? OR (leader = ? AND user_type_id = '4')"); $stmt_sc->execute([$selected_school, $selected_school]); $school_creators = $stmt_sc->fetchAll(PDO::FETCH_COLUMN); if (empty($school_creators)) $school_creators = ['__none__']; } $filters = [ 'name' => $search_name, 'type' => $search_type, ]; if ($user['user_type_id'] == '2' && !empty($search_subdistrict)) { $filters['sub_district'] = $search_subdistrict; } if ($user['user_type_id'] == '9') { if ($filter_region !== '') $filters['region'] = $filter_region; if ($filter_province !== '') $filters['province'] = $filter_province; if ($filter_district !== '') $filters['district'] = $filter_district; if ($filter_subdistrict !== '') $filters['sub_district'] = $filter_subdistrict; } if ($school_creators !== null) $filters['school_creators'] = $school_creators; [$page, $per_page, ] = paginationParams(); [$resources, $total_resources, $page, $per_page] = queryAccessiblePaginated($pdo, $user, 'learning_resources', [ 'filters' => $filters, 'order_by' => 'id DESC', 'page' => $page, 'per_page' => $per_page, ]); $pg = paginateSql($total_resources, $page, $per_page); $pg['items'] = $resources; // Fetch single resource for edit/view $editData = null; $editStatus = 'pending'; $isEditMode = false; $canViewOnly = false; if ($action == 'edit' && isset($_GET['id'])) { $stmt = $pdo->prepare("SELECT * FROM learning_resources WHERE id = ?"); $stmt->execute([$_GET['id']]); $editData = $stmt->fetch(); if (!$editData) { header("Location: resources.php"); exit(); } $editStatus = $editData['status'] ?? 'pending'; // ตรวจสอบสิทธิ์ในการแก้ไข if (canEditRecord($user, $editData)) { $isEditMode = true; } elseif (canAccessRecord($user, $editData)) { $canViewOnly = true; } else { header("Location: resources.php"); exit(); } } ?>