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/sahakorn.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'];

    // --- จัดการข้อมูลสหกรณ์ (sahakorn) ---
    if ($action == 'save_sahakorn') {
        $id = $_POST['sahakornID'];
        $code = mysqli_real_escape_string($link, $_POST['sahakorn_code']);
        $name = mysqli_real_escape_string($link, $_POST['name']);
        $province = mysqli_real_escape_string($link, $_POST['province']);
        
        // ---------------------------------------------------------
        // ❗ เช็ครหัสสหกรณ์ซ้ำ (sahakorn_code)
        // ---------------------------------------------------------
        if (empty($id)) {
            $check_sql = "SELECT COUNT(*) AS total FROM sahakorn WHERE sahakorn_code = '$code'";
        } else {
            $check_sql = "SELECT COUNT(*) AS total FROM sahakorn WHERE sahakorn_code = '$code' AND sahakornID != '$id'";
        }
        
        $check_result = mysqli_query($link, $check_sql);
        $check_row = mysqli_fetch_assoc($check_result);
        
        if ($check_row['total'] > 0) {
            echo json_encode(['status' => 'error', 'message' => 'รหัสสหกรณ์นี้มีอยู่ในระบบแล้ว กรุณาใช้รหัสอื่น!']);
            exit();
        }
        // ---------------------------------------------------------

        if (empty($id)) { // เพิ่มข้อมูลใหม่
            $sql = "INSERT INTO sahakorn (sahakorn_code, name, province) VALUES ('$code', '$name', '$province')";
        } else { // แก้ไขข้อมูลเดิม
            $sql = "UPDATE sahakorn SET sahakorn_code='$code', name='$name', province='$province' WHERE sahakornID='$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_sahakorn') {
        $id = mysqli_real_escape_string($link, $_POST['id']);
        
        // ❗ เช็คก่อนลบว่า สหกรณ์นี้ถูกใช้งานในตาราง sahakorn_process หรือไม่
        $check_process_sql = "SELECT COUNT(*) AS total FROM sahakorn_process WHERE sahakornID = '$id'";
        $check_process_res = mysqli_query($link, $check_process_sql);
        
        if ($check_process_res) {
            $row_process = mysqli_fetch_assoc($check_process_res);
            if ($row_process['total'] > 0) {
                echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบได้! เนื่องจากข้อมูลสหกรณ์นี้ถูกใช้งานในระบบแปรรูปปุ๋ยแล้ว']);
                exit();
            }
        }
        
        $sql = "DELETE FROM sahakorn WHERE sahakornID='$id'";
        
        if (mysqli_query($link, $sql)) {
            echo json_encode(['status' => 'success', 'message' => 'ลบข้อมูลสำเร็จ']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบข้อมูลได้: ' . mysqli_error($link)]);
        }
        exit();
    }
}

// --- ฟังก์ชันนำเข้าข้อมูลจากไฟล์ CSV ---
if (isset($_POST["import"])) {
    if ($_FILES["file"]["size"] > 0) {
        $file = fopen($_FILES["file"]["tmp_name"], "r");
        $row_count = 0;
        $success_count = 0;

        while (($data = fgetcsv($file, 10000, ",")) !== FALSE) {
            $row_count++;
            if ($row_count == 1) continue; 

            if (isset($data[0]) && isset($data[1]) && isset($data[2])) {
                $code = mysqli_real_escape_string($link, trim($data[0]));
                $name = mysqli_real_escape_string($link, trim($data[1]));
                $province = mysqli_real_escape_string($link, trim($data[2]));

                $check = mysqli_query($link, "SELECT sahakorn_code FROM sahakorn WHERE sahakorn_code = '$code'");
                if (mysqli_num_rows($check) == 0 && !empty($code)) {
                    $sql = "INSERT INTO sahakorn (sahakorn_code, name, province) VALUES ('$code', '$name', '$province')";
                    if (mysqli_query($link, $sql)) {
                        $success_count++;
                    }
                }
            }
        }
        fclose($file);
        
        echo "<script>
            document.addEventListener('DOMContentLoaded', function() {
                swal({
                    title: 'นำเข้าสำเร็จ!',
                    text: 'นำเข้าข้อมูลใหม่ทั้งหมด $success_count รายการ (ข้ามข้อมูลที่ซ้ำ)',
                    type: 'success'
                }, function() {
                    window.location.href = window.location.pathname;
                });
            });
        </script>";
    }
}
?>

<!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>

                     <div class="row">
                         <div class="col-md-6">
                             <button type="button" class="btn btn-primary" id="btnAddSahakorn">
                                 <i class="material-icons"><i class="fas fa-folder-plus"></i></i> เพิ่มข้อมูลสหกรณ์
                             </button>
                             <button type="button" class="btn btn-info" id="btnImportCSV">
                                 <i class="material-icons"><i class="fas fa-file-excel"></i></i> นำเข้าข้อมูล (CSV)
                             </button>
                         </div>
                     </div>
                     
                     <?php
                          $sql_sahakorn = "SELECT * FROM sahakorn ORDER BY sahakornID DESC";
                          $result_sahakorn = mysqli_query($link, $sql_sahakorn);     
                     ?>
                     <div class="card">
                         <div class="card-header card-header-icon" data-background-color="rose">
                             <i class="material-icons"><i class="fas fa-building"></i></i>
                         </div>
                         <h4 class="card-title">จัดการข้อมูลสหกรณ์</h4>
                         <div class="card-content">
                             <table class="table table-striped table-no-bordered table-hover dt-table" width="100%" style="width: 100%;">
                                 <thead>
                                     <tr>
                                         <th class="text-center" style="width: 10%;">ลำดับ</th>
                                         <th>รหัสสหกรณ์</th>
                                         <th>ชื่อสหกรณ์</th>
                                         <th>จังหวัด</th>
                                         <th class="text-right" style="width: 20%;">จัดการ</th>
                                     </tr>
                                 </thead>
                                 <tbody>
                                    <?php 
                                    $i=1;
                                    if($result_sahakorn) {
                                        while ($row = mysqli_fetch_array($result_sahakorn)) { ?>
                                        <tr>
                                            <td class="text-center"><?php echo $i; ?></td>
                                            <td><?php echo $row['sahakorn_code']; ?></td>
                                            <td><?php echo $row['name']; ?></td>
                                            <td><?php echo $row['province']; ?></td>
                                            <td class="td-actions text-right">                                      
                                                <button type="button" class="btn btn-success btn-round btn-edit-sahakorn" 
                                                    data-id="<?php echo $row['sahakornID']; ?>" 
                                                    data-code="<?php echo htmlspecialchars($row['sahakorn_code']); ?>"
                                                    data-name="<?php echo htmlspecialchars($row['name']); ?>" 
                                                    data-province="<?php echo htmlspecialchars($row['province']); ?>" 
                                                    title="แก้ไขข้อมูล">
                                                    <i class="material-icons"><i class="far fa-edit"></i></i>
                                                </button>
                                                
                                                <button id="<?php echo $row['sahakornID']; ?>" title="ลบข้อมูล" class="btn btn-danger btn-round btn-delete-sahakorn">
                                                    <i class="material-icons"><i class="far fa-times-circle"></i></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php $i++; } 
                                    } ?>          
                                 </tbody>
                             </table>
                         </div>
                     </div>
                            
                </div>
              </div>
            </div>
        
          <?php include 'footer1.php'; ?> 
        </div>
    </div>
<?php include 'footer2.php'; ?>

<div class="modal fade" id="modalSahakorn" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form id="formSahakorn">
        <div class="modal-header">
          <h4 class="modal-title" id="titleSahakorn">เพิ่มข้อมูลสหกรณ์</h4>
        </div>
        <div class="modal-body">
          <input type="hidden" name="action" value="save_sahakorn">
          <input type="hidden" name="sahakornID" id="sahakornID">
          
          <div class="form-group">
            <label class="control-label">รหัสสหกรณ์</label>
            <input type="number" class="form-control" name="sahakorn_code" id="sahakorn_code" required>
          </div>

          <div class="form-group">
            <label class="control-label">ชื่อสหกรณ์</label>
            <input type="text" class="form-control" name="name" id="name" required>
          </div>

          <div class="form-group">
            <label class="control-label">จังหวัด</label>
            <input type="text" class="form-control" name="province" id="province" 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="modalImportCSV" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form action="" method="post" enctype="multipart/form-data">
        <div class="modal-header">
          <h4 class="modal-title" style="font-weight:bold;">นำเข้าข้อมูลสหกรณ์ (ไฟล์ CSV)</h4>
        </div>
        <div class="modal-body">
            <div class="alert alert-info">
                <strong>คำแนะนำ:</strong> <br>
                1. โปรดบันทึกไฟล์ Excel ของคุณให้เป็นนามสกุล <b>.csv (UTF-8)</b> ก่อนนำเข้า <br>
                2. การจัดเรียงคอลัมน์: รหัสสหกรณ์ | ชื่อสหกรณ์ | จังหวัด <br>
                3. ระบบจะทำการข้ามข้อมูลแถวแรก (หัวตาราง) อัตโนมัติ
            </div>
            <div class="form-group is-empty is-fileinput">
                <input type="file" id="file" name="file" accept=".csv" required>
                <div class="input-group">
                    <input type="text" readonly="" class="form-control" placeholder="เลือกไฟล์ CSV...">
                    <span class="input-group-btn input-group-sm">
                        <button type="button" class="btn btn-fab btn-fab-mini btn-info">
                            <i class="material-icons">attach_file</i>
                        </button>
                    </span>
                </div>
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">ยกเลิก</button>
          <button type="submit" name="import" class="btn btn-info">เริ่มนำเข้าข้อมูล</button>
        </div>
      </form>
    </div>
  </div>
</div>


<script>
$(document).ready(function(){
    
    $('.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": "หน้าสุดท้าย" }
        }
    });

    $('#btnImportCSV').click(function(){
        $('#modalImportCSV').modal('show');
    });

    $('#btnAddSahakorn').click(function(){
        $('#titleSahakorn').text('เพิ่มข้อมูลสหกรณ์');
        $('#sahakornID').val(''); 
        $('#sahakorn_code').val(''); 
        $('#name').val(''); 
        $('#province').val(''); 
        $('#modalSahakorn').modal('show');
    });

    // ----------------------------------------------------------------------
    // ❗ แก้ไข: เปลี่ยนมาใช้ Event Delegation เพื่อให้ทำงานได้ทุกหน้า (Pagination)
    // ----------------------------------------------------------------------
    $(document).on('click', '.btn-edit-sahakorn', function() {
        $('#titleSahakorn').text('แก้ไขข้อมูลสหกรณ์');
        $('#sahakornID').val($(this).data('id')); 
        $('#sahakorn_code').val($(this).data('code')); 
        $('#name').val($(this).data('name')); 
        $('#province').val($(this).data('province')); 
        $('#modalSahakorn').modal('show');
    });

    $('#formSahakorn').submit(function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: window.location.href, 
            data: $(this).serialize(),
            success: function(response){
                if(response.status === 'success'){
                    $('#modalSahakorn').modal('hide');
                    swal({title: "สำเร็จ!", text: response.message, type: "success"}, function(){
                        location.reload(); 
                    });
                } else {
                    swal("ข้อผิดพลาด!", response.message, "error");
                }
            },
            error: function() {
                swal("ข้อผิดพลาด!", "ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้", "error");
            }
        });
    });

    // ----------------------------------------------------------------------
    // ❗ แก้ไข: เปลี่ยนมาใช้ Event Delegation เพื่อให้ทำงานได้ทุกหน้า (Pagination)
    // ----------------------------------------------------------------------
    $(document).on("click", ".btn-delete-sahakorn", 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_sahakorn', 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