<?php
// api/submit_laporan_kehamilan.php

require_once 'db_connect.php'; 

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit;
}

session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not logged in.']);
    exit;
}

$userId = $_SESSION['user_id'];

$hpht = $_POST['hpht'] ?? '';
$hariTidakHaid = $_POST['hariTidakHaid'] ?? '';
$adaBukti = $_POST['adaBukti'] ?? '';
$buktiFotoPath = null;
$type_sumber = "bumil";

if (empty($hpht) || empty($hariTidakHaid) || empty($adaBukti)) {
    echo json_encode(['status' => 'error', 'message' => 'All required fields must be filled.']);
    exit;
}

// Proses upload foto jika ada bukti
if ($adaBukti === 'ya' && isset($_FILES['buktiFoto']) && $_FILES['buktiFoto']['error'] === UPLOAD_ERR_OK) {
    $targetDir = "../uploads/"; 
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    
    $fileExtension = pathinfo($_FILES['buktiFoto']['name'], PATHINFO_EXTENSION);
    $fileName = uniqid('bukti_') . '.' . $fileExtension;
    $targetFilePath = $targetDir . $fileName;
    
    $allowedTypes = ['jpg', 'jpeg', 'png'];
    if (!in_array(strtolower($fileExtension), $allowedTypes)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid file type. Only JPG, JPEG, and PNG are allowed.']);
        exit;
    }

    if ($_FILES['buktiFoto']['size'] > 5 * 1024 * 1024) { // Max 5MB
        echo json_encode(['status' => 'error', 'message' => 'File size exceeds 5MB limit.']);
        exit;
    }

    if (move_uploaded_file($_FILES['buktiFoto']['tmp_name'], $targetFilePath)) {
        $buktiFotoPath = 'uploads/' . $fileName; 
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to upload photo.']);
        exit;
    }
} else if ($adaBukti === 'ya' && (!isset($_FILES['buktiFoto']) || $_FILES['buktiFoto']['error'] !== UPLOAD_ERR_OK)) {
    echo json_encode(['status' => 'error', 'message' => 'Please upload a photo if you selected "Ya" for proof.']);
    exit;
}

try {
    // 1. Ambil data user dari tabel users (asumsi user yang login ada di tabel 'users')
    $stmtUser = $pdo->prepare("SELECT full_name, nik, address, village, rt, rw, coordinates, phone_number FROM users WHERE id = :user_id");
    $stmtUser->bindParam(':user_id', $userId);
    $stmtUser->execute();
    $userData = $stmtUser->fetch(PDO::FETCH_ASSOC); 

    if (!$userData) {
        echo json_encode(['status' => 'error', 'message' => 'User data not found.']);
        exit;
    }

    // Parsing koordinat
    $latitude = null;
    $longitude = null;
    if (!empty($userData['coordinates'])) {
        $coords = explode(',', $userData['coordinates']);
        if (count($coords) === 2) {
            $latitude = trim($coords[0]);
            $longitude = trim($coords[1]);
        }
    }

    $phoneNumber = $userData['phone_number'] ?? null; 

    // 2. Simpan data ke tabel laporan_kehamilan
    $sql = "INSERT INTO laporan_kehamilan (user_id, nama, nik, alamat, desa, rt, rw, phone_number, latitude, longitude, hpht, hari_tidak_haid, ada_bukti, bukti_foto, type_sumber)
            VALUES (:user_id, :nama, :nik, :alamat, :desa, :rt, :rw, :phone_number, :latitude, :longitude, :hpht, :hari_tidak_haid, :ada_bukti, :bukti_foto, :type_sumber)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':user_id', $userId);
    $stmt->bindParam(':nama', $userData['full_name']);
    $stmt->bindParam(':nik', $userData['nik']);
    $stmt->bindParam(':alamat', $userData['address']);
    $stmt->bindParam(':desa', $userData['village']);
    $stmt->bindParam(':rt', $userData['rt']);
    $stmt->bindParam(':rw', $userData['rw']);
    $stmt->bindParam(':phone_number', $phoneNumber);
    $stmt->bindParam(':latitude', $latitude);
    $stmt->bindParam(':longitude', $longitude);
    $stmt->bindParam(':hpht', $hpht);
    $stmt->bindParam(':hari_tidak_haid', $hariTidakHaid);
    $stmt->bindParam(':ada_bukti', $adaBukti);
    $stmt->bindParam(':bukti_foto', $buktiFotoPath);
    $stmt->bindParam(':type_sumber', $type_sumber, PDO::PARAM_STR);
    $stmt->execute();
    
    // --- FITUR BARU: KIRIM NOTIFIKASI WA KE BIDAN DESA ---
    
    // 1. Ambil API Key Fonnte
    $stmtFonnte = $pdo->query("SELECT api_key FROM fonnte_api_keys LIMIT 1");
    $fonnteData = $stmtFonnte->fetch(PDO::FETCH_ASSOC);
    $apiKey = $fonnteData['api_key'] ?? null;

    if ($apiKey) {
        // 2. Cari Bidan Desa Berdasarkan Desa yang Sama di tabel 'users_laporan_bumil'
        $stmtBidan = $pdo->prepare("SELECT phone_number FROM users_laporan_bumil WHERE desa = :desa AND role = 'bidan_desa' LIMIT 1"); 
        $stmtBidan->bindParam(':desa', $userData['village']);
        $stmtBidan->execute();
        $bidanData = $stmtBidan->fetch(PDO::FETCH_ASSOC);
        
        $nomorBidan = $bidanData['phone_number'] ?? null;

        if ($nomorBidan) {
            // 3. Persiapkan dan Kirim Pesan WhatsApp
            // Menggunakan nama dari $userData['full_name']
            $message = "Halo, Bidan Desa " . $userData['village'] . ".\n\n"
                     . "Ada laporan kehamilan baru dari *Ibu " . $userData['full_name'] . "*.\n"
                     . "HPHT: " . $hpht . "\n"
                     . "Hari tidak haid: " . $hariTidakHaid . "\n\n"
                     . "Mohon segera ditindaklanjuti dalam 3x24 jam.\n\n"
                     . "Silakan cek data selengkapnya di sistem ibu hamil aplikasi Mampus. Terima kasih.";

            $data = [
                'target' => $nomorBidan,
                'message' => $message,
            ];

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => 'https://api.fonnte.com/send',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_HTTPHEADER => [
                    'Authorization: ' . $apiKey
                ],
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);

            if ($err) {
                error_log("cURL Error: " . $err);
            } else {
                error_log("Fonnte Response: " . $response);
            }
        } else {
            error_log("Bidan desa tidak ditemukan untuk desa: " . $userData['village']);
        }
    } else {
        error_log("Fonnte API Key tidak ditemukan di database.");
    }
    
    echo json_encode(['status' => 'success', 'message' => 'Laporan kehamilan berhasil disimpan.']);

} catch (PDOException $e) {
    error_log("Database error in submit_laporan_kehamilan.php: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Terjadi kesalahan saat menyimpan data: ' . $e->getMessage()]);
}
?>