<?php

header("Access-Control-Allow-Origin: *");
include 'conexion.php';
include 'notification.php';

// Cek koneksi
if ($connect->connect_error) {
    http_response_code(500);
    echo json_encode(['message' => 'Koneksi ke database gagal: ' . $connect->connect_error]);
    exit;
}
// Pastikan data dikirimkan menggunakan metode POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil data JSON dari fields
    $input = json_decode($_POST['data']);

    // Debugging: Tampilkan data yang diterima
    error_log('Input Data: ' . print_r($input, true));

    $product_name = $input->name ?? '';
    $product_description = $input->description ?? '';
    $price = $input->price ?? 0;
    $quantity = $input->quantity ?? 0;
    $category_id = $input->category_id ?? '';

    // Validasi input
    if (empty($product_name) || empty($product_description) || $price <= 0 || $quantity <= 0 || empty($category_id)) {
        http_response_code(600);
        echo json_encode(['message' => 'Data tidak' . $input . 'valid']);
        exit;
    }

    // Fetch category name from the categories table based on category_id
    $category_sql = "SELECT category_name FROM categories WHERE category_id = ?";
    $category_stmt = $connect->prepare($category_sql);
    if (!$category_stmt) {
        http_response_code(500);
        echo json_encode(['message' => 'Gagal mempersiapkan query kategori: ' . $connect->error]);
        exit;
    }

    $category_stmt->bind_param("i", $category_id);
    $category_stmt->execute();
    $category_stmt->bind_result($category_name);
    $category_stmt->fetch();
    $category_stmt->close();

    if (empty($category_name)) {
        http_response_code(1000);
        echo json_encode(['message' => 'Kategori tidak ditemukan']);
        exit;
    }

    // Hitung jumlah produk dalam kategori ini
    $product_count_sql = "SELECT COUNT(*) AS product_count FROM products WHERE category_id = ?";
    $product_count_stmt = $connect->prepare($product_count_sql);
    if (!$product_count_stmt) {
        http_response_code(500);
        echo json_encode(['message' => 'Gagal mempersiapkan query hitung produk: ' . $connect->error]);
        exit;
    }

    $product_count_stmt->bind_param("i", $category_id);
    $product_count_stmt->execute();
    $product_count_stmt->bind_result($product_count);
    $product_count_stmt->fetch();
    $product_count_stmt->close();
    $category_name = strtolower($category_name);
    // Tentukan nama gambar berdasarkan jumlah produk
    $image_number = str_pad($product_count + 1, 3, '0', STR_PAD_LEFT); // Menambahkan 1 untuk gambar berikutnya
    $image_base_name = $category_name . "_images/" . $category_name . "_img" . $image_number; // Nama dasar gambar (tanpa ekstensi)

    // Handle image upload
    $image = $_FILES['image'] ?? null;
    $image_url = '';
    if ($image) {
        $upload_dir = 'images/'; // Folder sesuai dengan nama kategori
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true); // Membuat folder jika belum ada
        }

        // Mendapatkan ekstensi file berdasarkan MIME type
        $image_ext = strtolower(pathinfo($image['name'], PATHINFO_EXTENSION)); // Mendapatkan ekstensi file
        $valid_exts = ['jpg', 'jpeg', 'png', 'gif']; // Daftar ekstensi yang valid

        if (!in_array($image_ext, $valid_exts)) {
            http_response_code(700);
            echo json_encode(['message' => 'Ekstensi file tidak valid. Hanya gambar dengan ekstensi JPG, JPEG, PNG, GIF yang diperbolehkan.']);
            exit;
        }

        // Path gambar yang disimpan
        $image_path = $upload_dir . "$image_base_name.$image_ext"; // Menyimpan gambar dengan ekstensi yang sesuai
        if (move_uploaded_file($image['tmp_name'], $image_path)) {
            $image_url = "$image_base_name.$image_ext"; // Hanya simpan nama relatif gambar dengan ekstensi
        } else {
            http_response_code(500);
            echo json_encode(['message' => 'Gagal mengupload gambar']);
            exit;
        }
    }

    // Begin transaction to ensure atomicity (rollback if any error occurs)
    $connect->begin_transaction();

    try {
        // Query untuk menyimpan data ke tabel products
        $sql = "INSERT INTO products (product_name, product_description, price, quantity, category_id, image_url) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $connect->prepare($sql);



        if (!$stmt) {
            http_response_code(500);
            echo json_encode(['message' => 'Gagal mempersiapkan query produk: ' . $connect->error]);
            exit;
        }

        $stmt->bind_param("ssdiis", $product_name, $product_description, $price, $quantity, $category_id, $image_url);

        if (!$stmt->execute()) {
            throw new Exception("Gagal menambahkan produk: " . $stmt->error);
        }
        // Retrieve the product_id of the newly inserted product
        $product_id = $stmt->insert_id;

        $title = "Produk Baru!!";
        $message = "$product_name Telah Hadir!!";
        $type = "newItem";
        $username = "Januar";
        $sql = "INSERT INTO notifications (title, message, type, username, product_id) VALUES (?, ?, ?, ?,?)";
        $stmt = $connect->prepare($sql);
        $stmt->bind_param("ssssi", $title, $message, $type, $username, $product_id);

        if (!$stmt->execute()) {
            throw new Exception("Gagal menambahkan notification: " . $stmt->error);
        }



        $tokens_sql = "SELECT token FROM user_tokens WHERE is_active = 1 AND username LIKE 'Januar'";
        $tokens_stmt = $connect->prepare($tokens_sql);

        // Eksekusi query
        $tokens_stmt->execute();

        // Ambil hasil
        $result = $tokens_stmt->get_result();
        $tokens = [];

        // Ambil semua token dan simpan dalam array
        while ($row = $result->fetch_assoc()) {
            $tokens[] = $row['token'];
        }
        $id_sql = "SELECT id FROM notifications ORDER BY id DESC LIMIT 1";
        $id_stmt = $connect->prepare($id_sql);
        $id_stmt->execute();
        $id_result = $id_stmt->get_result();
        $id_row = $id_result->fetch_assoc();

        if (!$id_row) {
            throw new Exception('ID notifikasi tidak ditemukan.');
        }

        $notification_id = $id_row['id'];

        // Kirim notifikasi ke FCM dengan product_id
        $fcm_response = sendFCMNotification($product_name, $product_id, $tokens, $notification_id);

        if (!$fcm_response) {
            // Jika FCM gagal, rollback perubahan di database
            $connect->rollback();
            throw new Exception('Gagal mengirim notifikasi FCM');
        }

        // Commit transaction if everything is successful
        $connect->commit();

        // Jika berhasil
        http_response_code(200);
        echo json_encode(['message' => 'Produk berhasil ditambahkan']);
    } catch (Exception $e) {
        // Rollback if any error occurred
        $connect->rollback();
        http_response_code(500);
        echo json_encode(['message' => 'Terjadi kesalahan: ' . $e->getMessage()]);
    } finally {
        $stmt->close();
    }
} else {
    http_response_code(405);
    echo json_encode(['message' => 'Metode tidak diizinkan']);
}

