<?php
require_once('includes/load.php');
global $db;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bundling_code = $_POST['bundling_code'] ?? '';
    $ids           = $_POST['id'] ?? []; // Will be empty for new rows
    $part_numbers  = $_POST['part_number'] ?? [];
    $quantities    = $_POST['quantity'] ?? [];
    $dates         = $_POST['date_active'] ?? [];

    $count = count($part_numbers);

    if (empty($bundling_code) || $count !== count($quantities) || $count !== count($dates)) {
        echo json_encode(['success' => false, 'error' => 'Invalid input']);
        exit;
    }

    try {
        $db->begin_transaction();

        $updateStmt = $db->prepare("UPDATE paket_bundling SET part_number = ?, quantity = ?, date_active = ? WHERE id = ?");
        $checkExistsStmt = $db->prepare("SELECT id FROM paket_bundling WHERE bundling_code = ? AND part_number = ? AND quantity = ? AND date_active = ?");
        $insertStmt = $db->prepare("INSERT INTO paket_bundling (bundling_code, part_number, quantity, date_active) VALUES (?, ?, ?, ?)");

        for ($i = 0; $i < $count; $i++) {
            $id           = isset($ids[$i]) ? intval($ids[$i]) : null;
            $part_number  = trim($part_numbers[$i]);
            $quantity     = (int) $quantities[$i];
            $date_active  = trim($dates[$i]);

            if (empty($part_number) || $quantity <= 0 || !validate_date($date_active)) {
                continue; // Skip invalid rows
            }

            if ($id) {
                // ✅ Update existing row by ID
                $updateStmt->bind_param("sisi", $part_number, $quantity, $date_active, $id);
                $updateStmt->execute();
            } else {
                // 🔍 Check for exact duplicates
                $checkExistsStmt->bind_param("ssis", $bundling_code, $part_number, $quantity, $date_active);
                $checkExistsStmt->execute();
                $checkExistsStmt->store_result();

                if ($checkExistsStmt->num_rows === 0) {
                    // ➕ Insert new row
                    $insertStmt->bind_param("ssis", $bundling_code, $part_number, $quantity, $date_active);
                    $insertStmt->execute();
                }
            }
        }

        $db->commit();

        // Clean up
        $updateStmt->close();
        $checkExistsStmt->close();
        $insertStmt->close();

        echo json_encode(['success' => true]);
        exit;
    } catch (Exception $e) {
        $db->rollback();
        echo json_encode(['success' => false, 'error' => 'DB error: ' . $e->getMessage()]);
        exit;
    }
}

echo json_encode(['success' => false, 'error' => 'Invalid request']);
exit;

// Utility to validate date
function validate_date($date)
{
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') === $date;
}
