<?php
header('Content-Type: application/json');
include 'koneksi.php';

$target_dir = "assets/img/";
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0777, true);
}

function save_foto($file_input, $target_path, $filename) {
    if (isset($_FILES[$file_input]) && $_FILES[$file_input]['error'] == 0) {
        return move_uploaded_file($_FILES[$file_input]['tmp_name'], $target_path . $filename);
    }
    return false;
}

// MODUS "upload_lengkap" (1x Request dari Raspi)
if (isset($_POST['mode']) && $_POST['mode'] === 'upload_lengkap') {
    $time = time();

    $nama_rgb    = "rgb_" . $time . ".jpg";
    $nama_gray   = "gray_" . $time . ".jpg";
    $nama_thresh = "thresh_" . $time . ".jpg";

    $rgb_ok    = save_foto('foto_rgb', $target_dir, $nama_rgb);
    $gray_ok   = save_foto('foto_gray', $target_dir, $nama_gray);
    $thresh_ok = save_foto('foto_thresh', $target_dir, $nama_thresh);

    if ($rgb_ok || $gray_ok) {
        // Simpan ke foto_telur_galeri TANPA memasukkan id_telur
        $query_galeri = "INSERT INTO foto_telur_galeri (foto_telur, foto_grayscale, foto_threshold) 
                         VALUES ('$nama_rgb', '$nama_gray', '$nama_thresh')";
        
        if (mysqli_query($koneksi, $query_galeri)) {
            $id_foto_baru = mysqli_insert_id($koneksi);
            
            $data_telur = isset($_POST['data_telur']) ? json_decode($_POST['data_telur'], true) : [];

            if (!empty($data_telur) && is_array($data_telur)) {
                $success_count = 0;
                
                foreach ($data_telur as $telur) {
                    $koordinat = mysqli_real_escape_string($koneksi, $telur['koordinat']);
                    $status    = mysqli_real_escape_string($koneksi, $telur['status']);

                    $query_riwayat = "INSERT INTO riwayat_telur (id_foto, koordinat, status, foto_telur, foto_grayscale, foto_threshold) 
                                      VALUES ('$id_foto_baru', '$koordinat', '$status', '$nama_rgb', '$nama_gray', '$nama_thresh')";
                    
                    if (mysqli_query($koneksi, $query_riwayat)) {
                        $success_count++;
                    }
                }

                echo json_encode([
                    "status" => "success", 
                    "message" => "Berhasil menyimpan foto dan $success_count data telur!",
                    "id_foto" => $id_foto_baru
                ]);
            } else {
                echo json_encode(["status" => "warning", "message" => "Foto tersimpan tetapi data array telur kosong."]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Gagal simpan ke galeri: " . mysqli_error($koneksi)]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Gagal mengunggah file gambar ke server."]);
    }
    exit();
}

echo json_encode(["status" => "error", "message" => "Parameter tidak sesuai atau data tidak lengkap."]);
?>