<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'guru') {
    header("Location: index.php");
    exit;
}

// Koneksi database
require_once 'config.php';

// Ambil data guru piket yang login
$username = $_SESSION['username'];
$guru_id = 0;
$guru_nama = '';

// Cek di tabel guru
$query = "SELECT * FROM guru WHERE nip = '$username' LIMIT 1";
$result = mysqli_query($conn, $query);

if ($result && mysqli_num_rows($result) > 0) {
    $guru = mysqli_fetch_assoc($result);
    $guru_id = $guru['id'];
    $guru_nama = $guru['nama'];
} else {
    // Coba dari tabel users
    $query_user = "SELECT * FROM users WHERE username = '$username' AND role = 'guru' LIMIT 1";
    $result_user = mysqli_query($conn, $query_user);
    if ($result_user && mysqli_num_rows($result_user) > 0) {
        $user = mysqli_fetch_assoc($result_user);
        $guru_nama = $user['nama'] ?? $username;
    }
}

// Ambil parameter ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    header("Location: dashboard_guru_piket.php");
    exit;
}

// Ambil data pelanggaran
$query = "SELECT p.*, 
                 s.nama as nama_siswa, 
                 s.nisn, 
                 s.kelas, 
                 s.no_wa,
                 g.nama as nama_guru_pelapor
          FROM pelanggaran p 
          LEFT JOIN siswa s ON p.siswa_id = s.id 
          LEFT JOIN guru g ON p.guru_id = g.id
          WHERE p.id = $id";

$result = mysqli_query($conn, $query);

if (!$result || mysqli_num_rows($result) == 0) {
    header("Location: dashboard_guru_piket.php");
    exit;
}

$pelanggaran = mysqli_fetch_assoc($result);

// Cek apakah sudah dialihkan
if ($pelanggaran['status_alihkan'] == 'ya') {
    header("Location: detail_pelanggaran.php?id=$id&alert=sudah_dialihkan");
    exit;
}

// Ambil daftar wali kelas
$wali_kelas_list = [];
$query_wali = "SELECT id, kelas, nama_wali, nip_wali FROM wali_kelas ORDER BY kelas ASC";
$result_wali = mysqli_query($conn, $query_wali);
if ($result_wali) {
    while ($row = mysqli_fetch_assoc($result_wali)) {
        $wali_kelas_list[] = $row;
    }
}

// Proses form pengalihan
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $wali_kelas_id = mysqli_real_escape_string($conn, $_POST['wali_kelas_id']);
    $catatan_alihkan = mysqli_real_escape_string($conn, $_POST['catatan_alihkan']);
    $tanggal_alihkan = date('Y-m-d H:i:s');
    
    // Validasi input
    $errors = [];
    
    if (empty($wali_kelas_id)) {
        $errors[] = "Wali kelas tujuan harus dipilih";
    }
    
    if (empty($catatan_alihkan)) {
        $errors[] = "Catatan pengalihan harus diisi";
    }
    
    if (empty($errors)) {
        $query = "UPDATE pelanggaran SET 
                  wali_kelas_id = '$wali_kelas_id',
                  status_alihkan = 'ya',
                  catatan_alihkan = '$catatan_alihkan',
                  tanggal_alihkan = '$tanggal_alihkan',
                  updated_at = '$tanggal_alihkan'
                  WHERE id = $id";
        
        if (mysqli_query($conn, $query)) {
            $message = "Pelanggaran berhasil dialihkan ke wali kelas!";
            $message_type = "success";
            
            // Redirect ke halaman detail setelah 2 detik
            header("refresh:2;url=detail_pelanggaran.php?id=$id");
        } else {
            $message = "Error: " . mysqli_error($conn);
            $message_type = "danger";
        }
    } else {
        $message = implode("<br>", $errors);
        $message_type = "danger";
    }
}

// Format tanggal
$tanggal_kejadian = date('d F Y', strtotime($pelanggaran['tanggal']));