// Tutup koneksi
$connect->close();


// Fungsi untuk mengirim FCM
// function sendFCMNotification($productName, $productId)
// {

//     $fcmUrl = 'https://fcm.googleapis.com/v1/projects/ecommerce-4ec3a/messages:send'; // Use your project ID
//     $accessToken = getAccessToken(); // Get the access token


//     // Send FCM request
//     $headers = ['Context-Type: application/json', 'Authorization: ' . 'Bearer ' . $accessToken];

//     $ch = curl_init($fcmUrl);
//     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//     curl_setopt($ch, CURLOPT_POSTFIELDS, '{
//     "message": {
//         "token": "fxmINLrHS4uKYiGR58GjD3:APA91bEsMpL2bSb0GHXdafmjki99TF6dhjDGHsL3uJRNeDFfZquQAYvUBqT2kArTvX-g93J45rWo4Jw1EB6HPrQyxzI8Nkh9CQUdoHtpJSoHqYZ24QWethY",
//         "notification": {
//             "title": "Produk Baru Ditambahkan",
//             "body": "' . $productName . ' telah tersedia!"
//         },
//         "data": {
//             "type": "newItem",
//             "id": "' . strval($productId) . '"
//         }
//     }

// }');
//     curl_setopt($ch, CURLOPT_VERBOSE, true);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($ch, CURLOPT_POST, true);

//     $response = curl_exec($ch);

//     if (curl_errno($ch)) {
//         echo 'Error:' . curl_error($ch);
//     }

//     curl_close($ch);

//     // Check if the request was successful
//     return json_decode($response, true);
// }