<?php
include '../config/conn.php';
require('fpdf/fpdf.php');
require('lib/BarcodeGenerator/BarcodeGenerator.php');
require('lib/BarcodeGenerator/BarcodeGeneratorPNG.php');

use Picqer\Barcode\BarcodeGeneratorPNG;

function cropImageToFit($sourcePath, $targetWidth, $targetHeight) {
    $info = getimagesize($sourcePath);
    $srcWidth = $info[0];
    $srcHeight = $info[1];
    $mime = $info['mime'];

    switch ($mime) {
        case 'image/jpeg':
            $srcImage = imagecreatefromjpeg($sourcePath);
            break;
        case 'image/png':
            $srcImage = imagecreatefrompng($sourcePath);
            break;
        case 'image/gif':
            $srcImage = imagecreatefromgif($sourcePath);
            break;
        default:
            return false;
    }

    $srcRatio = $srcWidth / $srcHeight;
    $targetRatio = $targetWidth / $targetHeight;

    if ($srcRatio > $targetRatio) {
        $newWidth = $srcHeight * $targetRatio;
        $newHeight = $srcHeight;
        $srcX = ($srcWidth - $newWidth) / 2;
        $srcY = 0;
    } else {
        $newWidth = $srcWidth;
        $newHeight = $srcWidth / $targetRatio;
        $srcX = 0;
        $srcY = ($srcHeight - $newHeight) / 2;
    }

    $dstImage = imagecreatetruecolor($targetWidth, $targetHeight);
    imagecopyresampled($dstImage, $srcImage, 0, 0, $srcX, $srcY, $targetWidth, $targetHeight, $newWidth, $newHeight);

    $tmpPath = tempnam(sys_get_temp_dir(), 'crop') . '.jpg';
    imagejpeg($dstImage, $tmpPath, 100);

    imagedestroy($srcImage);
    imagedestroy($dstImage);

    return $tmpPath;
}



// Data santri 
$data_santri = []; // hasil akhir
$id_terpilih = $_POST['selector']; // checkbox: array id santri

if (!empty($id_terpilih)) {
    // Escape tiap ID untuk keamanan SQL
    $escaped_ids = array_map(function($id) use ($conn) {
        return "'" . mysqli_real_escape_string($conn, $id) . "'";
    }, $id_terpilih);

    $id_list = implode(",", $escaped_ids);
    $sql = "SELECT * FROM santri WHERE id_santri IN ($id_list)";
    $result = mysqli_query($conn, $sql);

    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            //jenis kelamin
            if ($row['jenkel']=="l"){ $jk="Laki-Laki"; }else{ $jk="Perempuan"; }
            //tanggal lahir
                $bulan = [
                    1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                    'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
                ];
                $tgl = date('j', strtotime($row['tanggal_lahir']));       // tanggal tanpa 0 di depan
                $bln = date('n', strtotime($row['tanggal_lahir']));       // angka bulan tanpa 0 di depan
                $thn = date('Y', strtotime($row['tanggal_lahir']));       // tahun 4 digit
                
                $tgl_indo= $tgl . ' ' . $bulan[$bln] . ' ' . $thn;
            
            $data_santri[] = [
                
                'id_santri'     => $row['id_santri'],
                'nama'          => $row['nama'],
                'jenis_kelamin' => $jk,
                'ttl'           => $row['tempat_lahir'] . ', ' . $tgl_indo, // Sesuaikan field DB
                'alamat'        => $row['alamat'],
                'tahun_masuk'   => date('Y', strtotime($row['tanggal_masuk'])),
                'foto'          => $row['id_santri'] // pastikan ini path file seperti 'assets/foto/S123456.jpg'
            ];
        }
    } else {
        echo "Query error: " . mysqli_error($conn);
    }
} else {
    echo "Tidak ada santri yang dipilih.";
}


$pdf = new FPDF('P', 'mm', 'A4');
$pdf->SetAutoPageBreak(false);

$generator = new BarcodeGeneratorPNG();
$background = 'desain_kartu.png';

$kartu_width = 86;
$kartu_height = 54;
$margin_x = 10;
$margin_y = 10;
$space_x = 0.5;
$space_y = 0.1;
$col = 0;
$row = 0;

