<?php
include 'includes/config.php';
include 'includes/functions.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Metode request tidak valid']);
    exit;
}

$id_event = isset($_POST['id_event']) ? (int)$_POST['id_event'] : 0;
$nama_lengkap = isset($_POST['nama_lengkap']) ? $_POST['nama_lengkap'] : '';
$jabatan = isset($_POST['jabatan']) ? $_POST['jabatan'] : '';
$tanda_tangan = isset($_POST['tanda_tangan']) ? $_POST['tanda_tangan'] : '';

// Validasi data
if (empty($nama_lengkap)) {
    echo json_encode(['success' => false, 'message' => 'Nama lengkap harus diisi']);
    exit;
}

if (empty($tanda_tangan)) {
    echo json_encode(['success' => false, 'message' => 'Tanda tangan harus disediakan']);
    exit;
}

// Cek apakah event aktif
$event = $conn->query("SELECT * FROM dafdir_event WHERE id_event = $id_event AND status = 'aktif'")->fetch_assoc();
if (!$event) {
    echo json_encode(['success' => false, 'message' => 'Event tidak ditemukan atau tidak aktif']);
    exit;
}

// Proses gambar tanda tangan
// Proses gambar tanda tangan
if (!empty($tanda_tangan)) {
    // Decode base64 image
    $imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $tanda_tangan));
    
    // Buat gambar dari string
    $image = imagecreatefromstring($imageData);
    
    // Tambahkan transparansi
    imagealphablending($image, false);
    imagesavealpha($image, true);
    
    // Ubah warna putih menjadi transparan
    $white = imagecolorallocatealpha($image, 255, 255, 255, 127);
    imagefill($image, 0, 0, $white);
    
    // Temukan batas tanda tangan yang tidak transparan
    $width = imagesx($image);
    $height = imagesy($image);
    
    $minX = $width;
    $minY = $height;
    $maxX = 0;
    $maxY = 0;
    
    // Cari area yang memiliki konten (bukan transparan)
    for ($y = 0; $y < $height; $y++) {
        for ($x = 0; $x < $width; $x++) {
            $color = imagecolorat($image, $x, $y);
            $alpha = ($color >> 24) & 0xFF;
            
            // Jika pixel tidak transparan (alpha < 127)
            if ($alpha < 127) {
                if ($x < $minX) $minX = $x;
                if ($y < $minY) $minY = $y;
                if ($x > $maxX) $maxX = $x;
                if ($y > $maxY) $maxY = $y;
            }
        }
    }
    
    // Hitung dimensi baru
    $newWidth = ($maxX - $minX) + 10; // Tambahkan padding 5px di setiap sisi
    $newHeight = ($maxY - $minY) + 10;
    
    // Buat gambar baru dengan ukuran yang sesuai
    $croppedImage = imagecreatetruecolor($newWidth, $newHeight);
    imagesavealpha($croppedImage, true);
    $transparent = imagecolorallocatealpha($croppedImage, 255, 255, 255, 127);
    imagefill($croppedImage, 0, 0, $transparent);
    
    // Salin hanya area tanda tangan ke gambar baru
    imagecopy($croppedImage, $image, 5, 5, $minX, $minY, $maxX - $minX, $maxY - $minY);
    
    // Simpan gambar ke temporary file
    $tempFile = tempnam(sys_get_temp_dir(), 'signature_');
    imagepng($croppedImage, $tempFile);
    
    // Konversi ke base64 untuk disimpan
    $processedImage = base64_encode(file_get_contents($tempFile));
    $tanda_tangan = 'data:image/png;base64,' . $processedImage;
    
    // Hapus resource gambar
    imagedestroy($image);
    imagedestroy($croppedImage);
    unlink($tempFile);
}

// Dapatkan sequence terakhir untuk event ini
$lastSequence = $conn->query("SELECT MAX(sequence) as max_seq FROM dafdir_absensi WHERE id_event = $id_event")->fetch_assoc()['max_seq'];
$newSequence = ($lastSequence !== null) ? $lastSequence + 1 : 1;

// Simpan ke database
$stmt = $conn->prepare("INSERT INTO dafdir_absensi (id_event, nama_lengkap, jabatan, tanda_tangan, sequence) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("isssi", $id_event, $nama_lengkap, $jabatan, $tanda_tangan, $newSequence);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Absensi berhasil disimpan']);
} else {
    echo json_encode(['success' => false, 'message' => 'Gagal menyimpan absensi: ' . $conn->error]);
}

$stmt->close();
$conn->close();
?>