// Tentukan kelas badge untuk poin
$poin_class = 'bg-success';
if ($pelanggaran['poin'] >= 50) {
    $poin_class = 'bg-danger';
} elseif ($pelanggaran['poin'] >= 25) {
    $poin_class = 'bg-warning text-dark';
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Alihkan Pelanggaran - Guru Piket</title>
  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <!-- Select2 -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
  <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
  <style>
    :root {
      --primary: #10b981;
      --primary-dark: #059669;
      --secondary: #f59e0b;
      --danger: #ef4444;
      --info: #3b82f6;
      --dark: #1f2937;
      --light: #f8fafc;
    }
    
    body {
      font-family: 'Inter', sans-serif;
      background: #f3f4f6;
      color: #333;
    }
    
    /* Header */
    .header {
      background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
      color: white;
      padding: 1rem 2rem;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .header-content {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .user-info {
      background: rgba(255,255,255,0.2);
      padding: 0.5rem 1.5rem;
      border-radius: 50px;
      display: flex;
      align-items: center;
      gap: 1rem;
    }
    
    .user-avatar {
      width: 40px;
      height: 40px;
      background: rgba(255,255,255,0.3);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    /* Dashboard Container */
    .dashboard-container {
      max-width: 1400px;
      margin: 0 auto;
      padding: 2rem;
    }
    
    /* Breadcrumb */
    .breadcrumb-custom {
      background: white;
      border-radius: 12px;
      padding: 1rem 1.5rem;
      margin-bottom: 2rem;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
    
    .breadcrumb-custom a {
      color: #6b7280;
      text-decoration: none;
      transition: color 0.3s;
    }
    
    .breadcrumb-custom a:hover {
      color: var(--primary);
    }
    
    .breadcrumb-custom i {
      font-size: 0.875rem;
      color: #9ca3af;
    }
    
    /* Page Header */
    .page-header {
      background: white;
      border-radius: 16px;
      padding: 1.5rem 2rem;
      margin-bottom: 2rem;
      box-shadow: 0 4px 12px rgba(0,0,0,0.05);
      display: flex;
      align-items: center;
      gap: 1rem;
    }
    
    .page-icon {
      width: 60px;
      height: 60px;
      background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.75rem;
      color: white;
    }
    
    /* Cards */
    .card {
      border: none;
      border-radius: 16px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.05);
      overflow: hidden;
      margin-bottom: 1.5rem;
    }
    
    .card-header {
      background: white;
      border-bottom: 1px solid #e5e7eb;
      padding: 1.25rem 1.5rem;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 0.75rem;
    }
    
    .card-header i {
      color: var(--secondary);
      font-size: 1.25rem;
    }
    
    .card-body {
      padding: 1.5rem;
    }
    
    /* Info Grid */
    .info-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 1rem;
    }
    
    .info-item {
      padding: 0.75rem;
      border-bottom: 1px dashed #e5e7eb;
    }
    
    .info-label {
      font-size: 0.875rem;
      color: #6b7280;
      margin-bottom: 0.25rem;
    }
    
    .info-value {
      font-weight: 600;
      font-size: 1.1rem;
    }
    
    /* Student Card */
    .student-card {
      background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
      border-radius: 12px;
      padding: 1.25rem;
      margin-bottom: 1.5rem;
    }
    
    /* Alert Info */
    .alert-warning-custom {
      background: #fffbeb;
      border-left: 4px solid #f59e0b;
      border-radius: 8px;
    }
    
    /* Badges */
    .badge-custom {
      padding: 0.5rem 1rem;
      border-radius: 20px;
      font-size: 0.875rem;
      font-weight: 600;
    }
    
    /* Buttons */
    .btn-action {
      padding: 0.75rem 2rem;
      border-radius: 10px;
      font-weight: 500;
    }
    
    .btn-primary {
      background: var(--primary);
      border: none;
    }
    
    .btn-primary:hover {
      background: var(--primary-dark);
    }
    
    .btn-warning {
      background: var(--secondary);
      border: none;
    }
    
    .btn-warning:hover {
      background: #e07b0e;
    }
    
    /* Footer */
    .footer {
      background: #1f2937;
      color: white;
      padding: 1.5rem;
      margin-top: 3rem;
    }
    
    .footer-content {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .footer-links a {
      color: white;
      text-decoration: none;
      margin: 0 0.75rem;
      opacity: 0.8;
    }
    
    .footer-links a:hover {
      opacity: 1;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
      .header-content {
        flex-direction: column;
        gap: 1rem;
      }
      
      .dashboard-container {
        padding: 1rem;
      }
      
      .info-grid {
        grid-template-columns: 1fr;
      }
      
      .footer-content {
        flex-direction: column;
        gap: 1rem;
      }
    }
    
    /* Animasi */
    .fade-in {
      animation: fadeIn 0.5s ease-in;
    }
    
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(-20px); }
      to { opacity: 1; transform: translateY(0); }
    }
  </style>
</head>
<body>
  <!-- Header -->
  <header class="header">
    <div class="header-content">
      <div class="logo-section">
        <h1><i class="fas fa-shield-alt me-2"></i>Alihkan Pelanggaran</h1>
        <div class="small">Guru Piket - Sistem Pelanggaran Siswa</div>
      </div>
      <div class="user-info">
        <div class="user-avatar">
          <i class="fas fa-user-clock"></i>
        </div>
        <div>
          <div class="fw-bold"><?php echo htmlspecialchars($guru_nama); ?></div>
          <small>Guru Piket</small>
        </div>
      </div>
    </div>
  </header>

  <!-- Main Content -->
  <div class="dashboard-container">
    <!-- Breadcrumb -->
    <div class="breadcrumb-custom">
      <a href="dashboard_guru_piket.php"><i class="fas fa-home me-1"></i>Dashboard</a>
      <i class="fas fa-chevron-right"></i>
      <a href="semua_pelanggaran.php">Semua Pelanggaran</a>
      <i class="fas fa-chevron-right"></i>
      <a href="detail_pelanggaran.php?id=<?php echo $id; ?>">Detail Pelanggaran</a>
      <i class="fas fa-chevron-right"></i>
      <span class="text-dark fw-semibold">Alihkan ke Wali Kelas</span>
    </div>

    <!-- Page Header -->
    <div class="page-header">
      <div class="page-icon">
        <i class="fas fa-share-alt"></i>
      </div>
      <div>
        <h3 class="mb-1">Alihkan Pelanggaran ke Wali Kelas</h3>
        <p class="text-muted mb-0">Pengalihan penanganan pelanggaran dari guru piket ke wali kelas</p>
      </div>
    </div>

    <!-- Alert Message -->
    <?php if (!empty($message)): ?>
    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show fade-in mb-4" role="alert">
      <i class="fas fa-<?php echo ($message_type == 'success') ? 'check-circle' : 'exclamation-circle'; ?> me-2"></i>
      <?php echo $message; ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Alert Info -->
    <div class="alert alert-warning-custom d-flex align-items-center mb-4" role="alert">
      <i class="fas fa-info-circle fa-2x me-3" style="color: #f59e0b;"></i>
      <div>
        <strong>Perhatian!</strong> Dengan mengalihkan pelanggaran ini, tanggung jawab penanganan akan beralih kepada wali kelas yang dipilih. Pastikan Anda memilih wali kelas yang sesuai dengan kelas siswa.
      </div>
    </div>

    <div class="row">
      <!-- Informasi Pelanggaran -->
      <div class="col-md-5">
        <div class="card fade-in">
          <div class="card-header">
            <i class="fas fa-exclamation-triangle" style="color: #ef4444;"></i>
            <span>Informasi Pelanggaran</span>
          </div>
          <div class="card-body">
            <div class="student-card">
              <div class="d-flex align-items-center gap-3">
                <div class="bg-primary bg-opacity-10 p-3 rounded-circle">
                  <i class="fas fa-user-graduate fa-2x" style="color: var(--primary);"></i>
                </div>
                <div>
                  <h5 class="mb-1"><?php echo htmlspecialchars($pelanggaran['nama_siswa'] ?? '-'); ?></h5>
                  <p class="text-muted mb-0">NISN: <?php echo htmlspecialchars($pelanggaran['nisn'] ?? '-'); ?></p>
                  <p class="text-muted mb-0">Kelas: <?php echo htmlspecialchars($pelanggaran['kelas'] ?? '-'); ?></p>
                </div>
              </div>
            </div>

            <div class="info-grid mt-3">
              <div class="info-item">
                <div class="info-label">Tanggal Kejadian</div>
                <div class="info-value"><?php echo $tanggal_kejadian; ?></div>
              </div>
              <div class="info-item">
                <div class="info-label">Jenis Pelanggaran</div>
                <div class="info-value"><?php echo htmlspecialchars($pelanggaran['jenis_pelanggaran']); ?></div>
              </div>
              <div class="info-item">
                <div class="info-label">Poin Pelanggaran</div>
                <div class="info-value">
                  <span class="badge <?php echo $poin_class; ?> badge-custom">
                    <?php echo $pelanggaran['poin']; ?> Poin
                  </span>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">Status</div>
                <div class="info-value">
                  <span class="badge bg-danger badge-custom">
                    <i class="fas fa-clock me-1"></i>Aktif
                  </span>
                </div>
              </div>
            </div>

            <div class="mt-3">
              <div class="info-label mb-2">Keterangan</div>
              <div class="p-3 bg-light rounded" style="max-height: 150px; overflow-y: auto;">
                <?php echo nl2br(htmlspecialchars($pelanggaran['keterangan'])); ?>
              </div>
            </div>

            <?php if (!empty($pelanggaran['bukti_foto'])): ?>
            <div class="mt-3">
              <div class="info-label mb-2">Bukti Foto</div>
              <a href="<?php echo $pelanggaran['bukti_foto']; ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                <i class="fas fa-image me-1"></i>Lihat Bukti
              </a>
            </div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- Form Pengalihan -->
      <div class="col-md-7">
        <div class="card fade-in">
          <div class="card-header">
            <i class="fas fa-share-alt" style="color: #f59e0b;"></i>
            <span>Form Pengalihan ke Wali Kelas</span>
          </div>
          <div class="card-body">
            <form method="POST" action="" id="formAlihkan">
              <!-- Pilih Wali Kelas -->
              <div class="mb-4">
                <label class="form-label fw-semibold">
                  <i class="fas fa-chalkboard-teacher me-2" style="color: #f59e0b;"></i>
                  Pilih Wali Kelas Tujuan <span class="text-danger">*</span>
                </label>
                <select class="form-select select2" name="wali_kelas_id" required>
                  <option value="">-- Pilih Wali Kelas --</option>
                  <?php foreach ($wali_kelas_list as $wali): ?>
                  <option value="<?php echo $wali['id']; ?>" data-kelas="<?php echo $wali['kelas']; ?>">
                    Kelas <?php echo htmlspecialchars($wali['kelas']); ?> - <?php echo htmlspecialchars($wali['nama_wali']); ?> (NIP: <?php echo htmlspecialchars($wali['nip_wali'] ?? '-'); ?>)
                  </option>
                  <?php endforeach; ?>
                </select>
                <div class="form-text">Pilih wali kelas yang sesuai dengan kelas siswa jika memungkinkan</div>
              </div>

              <!-- Catatan Pengalihan -->
              <div class="mb-4">
                <label class="form-label fw-semibold">
                  <i class="fas fa-sticky-note me-2" style="color: #f59e0b;"></i>
                  Catatan Pengalihan <span class="text-danger">*</span>
                </label>
                <textarea class="form-control" name="catatan_alihkan" rows="5" placeholder="Isikan catatan atau alasan pengalihan, serta hal-hal yang perlu diketahui oleh wali kelas..." required><?php echo isset($_POST['catatan_alihkan']) ? htmlspecialchars($_POST['catatan_alihkan']) : ''; ?></textarea>
                <div class="form-text">Jelaskan alasan pengalihan dan informasi penting untuk wali kelas</div>
              </div>

              <!-- Preview Info -->
              <div class="alert alert-info d-none" id="previewInfo">
                <i class="fas fa-info-circle me-2"></i>
                <span id="previewText"></span>
              </div>

              <!-- Tombol Aksi -->
              <div class="d-flex gap-3 justify-content-end mt-4">
                <a href="detail_pelanggaran.php?id=<?php echo $id; ?>" class="btn btn-outline-secondary btn-action">
                  <i class="fas fa-times me-2"></i>Batal
                </a>
                <button type="submit" class="btn btn-warning btn-action text-white" id="btnSubmit">
                  <i class="fas fa-share-alt me-2"></i>Alihkan ke Wali Kelas
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- Informasi Tambahan -->
    <div class="card mt-4">
      <div class="card-header">
        <i class="fas fa-question-circle" style="color: #3b82f6;"></i>
        <span>Panduan Pengalihan</span>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-4 mb-3">
            <div class="d-flex gap-3">
              <div class="bg-primary bg-opacity-10 p-2 rounded-circle" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-check-circle text-primary"></i>
              </div>
              <div>
                <h6>Kapan harus dialihkan?</h6>
                <p class="text-muted small">Pelanggaran yang memerlukan penanganan lebih lanjut oleh wali kelas, seperti pemanggilan orang tua atau pembinaan berkelanjutan.</p>
              </div>
            </div>
          </div>
          <div class="col-md-4 mb-3">
            <div class="d-flex gap-3">
              <div class="bg-warning bg-opacity-10 p-2 rounded-circle" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-exclamation-triangle text-warning"></i>
              </div>
              <div>
                <h6>Perhatikan Kelas Siswa</h6>
                <p class="text-muted small">Usahakan memilih wali kelas yang sesuai dengan kelas siswa agar penanganan lebih efektif.</p>
              </div>
            </div>
          </div>
          <div class="col-md-4 mb-3">
            <div class="d-flex gap-3">
              <div class="bg-success bg-opacity-10 p-2 rounded-circle" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-history text-success"></i>
              </div>
              <div>
                <h6>Riwayat Tercatat</h6>
                <p class="text-muted small">Setelah dialihkan, status akan tercatat dan dapat dilihat di riwayat pelanggaran.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Footer -->
  <footer class="footer">
    <div class="footer-content">
      <div>Versi 4.00 | Sistem Pelanggaran Siswa</div>
      <div class="footer-links">
        <a href="tentang.php"><i class="fas fa-info-circle"></i> Tentang</a>
        <a href="bantuan.php"><i class="fas fa-question-circle"></i> Bantuan</a>
        <a href="kontak.php"><i class="fas fa-phone"></i> Kontak</a>
      </div>
    </div>
  </footer>

  <!-- Scripts -->
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
  
  <script>
    $(document).ready(function() {
      // Inisialisasi Select2
      $('.select2').select2({
        theme: 'bootstrap-5',
        width: '100%',
        placeholder: '-- Pilih Wali Kelas --',
        allowClear: true
      });
      
      // Preview info saat memilih wali kelas
      $('.select2').on('change', function() {
        const selected = $(this).find('option:selected');
        const kelas = selected.data('kelas');
        const nama = selected.text().split('-')[1]?.trim() || '';
        
        if (kelas) {
          const siswaKelas = '<?php echo $pelanggaran['kelas']; ?>';
          $('#previewText').html(`Anda akan mengalihkan pelanggaran siswa kelas <strong>${siswaKelas}</strong> ke wali kelas <strong>${nama}</strong> (Kelas ${kelas})`);
          $('#previewInfo').removeClass('d-none');
          
          // Beri peringatan jika kelas tidak sesuai
          if (siswaKelas !== kelas) {
            $('#previewInfo').removeClass('alert-info').addClass('alert-warning');
            $('#previewText').append('<br><small class="text-warning"><i class="fas fa-exclamation-triangle me-1"></i>Perhatian: Kelas siswa tidak sesuai dengan wali kelas yang dipilih!</small>');
          } else {
            $('#previewInfo').removeClass('alert-warning').addClass('alert-info');
          }
        } else {
          $('#previewInfo').addClass('d-none');
        }
      });
      
      // Validasi form sebelum submit
      $('#formAlihkan').submit(function(e) {
        const waliKelas = $('select[name="wali_kelas_id"]').val();
        const catatan = $('textarea[name="catatan_alihkan"]').val();
        
        if (!waliKelas) {
          e.preventDefault();
          alert('Pilih wali kelas tujuan terlebih dahulu!');
          return false;
        }
        
        if (!catatan || catatan.trim() === '') {
          e.preventDefault();
          alert('Catatan pengalihan harus diisi!');
          return false;
        }
        
        if (catatan.length < 10) {
          e.preventDefault();
          alert('Catatan pengalihan terlalu pendek! Minimal 10 karakter.');
          return false;
        }
        
        return confirm('Apakah Anda yakin ingin mengalihkan pelanggaran ini ke wali kelas?');
      });
      
      // Animasi tombol submit
      $('#btnSubmit').hover(
        function() { $(this).removeClass('btn-warning').addClass('btn-primary'); },
        function() { $(this).removeClass('btn-primary').addClass('btn-warning'); }
      );
    });
  </script>
</body>
</html>