<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("definitions.php");

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

// =============================
// INPUT VALIDATION
// =============================
$primaryCustomer = isset($_POST['primary_customer_key']) ? intval($_POST['primary_customer_key']) : 0;
$mergeCustomer   = isset($_POST['merge_customer_key']) ? intval($_POST['merge_customer_key']) : 0;

if ($primaryCustomer <= 0 || $mergeCustomer <= 0) {
    echo json_encode(["error" => "Invalid customer keys"]);
    exit;
}

if ($primaryCustomer === $mergeCustomer) {
    echo json_encode(["error" => "Cannot merge the same customer"]);
    exit;
}

// =============================
// DB CONNECT
// =============================
$conn = new mysqli(
    PACKAGE_LOG_DB_SERVER,
    PACKAGE_LOG_DB_USER,
    PACKAGE_LOG_DB_PASS,
    PACKAGE_LOG_DB_NAME
);

if ($conn->connect_error) {
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}

// =============================
// START TRANSACTION
// =============================
$conn->begin_transaction();

try {

    // =============================
    // 1. MERGE EMAILS
    // =============================
    // Move emails but avoid duplicates
    $sql = "
        INSERT INTO customer_email (customer_key, email, `primary`)
        SELECT ?, ce.email, NULL
        FROM customer_email ce
        WHERE ce.customer_key = ?
        AND NOT EXISTS (
            SELECT 1 FROM customer_email ce2
            WHERE ce2.customer_key = ?
            AND ce2.email = ce.email
        )
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iii", $primaryCustomer, $mergeCustomer, $primaryCustomer);
    $stmt->execute();
    $stmt->close();

    // =============================
    // 2. MERGE ADDRESSES
    // =============================
    $sql = "
        INSERT INTO customer_addresses (
            customer_key, address1, address2, city, state, zip, country, is_primary
        )
        SELECT 
            ?, address1, address2, city, state, zip, country, NULL
        FROM customer_addresses ca
        WHERE ca.customer_key = ?
        AND NOT EXISTS (
            SELECT 1 FROM customer_addresses ca2
            WHERE ca2.customer_key = ?
            AND ca2.address1 = ca.address1
            AND IFNULL(ca2.address2,'') = IFNULL(ca.address2,'')
            AND ca2.city = ca.city
            AND ca2.state = ca.state
            AND ca2.zip = ca.zip
            AND ca2.country = ca.country
        )
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iii", $primaryCustomer, $mergeCustomer, $primaryCustomer);
    $stmt->execute();
    $stmt->close();

    // =============================
    // 3. MERGE CUSTOMER_MAILBOXES
    // =============================
    $sql = "
        INSERT INTO customer_mailboxes (
            customer_key, mailbox_key, agent_key, `primary`,
            date_open, date_closed, ps1583_uploaded, ps1583_location,
            articles_inc_uploaded, articles_inc_location,
            id_one, id_one_type, id_two, id_two_type,
            payment_frequency_mo, payment_intro_mo, payment_profile, payment_subscriptionid
        )
        SELECT 
            ?, mailbox_key, agent_key, `primary`,
            date_open, date_closed, ps1583_uploaded, ps1583_location,
            articles_inc_uploaded, articles_inc_location,
            id_one, id_one_type, id_two, id_two_type,
            payment_frequency_mo, payment_intro_mo, payment_profile, payment_subscriptionid
        FROM customer_mailboxes cm
        WHERE cm.customer_key = ?
        AND NOT EXISTS (
            SELECT 1 FROM customer_mailboxes cm2
            WHERE cm2.customer_key = ?
            AND cm2.mailbox_key = cm.mailbox_key
        )
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iii", $primaryCustomer, $mergeCustomer, $primaryCustomer);
    $stmt->execute();
    $stmt->close();

    // =============================
    // 4. MERGE PHONE NUMBERS
    // =============================
    $sql = "
        INSERT INTO customer_phone (customer_key, phone, dnd)
        SELECT ?, phone, dnd
        FROM customer_phone cp
        WHERE cp.customer_key = ?
        AND NOT EXISTS (
            SELECT 1 FROM customer_phone cp2
            WHERE cp2.customer_key = ?
            AND cp2.phone = cp.phone
        )
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iii", $primaryCustomer, $mergeCustomer, $primaryCustomer);
    $stmt->execute();
    $stmt->close();

    // =============================
    // 5. DELETE MERGED CUSTOMER DATA
    // =============================
    // Delete children first (FK safe)
    $conn->query("DELETE FROM customer_email WHERE customer_key = $mergeCustomer");
    $conn->query("DELETE FROM customer_addresses WHERE customer_key = $mergeCustomer");
    $conn->query("DELETE FROM customer_mailboxes WHERE customer_key = $mergeCustomer");
    $conn->query("DELETE FROM customer_phone WHERE customer_key = $mergeCustomer");

    // =============================
    // 6. DELETE CUSTOMER RECORD
    // =============================
    $conn->query("DELETE FROM customers WHERE customer_key = $mergeCustomer");

    // =============================
    // COMMIT
    // =============================
    $conn->commit();

    echo json_encode(["success" => true]);

} catch (Exception $e) {

    $conn->rollback();

    echo json_encode([
        "error" => "Merge failed",
        "details" => $e->getMessage()
    ]);
}

$conn->close();