foreach ($data_santri as $index => $data) {
    if ($index % 10 == 0) {
        $pdf->AddPage();
        $col = 0;
        $row = 0;
    }

    $x = $margin_x + ($col * ($kartu_width + $space_x));
    $y = $margin_y + ($row * ($kartu_height + $space_y));

    // Background kartu
    $pdf->Image($background, $x, $y, $kartu_width, $kartu_height);

    $images_path = '../images/'.$data['foto'].'.jpg';

    // Foto (diletakkan di kiri bawah, tidak menutupi logo)
    if (file_exists($images_path)) {
       // Ukuran target
        $fotoWidth = 19.5;
        $fotoHeight = 26;

        // Crop gambar
        $croppedFoto = cropImageToFit($images_path, $fotoWidth * 15, $fotoHeight * 15); // *4 untuk resolusi lebih baik

        if ($croppedFoto) {
            $pdf->Image($croppedFoto, $x + 4, $y + 20, $fotoWidth, $fotoHeight);
            unlink($croppedFoto); // Hapus file sementara
        } else {
            // fallback jika gagal
            $pdf->Rect($x + 4, $y + 20, $fotoWidth, $fotoHeight); // tampilkan kotak kosong
        }

    }else{
        $pdf->Image("assets/foto/no-image.png", $x + 4, $y + 20, 19.5, 26); // ukuran (rasio 3x4) & posisi disesuaikan
    }

                // Pengaturan posisi dan jarak baris
$p_x = 25;
$p_y = 18;
$line_spacing = 4; // tinggi baris (tapi untuk MultiCell tinggi baris pakai parameter 3 misalnya)

// Lebar area teks agar tidak keluar desain
$text_width = 59; // sesuaikan dengan desain kartu

// Ukuran label dan konten
$label_width = 17;
$content_width = $text_width - $label_width;

// Nama (font ukuran 10, bold)
$nama_font_size = 8;
$nama_font_style = 'B';
$pdf->SetFont('Arial', $nama_font_style, $nama_font_size);
$pdf->SetXY($x + $p_x, $y + 17);
$pdf->Cell($text_width, 4, $data['nama'], 0, 1);

// Data lain font normal ukuran 7
$font_size = 7;
$pdf->SetFont('Arial', '', $font_size);

// Baris 1 - ID Santri
$pdf->SetXY($x + $p_x, $y + $p_y + $line_spacing * 1);
$pdf->SetFont('Arial', 'B', $font_size);
$pdf->Cell($label_width, 3, 'ID Santri', 0, 0);
$pdf->SetFont('Arial', '', $font_size);
$pdf->Cell($content_width, 3, ': ' .$data['id_santri'], 0, 1);

// Baris 2 - Jenis Kelamin
$pdf->SetXY($x + $p_x, $y + $p_y + $line_spacing * 2);
$pdf->SetFont('Arial', 'B', $font_size);
$pdf->Cell($label_width, 3, 'Jenis Kelamin', 0, 0);
$pdf->SetFont('Arial', '', $font_size);
$pdf->Cell($content_width, 3, ': ' .$data['jenis_kelamin'], 0, 1);

// Baris 3 - TTL
$pdf->SetXY($x + $p_x, $y + $p_y + $line_spacing * 3);
$pdf->SetFont('Arial', 'B', $font_size);
$pdf->Cell($label_width, 3, 'TTL', 0, 0);
$pdf->SetFont('Arial', '', $font_size);
$pdf->Cell($content_width, 3, ': ' .$data['ttl'], 0, 1);

// Baris 4 - Alamat (Multiline jika panjang)
$pdf->SetXY($x + $p_x, $y + $p_y + $line_spacing * 4);
$pdf->SetFont('Arial', 'B', $font_size);
$pdf->Cell($label_width, 3, 'Alamat', 0, 0);

$pdf->SetFont('Arial', '', $font_size);
$pdf->SetXY($x + $p_x + $label_width, $y + $p_y + $line_spacing * 4);
$pdf->MultiCell($content_width, 3, ': ' .$data['alamat'], 0, 'L');

// Baris 5 - Tahun Masuk (setelah alamat selesai)
$pos_y_setelah_alamat = $pdf->GetY() + 1;
$pdf->SetXY($x + $p_x, $pos_y_setelah_alamat);
$pdf->SetFont('Arial', 'B', $font_size);
$pdf->Cell($label_width, 3, 'Tahun Masuk', 0, 0);
$pdf->SetFont('Arial', '', $font_size);
$pdf->Cell($content_width, 3, ': ' .$data['tahun_masuk'], 0, 1);




   // Barcode (posisi di bawah data, tengah kanan)
   $barcode_path = 'assets/barcode/' . $data['id_santri'] . '.png';
   if (!file_exists($barcode_path)) {
       $barcodeData = $generator->getBarcode($data['id_santri'], $generator::TYPE_CODE_128);
       file_put_contents($barcode_path, $barcodeData);
   }
   $pdf->Image($barcode_path, $x + 52, $y + 43, 27, 8); // posisi & ukuran barcode
   
    $col++;
    if ($col >= 2) {
        $col = 0;
        $row++;
    }
}

$pdf->Output();
