<?php
include_once("../config.php");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!isset($_SESSION['client_id']) || empty($_SESSION['client_id']) || !is_numeric($_SESSION['client_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'User not authenticated or session expired']);
        exit;
    }
    // Read JSON input
    $json = file_get_contents("php://input");
    $requestData = json_decode($json, true);

    // Validate data structure
    if (!isset($requestData["contacts"]) || !isset($requestData["importAction"])) {
        echo json_encode(["error" => "Invalid or missing data."]);
        exit;
    }

    $importAction = $requestData["importAction"]; // "append", "update_records", or "skip_records"
    $dataArray = $requestData["contacts"];

    // Ensure $db is correctly set
    global $db; // Assuming $db is defined in config.php

    foreach ($dataArray as $data) {
        // Extract main fields
        $name = trim($data["name"] ?? "");
        $countryCode = trim($data["countrycode"] ?? "");
        $phone = trim($data["phone"] ?? "");

        if (empty($name) || empty($phone)) {
            continue; // Skip rows with missing required fields
        }

        $source = "Watify"; // Static source value
        $client_id = $_SESSION['client_id']; // Static client ID (assuming it's a string)


        // Check if contact already exists
        $stmt = $db->prepare("SELECT id FROM contacts WHERE phone = ?");
        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $stmt->store_result();
        $contactExists = $stmt->num_rows > 0;
        $stmt->bind_result($contactId);
        $stmt->fetch();
        $stmt->close();

        if ($importAction === "skip_records" && $contactExists) {
            continue; // Skip existing contacts
        }

        if ($importAction === "update_records" && $contactExists) {
            // Update existing contact
            $stmt = $db->prepare("UPDATE contacts SET name = ?, country_code = ?, source = ? WHERE phone = ?");
            $stmt->bind_param("ssss", $name, $countryCode, $source, $phone);
            $stmt->execute();
        } else if (!$contactExists) {
            // Insert new contact
            $stmt = $db->prepare("INSERT INTO contacts (client_id, name, country_code, phone, source) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $client_id, $name, $countryCode, $phone, $source);
            $stmt->execute();
            $contactId = $db->insert_id; // Get last inserted contact ID
        }

        // Insert or update contact attributes
        foreach ($data as $attri_name => $attri_value) {
            if (!in_array($attri_name, ["name", "countrycode", "phone"])) {
                // Check if attribute already exists
                $stmt = $db->prepare("SELECT id FROM contact_attributes WHERE contact_id = ? AND attri_name = ?");
                $stmt->bind_param("is", $contactId, $attri_name);
                $stmt->execute();
                $stmt->store_result();
                $attributeExists = $stmt->num_rows > 0;
                $stmt->close();

                if ($attributeExists) {
                    // Update existing attribute
                    $stmt = $db->prepare("UPDATE contact_attributes SET attri_value = ? WHERE contact_id = ? AND attri_name = ?");
                    $stmt->bind_param("sis", $attri_value, $contactId, $attri_name);
                } else {
                    // Insert new attribute
                    $stmt = $db->prepare("INSERT INTO contact_attributes (client_id, contact_id, attri_name, attri_value) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("siss", $client_id, $contactId, $attri_name, $attri_value);
                }
                $stmt->execute();
            }
        }
    }
    echo json_encode(["message" => "Data imported successfully!"]);
} else {
    echo json_encode(["error" => "Invalid request."]);
}
