<?php
$madrasa_code = $_SESSION["madrasa_code"] ?? 1;
$row = [];
$search = "";
$success_message = "";
$error_message = "";

// স্টুডেন্ট সার্চ
if (isset($_POST['search'])) {
  $search = mysqli_real_escape_string($con, $_POST['admission']);
  $result = mysqli_query($con, "SELECT * FROM teacher WHERE teacher_id = '$search'  AND madrasa_code = '$madrasa_code' ");
  if ($result && mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
  } else {
    $error_message = 'No teacher found with this ID.';
  }
}

// ইমেজ আপলোড এবং আপডেট
if (isset($_POST['cropped_image'])) {
  if (isset($_POST['id']) && !empty($_POST['id'])) {
    $id = mysqli_real_escape_string($con, $_POST['id']);
  } else {
    die("Invalid teacher ID");
  }

  $imageData = $_POST['cropped_image'];
  $imageData = str_replace('data:image/png;base64,', '', $imageData);
  $imageData = base64_decode($imageData);
  $imageName = uniqid() . '.png';
  $imagePath = 'male/teacher/teacher_img/' . $imageName;

  // Ensure folder exists
  if (!file_exists('male/teacher/teacher_img')) {
    mkdir('male/teacher/teacher_img', 0777, true);
  }

  // আগের ছবি ডিলেট করা
  $oldImageQuery = mysqli_query($con, "SELECT teacher_img FROM teacher WHERE teacher_id = '$id' AND madrasa_code = '$madrasa_code'");
  if ($oldImageQuery) {
    $oldImageData = mysqli_fetch_assoc($oldImageQuery);
    if (
      !empty($oldImageData['teacher_img']) &&
      $oldImageData['teacher_img'] != 'gr man.png' &&
      file_exists('male/teacher/teacher_img/' . $oldImageData['teacher_img'])
    ) {
      unlink('male/teacher/teacher_img/' . $oldImageData['teacher_img']);
    }
  }

  if (file_put_contents($imagePath, $imageData)) {
    $update_sql = "UPDATE teacher SET teacher_img = '$imageName' WHERE teacher_id = '$id' AND madrasa_code = '$madrasa_code'";
    if (mysqli_query($con, $update_sql)) {
      $success_message = 'Image updated successfully!';
      $result = mysqli_query($con, "SELECT * FROM teacher WHERE teacher_id = '$id' AND madrasa_code = '$madrasa_code'");
      if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
      }
    } else {
      $error_message = "Error updating image: " . mysqli_error($con);
    }
  } else {
    $error_message = "Error saving image.";
  }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Student Image Upload</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
  <style>
    #previewImage {
      max-width: 100%;
      max-height: 300px;
      display: block;
      margin: 10px auto;
    }

    .drag-area {
      border: 2px dashed #ccc;
      padding: 30px;
      text-align: center;
      margin-bottom: 20px;
      border-radius: 8px;
      background-color: #f9f9f9;
      transition: all 0.3s;
    }

    .drag-area.active {
      border-color: #007bff;
      background-color: #e8f4ff;
    }
  </style>
</head>

