<?php
// api/submit_pregnancy_report.php
session_start();
header('Content-Type: application/json');

include 'db_connect.php'; // <--- UBAH PATH INI: 'db_connect.php' karena sudah berada di folder yang sama

$response = ['success' => false, 'message' => ''];

// Pastikan user sudah login
if (!isset($_SESSION['user_id'])) {
    $response['message'] = 'Anda harus login untuk mengirim laporan.';
    echo json_encode($response);
    exit();
}

$user_id = $_SESSION['user_id'];

// Validasi input
$hpht = $_POST['hpht'] ?? '';
$hariTidakHaid = $_POST['hariTidakHaid'] ?? '';
$adaBukti = $_POST['adaBukti'] ?? '';
$buktiFoto = $_FILES['buktiFoto'] ?? null;

if (empty($hpht) || empty($hariTidakHaid) || empty($adaBukti)) {
    $response['message'] = 'Semua kolom wajib diisi kecuali bukti foto jika tidak ada.';
    echo json_encode($response);
    exit();
}

// Validasi format tanggal
if (!DateTime::createFromFormat('Y-m-d', $hpht)) {
    $response['message'] = 'Format HPHT tidak valid.';
    echo json_encode($response);
    exit();
}

// Validasi hari tidak haid
if (!filter_var($hariTidakHaid, FILTER_VALIDATE_INT) || $hariTidakHaid < 0) {
    $response['message'] = 'Jumlah hari tidak haid harus angka positif.';
    echo json_encode($response);
    exit();
}

$proof_image_path = null;

// Handle upload foto jika ada bukti
if ($adaBukti === 'ya' && $buktiFoto && $buktiFoto['error'] === UPLOAD_ERR_OK) {
    $target_dir = "../uploads/pregnancy_proofs/"; // Sesuaikan folder upload Anda
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true); // Buat folder jika belum ada
    }

    $imageFileType = strtolower(pathinfo($buktiFoto['name'], PATHINFO_EXTENSION));
    $allowed_types = ['jpg', 'jpeg', 'png'];
    $max_size = 5 * 1024 * 1024; // 5MB

    if (!in_array($imageFileType, $allowed_types)) {
        $response['message'] = 'Maaf, hanya file JPG, JPEG, & PNG yang diizinkan.';
        echo json_encode($response);
        exit();
    }
    if ($buktiFoto['size'] > $max_size) {
        $response['message'] = 'Maaf, ukuran file terlalu besar. Maksimal 5MB.';
        echo json_encode($response);
        exit();
    }

    $file_name = uniqid('proof_') . '.' . $imageFileType;
    $target_file = $target_dir . $file_name;

    if (move_uploaded_file($buktiFoto['tmp_name'], $target_file)) {
        $proof_image_path = 'uploads/pregnancy_proofs/' . $file_name; // Simpan path relatif ke DB
    } else {
        $response['message'] = 'Gagal mengupload foto bukti.';
        echo json_encode($response);
        exit();
    }
} elseif ($adaBukti === 'ya' && (!$buktiFoto || $buktiFoto['error'] === UPLOAD_ERR_NO_FILE)) {
    $response['message'] = 'Anda memilih "Ya" untuk bukti kehamilan, tetapi tidak ada foto yang diupload.';
    echo json_encode($response);
    exit();
}


try {
    $conn->beginTransaction();

    $stmt = $conn->prepare("INSERT INTO pregnancies_reports (user_id, hpht, days_since_last_period, has_proof, proof_image_path) VALUES (:user_id, :hpht, :days_since_last_period, :has_proof, :proof_image_path)");
    
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':hpht', $hpht);
    $stmt->bindParam(':days_since_last_period', $hariTidakHaid);
    $stmt->bindParam(':has_proof', $adaBukti);
    $stmt->bindParam(':proof_image_path', $proof_image_path);
    
    $stmt->execute();

    $conn->commit();
    $response['success'] = true;
    $response['message'] = 'Laporan kehamilan berhasil dikirim!';

} catch (PDOException $e) {
    $conn->rollBack();
    $response['message'] = 'Terjadi kesalahan database: ' . $e->getMessage();
} catch (Exception $e) {
    $conn->rollBack();
    $response['message'] = 'Terjadi kesalahan: ' . $e->getMessage();
}

echo json_encode($response);
?>