Mini Shell

Direktori : /var/www/vhosts/ccp.ac.th/backup_full/httpdocs/fertilizer/
Upload File :
Current File : /var/www/vhosts/ccp.ac.th/backup_full/httpdocs/fertilizer/mother_additives_name.php

<?php 
// ==========================================
// 1. ส่วนประมวลผลข้อมูลเบื้องหลัง (PHP Backend)
// ==========================================
include 'db/database.php';

if (isset($_POST['action'])) {
    header('Content-Type: application/json; charset=utf-8'); // บังคับให้ตอบกลับเป็น JSON
    $action = $_POST['action'];

    // --- จัดการแม่ปุ๋ย (mother_name) ---
    if ($action == 'save_mother') {
        $id = $_POST['mother_id'];
        $name = mysqli_real_escape_string($link, $_POST['mother_name']);
        
        // ---------------------------------------------------------
        // ❗ เช็คชื่อแม่ปุ๋ยซ้ำ
        // ---------------------------------------------------------
        if (empty($id)) {
            $check_dup = "SELECT COUNT(*) AS total FROM mother_name WHERE mother_name = '$name'";
        } else {
            $check_dup = "SELECT COUNT(*) AS total FROM mother_name WHERE mother_name = '$name' AND mother_name_id != '$id'";
        }
        $res_dup = mysqli_query($link, $check_dup);
        $row_dup = mysqli_fetch_assoc($res_dup);
        
        if ($row_dup['total'] > 0) {
            echo json_encode(['status' => 'error', 'message' => 'ชื่อแม่ปุ๋ยนี้มีอยู่ในระบบแล้ว กรุณาใช้ชื่ออื่น!']);
            exit();
        }
        // ---------------------------------------------------------

        if (empty($id)) { // เพิ่มข้อมูลใหม่
            $sql = "INSERT INTO mother_name (mother_name) VALUES ('$name')";
        } else { // แก้ไขข้อมูลเดิม
            $sql = "UPDATE mother_name SET mother_name='$name' WHERE mother_name_id='$id'";
        }
        
        if (mysqli_query($link, $sql)) {
            echo json_encode(['status' => 'success', 'message' => 'บันทึกข้อมูลสำเร็จ']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'เกิดข้อผิดพลาดในการบันทึก: ' . mysqli_error($link)]);
        }
        exit();
    }
    
    if ($action == 'delete_mother') {
        $id = mysqli_real_escape_string($link, $_POST['id']);
        
        // แก้ไขชื่อคอลัมน์เป็น mother_fertilizer_name_id ตามฐานข้อมูลของคุณ
        $check_sql = "SELECT COUNT(*) AS total FROM mother_fertilizer WHERE mother_fertilizer_name_id = '$id'";
        $check_result = mysqli_query($link, $check_sql);
        
        // ดัก Error กรณีที่อาจจะยังไม่มีตาราง หรือชื่อคอลัมน์ไม่ตรง
        if (!$check_result) {
            echo json_encode(['status' => 'error', 'message' => 'ข้อผิดพลาด SQL (ตารางสูตรแม่ปุ๋ย): ' . mysqli_error($link)]);
            exit();
        }

        $check_row = mysqli_fetch_assoc($check_result);
        if ($check_row['total'] > 0) {
            echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบได้ เนื่องจากชื่อแม่ปุ๋ยนี้ถูกใช้งานอยู่ในตารางสูตรปุ๋ยแล้ว']);
        } else {
            $sql = "DELETE FROM mother_name WHERE mother_name_id='$id'";
            if (mysqli_query($link, $sql)) {
                echo json_encode(['status' => 'success', 'message' => 'ลบข้อมูลสำเร็จ']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบข้อมูลได้: ' . mysqli_error($link)]);
            }
        }
        exit();
    }

    // --- จัดการสารเติมแต่ง (additives) ---
    if ($action == 'save_additive') {
        $id = $_POST['additive_id'];
        $name = mysqli_real_escape_string($link, $_POST['additive_name']);
        
        // ---------------------------------------------------------
        // ❗ เช็คชื่อสารเติมแต่งซ้ำ
        // ---------------------------------------------------------
        if (empty($id)) {
            $check_dup = "SELECT COUNT(*) AS total FROM additives WHERE additives_name = '$name'";
        } else {
            $check_dup = "SELECT COUNT(*) AS total FROM additives WHERE additives_name = '$name' AND additives_id != '$id'";
        }
        $res_dup = mysqli_query($link, $check_dup);
        $row_dup = mysqli_fetch_assoc($res_dup);
        
        if ($row_dup['total'] > 0) {
            echo json_encode(['status' => 'error', 'message' => 'ชื่อสารเติมแต่งนี้มีอยู่ในระบบแล้ว กรุณาใช้ชื่ออื่น!']);
            exit();
        }
        // ---------------------------------------------------------

        if (empty($id)) {
            $sql = "INSERT INTO additives (additives_name) VALUES ('$name')";
        } else {
            $sql = "UPDATE additives SET additives_name='$name' WHERE additives_id='$id'";
        }
        
        if (mysqli_query($link, $sql)) {
            echo json_encode(['status' => 'success', 'message' => 'บันทึกข้อมูลสำเร็จ']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'เกิดข้อผิดพลาดในการบันทึก: ' . mysqli_error($link)]);
        }
        exit();
    }

    if ($action == 'delete_additive') {
        $id = mysqli_real_escape_string($link, $_POST['id']);
        
        // แก้ไขชื่อคอลัมน์เป็น additives_fertilizer_name ตามฐานข้อมูลของคุณ
        $check_sql = "SELECT COUNT(*) AS total FROM additives_fertilizer WHERE additives_fertilizer_name = '$id'";
        $check_result = mysqli_query($link, $check_sql);
        
        if (!$check_result) {
            echo json_encode(['status' => 'error', 'message' => 'ข้อผิดพลาด SQL (ตารางสูตรสารเติมแต่ง): ' . mysqli_error($link)]);
            exit();
        }

        $check_row = mysqli_fetch_assoc($check_result);
        if ($check_row['total'] > 0) {
            echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบได้ เนื่องจากสารเติมแต่งนี้ถูกใช้งานอยู่ในตารางสูตรปุ๋ยแล้ว']);
        } else {
            $sql = "DELETE FROM additives WHERE additives_id='$id'";
            if (mysqli_query($link, $sql)) {
                echo json_encode(['status' => 'success', 'message' => 'ลบข้อมูลสำเร็จ']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบข้อมูลได้: ' . mysqli_error($link)]);
            }
        }
        exit();
    }
}
?>

