<?php
/**
 * Admin: update Shopify customer, then sync HubSpot contact (no local PII storage).
 */
require __DIR__ . '/config.php';
require_once __DIR__ . '/includes/admin_shopify_frame_headers.php';
if (is_file(__DIR__ . '/hubspot-config.php')) {
    require_once __DIR__ . '/hubspot-config.php';
}
require_once __DIR__ . '/admin_config_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: folders.php');
    exit;
}

$folder_id = isset($_POST['folder_id']) ? (int) $_POST['folder_id'] : 0;
$return_to = isset($_POST['return_to']) ? trim((string) $_POST['return_to']) : 'folders';
$firstName = trim((string) ($_POST['customer_first_name'] ?? ''));
$lastName = trim((string) ($_POST['customer_last_name'] ?? ''));
$phone = trim((string) ($_POST['customer_phone'] ?? ''));
$billing = trim((string) ($_POST['billing_address'] ?? ''));

function folder_contact_redirect($return_to, $folder_id, $query = '') {
    $redirect = $return_to === 'folder_detail'
        ? 'folder_detail.php?id=' . $folder_id
        : 'folders.php';
    if ($query !== '') {
        $sep = strpos($redirect, '?') !== false ? '&' : '?';
        $redirect .= $sep . $query;
    }
    header('Location: ' . $redirect);
    //;
}

if ($folder_id <= 0) {
    header('Location: folders.php?contact_error=' . rawurlencode('Invalid project.'));
    exit;
}

$stmt = $pdo->prepare('SELECT id, customer_email FROM door_folders WHERE id = ?');
$stmt->execute([$folder_id]);
$folder = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$folder) {
    header('Location: folders.php?contact_error=' . rawurlencode('Project not found.'));
    exit;
}

$email = trim((string) ($folder['customer_email'] ?? ''));
if ($email === '') {
    folder_contact_redirect($return_to, $folder_id, 'contact_error=' . rawurlencode('This project has no customer email yet.') . '&contact_open=' . $folder_id);
}

$fields = [
    'customer_first_name' => $firstName,
    'customer_last_name' => $lastName,
    'customer_phone' => $phone,
    'billing_address' => $billing,
];

$shopify = admin_upsert_shopify_customer($email, $fields);
if (!$shopify['success']) {
    folder_contact_redirect(
        $return_to,
        $folder_id,
        'contact_error=' . rawurlencode($shopify['error']) . '&contact_open=' . $folder_id
    );
}

$hs = admin_upsert_hubspot_contact($email, $fields);
if (!$hs['success']) {
    folder_contact_redirect(
        $return_to,
        $folder_id,
        'contact_error=' . rawurlencode('Shopify saved, but HubSpot sync failed: ' . $hs['error']) . '&contact_open=' . $folder_id
    );
}

folder_contact_redirect($return_to, $folder_id, 'contact_saved=1&contact_open=' . $folder_id);
