<?php
session_start();
header('Content-Type: application/json');
require_once("definitions.php");

// Get store_key from session
$store_key = $_SESSION['storekey'] ?? 0;
if ($store_key <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid store key']);
    exit;
}

// Validate POST inputs
$customer_key = isset($_POST['customer_key']) ? intval($_POST['customer_key']) : 0;
$firstname = trim($_POST['firstname'] ?? '');
$lastname = trim($_POST['lastname'] ?? '');
$alias = trim($_POST['alias'] ?? '');
$email = trim($_POST['email'] ?? '');
$business = isset($_POST['business']) && $_POST['business'] == '2' ? 2 : 1;

if ($customer_key <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid customer key']);
    exit;
}

if ($firstname === '') {
    echo json_encode(['success' => false, 'message' => 'First name is required']);
    exit;
}

if ($lastname === '') {
    echo json_encode(['success' => false, 'message' => 'Last name is required']);
    exit;
}

// Connect to DB
$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(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Verify that customer belongs to the store (via mailbox join)
$check_sql = "SELECT c.customer_key FROM customers c
              INNER JOIN customer_mailboxes cm ON cm.customer_key = c.customer_key
              INNER JOIN mailboxes m ON m.mailbox_key = cm.mailbox_key
              WHERE c.customer_key = ? AND m.store_key = ? LIMIT 1";
$check_stmt = $conn->prepare($check_sql);
if (!$check_stmt) {
    echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
    $conn->close();
    exit;
}
$check_stmt->bind_param("ii", $customer_key, $store_key);
$check_stmt->execute();
$check_stmt->store_result();
if ($check_stmt->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Customer not found or no permission']);
    $check_stmt->close();
    $conn->close();
    exit;
}
$check_stmt->close();

// Begin transaction
$conn->begin_transaction();

try {
    // Update customers table
    $update_customer_sql = "UPDATE customers SET firstname = ?, lastname = ?, alias = ?, business = ? WHERE customer_key = ?";
    $stmt = $conn->prepare($update_customer_sql);
    if (!$stmt) {
        throw new Exception('Prepare failed (customers): ' . $conn->error);
    }
    $stmt->bind_param("sssii", $firstname, $lastname, $alias, $business, $customer_key);
    if (!$stmt->execute()) {
        throw new Exception('Execute failed (customers): ' . $stmt->error);
    }
    $stmt->close();

    // Update or insert primary email in customer_email table
    // Check if primary email record exists
    $email_check_sql = "SELECT email_key FROM customer_email WHERE customer_key = ? AND primary = 1 LIMIT 1";
    $stmt = $conn->prepare($email_check_sql);
    if (!$stmt) {
        throw new Exception('Prepare failed (email check): ' . $conn->error);
    }
    $stmt->bind_param("i", $customer_key);
    $stmt->execute();
    $stmt->store_result();
    $has_primary_email = $stmt->num_rows > 0;
    $stmt->bind_result($email_key);
    $stmt->fetch();
    $stmt->close();

    if ($email === '') {
        // If email empty, delete primary email record if exists
        if ($has_primary_email) {
            $del_stmt = $conn->prepare("DELETE FROM customer_email WHERE email_key = ?");
            if (!$del_stmt) {
                throw new Exception('Prepare failed (email delete): ' . $conn->error);
            }
            $del_stmt->bind_param("i", $email_key);
            if (!$del_stmt->execute()) {
                throw new Exception('Execute failed (email delete): ' . $del_stmt->error);
            }
            $del_stmt->close();
        }
    } else {
        if ($has_primary_email) {
            // Update existing primary email
            $update_email_sql = "UPDATE customer_email SET email = ? WHERE email_key = ?";
            $stmt = $conn->prepare($update_email_sql);
            if (!$stmt) {
                throw new Exception('Prepare failed (email update): ' . $conn->error);
            }
            $stmt->bind_param("si", $email, $email_key);
            if (!$stmt->execute()) {
                throw new Exception('Execute failed (email update): ' . $stmt->error);
            }
            $stmt->close();
        } else {
            // Insert new primary email
            $insert_email_sql = "INSERT INTO customer_email (customer_key, email, primary) VALUES (?, ?, 1)";
            $stmt = $conn->prepare($insert_email_sql);
            if (!$stmt) {
                throw new Exception('Prepare failed (email insert): ' . $conn->error);
            }
            $stmt->bind_param("is", $customer_key, $email);
            if (!$stmt->execute()) {
                throw new Exception('Execute failed (email insert): ' . $stmt->error);
            }
            $stmt->close();
        }
    }

    $conn->commit();

    echo json_encode(['success' => true, 'message' => 'Customer updated successfully']);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Update failed: ' . $e->getMessage()]);
}

$conn->close();