<!doctype html>
<html lang="en">
<?php include 'head.php'; ?>

<body>
    <div class="wrapper">
      <?php include 'leftside.php'; ?>
        <div class="main-panel">  
       <?php include 'header.php'; ?>
            
            <div class="content">
                <div class="container-fluid">      
                 <div class="col-md-12">
                     
                     <nav aria-label="breadcrumb">
                       <ol class="breadcrumb">
                           <li class="breadcrumb-item"><a href="home.php">หน้าหลัก</a></li>
                           <li class="breadcrumb-item active" aria-current="page">จัดการข้อมูลแม่ปุ๋ยและสารเติมแต่ง</li>
                       </ol>
                     </nav>

                     <button type="button" class="btn btn-primary" id="btnAddMother">
                         <i class="material-icons"><i class="fas fa-folder-plus"></i></i> เพิ่มชื่อแม่ปุ๋ย
                     </button>
                     
                     <?php
                          $sql_mother = "SELECT * FROM mother_name ORDER BY mother_name_id DESC";
                          $result_mother = mysqli_query($link, $sql_mother);     
                     ?>
                     <div class="card">
                         <div class="card-header card-header-icon" data-background-color="rose">
                             <i class="material-icons"><i class="fas fa-seedling"></i></i>
                         </div>
                         <h4 class="card-title">จัดการชื่อแม่ปุ๋ย</h4>
                         <div class="card-content">
                             <div>
                                 <table class="table table-striped table-no-bordered table-hover dt-table" width="100%">
                                     <thead>
                                         <tr>
                                             <th class="text-center" style="width: 10%;">ลำดับ</th>
                                             <th>ชื่อแม่ปุ๋ย</th>
                                             <th class="text-right" style="width: 20%;">จัดการ</th>
                                         </tr>
                                     </thead>
                                     <tbody>
                                        <?php 
                                        $i=1;
                                        if($result_mother) {
                                            while ($row_mother = mysqli_fetch_array($result_mother)) { ?>
                                            <tr>
                                                <td class="text-center"><?php echo $i; ?></td>
                                                <td><?php echo $row_mother['mother_name']; ?> </td>
                                                <td class="td-actions text-right">                                      
                                                    <button type="button" class="btn btn-success btn-round btn-edit-mother" 
                                                        data-id="<?php echo $row_mother['mother_name_id']; ?>" 
                                                        data-name="<?php echo htmlspecialchars($row_mother['mother_name']); ?>" title="แก้ไขข้อมูล">
                                                        <i class="material-icons"><i class="far fa-edit"></i></i>
                                                    </button>
                                                    
                                                    <button id="<?php echo $row_mother['mother_name_id']; ?>" title="ลบข้อมูล" class="btn btn-danger btn-round btn-delete-mother">
                                                        <i class="material-icons"><i class="far fa-times-circle"></i></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php $i++; } 
                                        } ?>          
                                     </tbody>
                                 </table>
                             </div>
                         </div>
                     </div>

                     <br>
                     <button type="button" class="btn btn-info" id="btnAddAdditive">
                         <i class="material-icons"><i class="fas fa-folder-plus"></i></i> เพิ่มสารเติมแต่ง
                     </button>
                     
                     <?php
                          $sql_additives = "SELECT * FROM additives ORDER BY additives_id DESC";
                          $result_additives = mysqli_query($link, $sql_additives);     
                     ?>
                     <div class="card">
                         <div class="card-header card-header-icon" data-background-color="blue">
                             <i class="material-icons"><i class="fas fa-flask"></i></i>
                         </div>
                         <h4 class="card-title">จัดการสารเติมแต่ง</h4>
                         <div class="card-content">
                             <div>
                                 <table class="table table-striped table-no-bordered table-hover dt-table" width="100%">
                                     <thead>
                                         <tr>
                                             <th class="text-center" style="width: 10%;">ลำดับ</th>
                                             <th>ชื่อสารเติมแต่ง</th>
                                             <th class="text-right" style="width: 20%;">จัดการ</th>
                                         </tr>
                                     </thead>
                                     <tbody>
                                        <?php 
                                        $j=1;
                                        if($result_additives) {
                                            while ($row_add = mysqli_fetch_array($result_additives)) { ?>
                                            <tr>
                                                <td class="text-center"><?php echo $j; ?></td>
                                                <td><?php echo $row_add['additives_name']; ?> </td>
                                                <td class="td-actions text-right">                                      
                                                    <button type="button" class="btn btn-success btn-round btn-edit-additive" 
                                                        data-id="<?php echo $row_add['additives_id']; ?>" 
                                                        data-name="<?php echo htmlspecialchars($row_add['additives_name']); ?>" title="แก้ไขข้อมูล">
                                                        <i class="material-icons"><i class="far fa-edit"></i></i>
                                                    </button>
                                                    
                                                    <button id="<?php echo $row_add['additives_id']; ?>" title="ลบข้อมูล" class="btn btn-danger btn-round btn-delete-additive">
                                                        <i class="material-icons"><i class="far fa-times-circle"></i></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php $j++; } 
                                        } ?>          
                                     </tbody>
                                 </table>
                             </div>
                         </div>
                     </div>
                            
                </div>
              </div>
            </div>
        
          <?php include 'footer1.php'; ?> 
        </div>
    </div>