<body>
  <div class="container mt-4">
    <?php if (!empty($success_message)): ?>
      <div class="alert alert-success"><?php echo $success_message; ?></div>
    <?php endif; ?>
    <?php if (!empty($error_message)): ?>
      <div class="alert alert-danger"><?php echo $error_message; ?></div>
    <?php endif; ?>

    <form action="" method="POST" class="mb-4 d-flex">
      <div class="form-group flex-grow-1 mr-2">
        <input type="text" name="admission" class="form-control" value="<?php echo $search; ?>"
          placeholder="আইডি নম্বর লিখুন" required>
      </div>
      <button type="submit" name="search" class="btn btn-primary">খোঁজ করুন</button>
    </form>

    <?php if (!empty($row)) {
      $studentImage = !empty($row['teacher_img']) ? 'male/teacher/teacher_img/' . $row['teacher_img'] : 'male/teacher/teacher_img/gr man.png';
      if (!file_exists($studentImage) && $studentImage !== 'male/teacher/teacher_img/gr man.png') {
        $studentImage = 'male/teacher/teacher_img/gr man.png';
      }
      ?>
      <div class="card">
        <div class="card-header">
          <h5 class="card-title">স্টাফ তথ্য: <?php echo htmlspecialchars($row['name']); ?>আইডি:
            <?php echo htmlspecialchars($row['teacher_id']); ?>
          </h5>

        </div>
        <div class="card-body">
          <form id="uploadForm" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $row['teacher_id']; ?>">
            <div class="text-center mb-3">
              <img id="previewImage" class="img-fluid border" src="<?php echo $studentImage; ?>">
            </div>

            <div class="drag-area" id="dragArea">
              <p>ছবি আপলোড করতে Choose File ক্লিক করুন অথবা ছবিটি ড্রাগ এন্ড ড্রপ করুন</p>
              <input type="file" id="imageInput" accept="image/*" hidden>
              <div class="d-flex justify-content-center gap-3">
                <button type="button" id="chooseFileBtn" class="btn btn-info">Choose File</button>
              </div>
              <br>
              <button type="button" id="cropButton" class="btn btn-success" disabled>Crop & Upload</button>
            </div>

            <input type="hidden" name="cropped_image" id="croppedImage">
          </form>
        </div>
      </div>
    <?php } ?>
  </div>

  <script>
    let cropper;
    const dragArea = document.getElementById('dragArea');
    const imageInput = document.getElementById('imageInput');
    const cropButton = document.getElementById('cropButton');
    const previewImage = document.getElementById('previewImage');
    const chooseFileBtn = document.getElementById('chooseFileBtn');

    // ড্রাগ এন্ড ড্রপ হ্যান্ডলার
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
      dragArea.addEventListener(eventName, e => {
        e.preventDefault();
        e.stopPropagation();
      }, false);
    });
    ['dragenter', 'dragover'].forEach(eventName => {
      dragArea.addEventListener(eventName, () => dragArea.classList.add('active'), false);
    });
    ['dragleave', 'drop'].forEach(eventName => {
      dragArea.addEventListener(eventName, () => dragArea.classList.remove('active'), false);
    });
    dragArea.addEventListener('drop', e => {
      const files = e.dataTransfer.files;
      if (files.length) { handleImage(files[0]); }
    });

    // ✅ Choose File বাটনের জন্য আলাদা হ্যান্ডলার
    chooseFileBtn.addEventListener('click', () => imageInput.click());

    // ফাইল ইনপুট
    imageInput.addEventListener('change', function () {
      if (this.files && this.files[0]) { handleImage(this.files[0]); }
    });

    function handleImage(file) {
      if (file.type.match('image.*')) {
        const reader = new FileReader();
        reader.onload = function (e) {
          previewImage.src = e.target.result;

          if (cropper) { cropper.destroy(); } // পুরানো cropper ডেস্ট্রয়
          cropper = new Cropper(previewImage, {
            aspectRatio: 7 / 9,
            viewMode: 1,
            autoCropArea: 0.9,
            responsive: true,
            ready: function () { cropButton.disabled = false; }
          });
        }
        reader.readAsDataURL(file);
      } else {
        alert("দয়া করে JPG/PNG/GIF ফাইল দিন");
      }
    }

    // ক্রপ বাটন
    cropButton.addEventListener('click', function () {
      if (cropper) {
        const canvas = cropper.getCroppedCanvas({ width: 350, height: 450, imageSmoothingQuality: 'high' });
        document.getElementById('croppedImage').value = canvas.toDataURL('image/png', 1.0);
        document.getElementById('uploadForm').submit();
      }
    });
  </script>
</body>

</html>