<?php include 'footer2.php'; ?>

<div class="modal fade" id="modalMother" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form id="formMother">
        <div class="modal-header">
          <h4 class="modal-title" id="titleMother">เพิ่มชื่อแม่ปุ๋ย</h4>
        </div>
        <div class="modal-body">
          <input type="hidden" name="action" value="save_mother">
          <input type="hidden" name="mother_id" id="mother_id">
          <div class="form-group">
            <label class="control-label">ระบุชื่อแม่ปุ๋ย</label>
            <input type="text" class="form-control" name="mother_name" id="mother_name" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-rose">บันทึกข้อมูล</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="modalAdditive" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form id="formAdditive">
        <div class="modal-header">
          <h4 class="modal-title" id="titleAdditive">เพิ่มสารเติมแต่ง</h4>
        </div>
        <div class="modal-body">
          <input type="hidden" name="action" value="save_additive">
          <input type="hidden" name="additive_id" id="additive_id">
          <div class="form-group">
            <label class="control-label">ระบุชื่อสารเติมแต่ง</label>
            <input type="text" class="form-control" name="additive_name" id="additive_name" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-info">บันทึกข้อมูล</button>
        </div>
      </form>
    </div>
  </div>
</div>


<script>
$(document).ready(function(){
    
    // ตั้งค่า DataTables
    $('.dt-table').DataTable({
        "pagingType": "full_numbers",
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        responsive: true,
        language: {
           "search": "ค้นหา:",
           "emptyTable": "ไม่มีข้อมูลในตาราง",
           "info": "แสดง _START_ ถึง _END_ จาก _TOTAL_ แถว",
           "lengthMenu": "แสดง _MENU_ แถว",
           "paginate": { "first": "หน้าแรก", "previous": "ก่อนหน้า", "next": "ถัดไป", "last": "หน้าสุดท้าย" }
        }
    });

    // ----------------------------------------------------
    // จัดการ Event ของตารางแม่ปุ๋ย (Mother Name)
    // ----------------------------------------------------
    
    $('#btnAddMother').click(function(){
        $('#titleMother').text('เพิ่มชื่อแม่ปุ๋ย');
        $('#mother_id').val(''); 
        $('#mother_name').val(''); 
        $('#modalMother').modal('show');
    });

    // เปลี่ยนมาใช้ Event Delegation สำหรับปุ่มแก้ไขแม่ปุ๋ย
    $(document).on('click', '.btn-edit-mother', function(){
        $('#titleMother').text('แก้ไขชื่อแม่ปุ๋ย');
        $('#mother_id').val($(this).data('id')); 
        $('#mother_name').val($(this).data('name')); 
        $('#modalMother').modal('show');
    });

    $('#formMother').submit(function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: window.location.href, 
            data: $(this).serialize(),
            success: function(response){
                // เช็คสถานะการตอบกลับ
                if(response.status === 'success'){
                    $('#modalMother').modal('hide');
                    swal({title: "สำเร็จ!", text: response.message, type: "success"}, function(){
                        location.reload(); 
                    });
                } else {
                    // ถ้าชื่อซ้ำ จะแสดง error โดยไม่ปิด Modal
                    swal("ข้อผิดพลาด!", response.message, "error");
                }
            },
            error: function() {
                swal("ข้อผิดพลาด!", "ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้", "error");
            }
        });
    });

    // เปลี่ยนมาใช้ Event Delegation สำหรับปุ่มลบแม่ปุ๋ย
    $(document).on("click", ".btn-delete-mother", function(e) {
         e.preventDefault();
         var uid = $(this).attr('id');
         swal({
             title: "ลบแม่ปุ๋ย?", 
             text: "คุณจะไม่สามารถกู้คืนข้อมูลนี้ได้อีก!", 
             type: "warning",
             showCancelButton: true, 
             confirmButtonColor: '#d33', 
             confirmButtonText: "ตกลง, ลบ!",
             cancelButtonText: "ยกเลิก",
             closeOnConfirm: false
          }, function(isConfirm) {
             if (isConfirm) {
                $.ajax({
                    url: window.location.href,
                    type: 'POST',
                    dataType: 'json',
                    data: { action: 'delete_mother', id: uid },
                    success: function(data) {
                        if (data.status === 'error') {
                            swal("แจ้งเตือน!", data.message, "error");
                        } else {
                            swal({title: "สำเร็จ!", text: data.message, type: "success"}, function(){
                                location.reload(); 
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        swal("ระบบขัดข้อง!", "กรุณาตรวจสอบ Console (F12)", "error");
                        console.error("AJAX Error:", xhr.responseText);
                    }
                });
            }
         });
    });

    // ----------------------------------------------------
    // จัดการ Event ของตารางสารเติมแต่ง (Additives)
    // ----------------------------------------------------

    $('#btnAddAdditive').click(function(){
        $('#titleAdditive').text('เพิ่มสารเติมแต่ง');
        $('#additive_id').val('');
        $('#additive_name').val('');
        $('#modalAdditive').modal('show');
    });

    // เปลี่ยนมาใช้ Event Delegation สำหรับปุ่มแก้ไขสารเติมแต่ง
    $(document).on('click', '.btn-edit-additive', function(){
        $('#titleAdditive').text('แก้ไขสารเติมแต่ง');
        $('#additive_id').val($(this).data('id'));
        $('#additive_name').val($(this).data('name'));
        $('#modalAdditive').modal('show');
    });

    $('#formAdditive').submit(function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: window.location.href,
            data: $(this).serialize(),
            success: function(response){
                // เช็คสถานะการตอบกลับ
                if(response.status === 'success'){
                    $('#modalAdditive').modal('hide');
                    swal({title: "สำเร็จ!", text: response.message, type: "success"}, function(){
                        location.reload(); 
                    });
                } else {
                    // ถ้าชื่อซ้ำ จะแสดง error โดยไม่ปิด Modal
                    swal("ข้อผิดพลาด!", response.message, "error");
                }
            },
            error: function() {
                swal("ข้อผิดพลาด!", "ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้", "error");
            }
        });
    });

    // เปลี่ยนมาใช้ Event Delegation สำหรับปุ่มลบสารเติมแต่ง
    $(document).on("click", ".btn-delete-additive", function(e) {
         e.preventDefault();
         var uid = $(this).attr('id');
         swal({
             title: "ลบสารเติมแต่ง?", 
             text: "คุณจะไม่สามารถกู้คืนข้อมูลนี้ได้อีก!", 
             type: "warning",
             showCancelButton: true, 
             confirmButtonColor: '#d33', 
             confirmButtonText: "ตกลง, ลบ!",
             cancelButtonText: "ยกเลิก",
             closeOnConfirm: false
          }, function(isConfirm) {
             if (isConfirm) {
                $.ajax({
                    url: window.location.href,
                    type: 'POST',
                    dataType: 'json',
                    data: { action: 'delete_additive', id: uid },
                    success: function(data) {
                        if (data.status === 'error') {
                            swal("แจ้งเตือน!", data.message, "error");
                        } else {
                            swal({title: "สำเร็จ!", text: data.message, type: "success"}, function(){
                                location.reload();
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        swal("ระบบขัดข้อง!", "กรุณาตรวจสอบ Console (F12)", "error");
                        console.error("AJAX Error:", xhr.responseText);
                    }
                });
            }
         });
    });

});
</script>
</body>
</html>

Zerion Mini Shell 1.0