<?php

/**

 * Storefront customer profile for door configurator flow.

 * GET  ?choices=1  → dropdown options from Shopify metafield definitions (omni_signups)

 * POST JSON: email, first_name, last_name?, company?, address?, city?, zip, phone, you_are?, how_did_you_hear?

 */

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

ini_set('display_errors', '0');



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

header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

header('Access-Control-Allow-Headers: Content-Type');

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

$allowed_origins = [

    'https://shopify.vintagedoors.com',

    'https://vintagedoors.com',

    'https://rice-123.myshopify.com',

    'https://vintage.espirevox.com',

];

if (in_array($origin, $allowed_origins, true)) {

    header('Access-Control-Allow-Origin: ' . $origin);

} else {

    header('Access-Control-Allow-Origin: *');

}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {

    http_response_code(204);

    exit;

}



$configPath = __DIR__ . '/../config.php';

if (!is_file($configPath)) {

    $configPath = __DIR__ . '/../admin/config.php';

}

if (!is_file($configPath)) {

    http_response_code(500);

    echo json_encode(['success' => false, 'error' => 'Config not found']);

    exit;

}

require_once $configPath;



if (!defined('SHOPIFY_SHOP') || !defined('SHOPIFY_ACCESS_TOKEN') || SHOPIFY_SHOP === '' || SHOPIFY_ACCESS_TOKEN === '') {

    http_response_code(500);

    echo json_encode(['success' => false, 'error' => 'Shopify API not configured']);

    exit;

}



$apiVersion = defined('SHOPIFY_API_VERSION') && SHOPIFY_API_VERSION !== '' ? SHOPIFY_API_VERSION : '2024-10';

$gqlUrl = 'https://' . SHOPIFY_SHOP . '/admin/api/' . $apiVersion . '/graphql.json';



function shopify_gql_request($url, $query, $variables) {

    global $gqlUrl;

    $ch = curl_init($gqlUrl);

    curl_setopt_array($ch, [

        CURLOPT_POST           => true,

        CURLOPT_POSTFIELDS     => json_encode(['query' => $query, 'variables' => $variables]),

        CURLOPT_RETURNTRANSFER => true,

        CURLOPT_HTTPHEADER     => [

            'Content-Type: application/json',

            'X-Shopify-Access-Token: ' . SHOPIFY_ACCESS_TOKEN,

        ],

        CURLOPT_TIMEOUT        => 30,

    ]);

    $response = curl_exec($ch);

    $err = curl_error($ch);

    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($err) {

        return ['ok' => false, 'error' => 'Shopify request failed: ' . $err, 'http' => 500];

    }

    $data = json_decode($response, true);

    if ($code < 200 || $code >= 300) {

        return ['ok' => false, 'error' => 'Shopify HTTP ' . $code, 'http' => $code, 'raw' => $response];

    }

    if (!empty($data['errors'])) {

        $msg = is_array($data['errors']) ? json_encode($data['errors']) : (string)$data['errors'];

        return ['ok' => false, 'error' => $msg, 'http' => 500];

    }

    return ['ok' => true, 'data' => $data['data'] ?? []];

}



function parse_metafield_choices(array $validations) {

    foreach ($validations as $v) {

        if (!is_array($v)) {

            continue;

        }

        $name = isset($v['name']) ? (string)$v['name'] : '';

        if ($name !== 'choices') {

            continue;

        }

        $raw = $v['value'] ?? '';

        if (is_array($raw)) {

            return array_values(array_filter(array_map('strval', $raw)));

        }

        $decoded = json_decode((string)$raw, true);

        if (is_array($decoded)) {

            return array_values(array_filter(array_map('strval', $decoded)));

        }

    }

    return [];

}



function fetch_omni_signup_field_definitions() {

    $query = <<<'GQL'

query omniSignupMetafieldDefs($namespace: String!) {

  metafieldDefinitions(first: 20, ownerType: CUSTOMER, namespace: $namespace) {

    edges {

      node {

        key

        type { name }

        validations { name value }

      }

    }

  }

}

GQL;

    $res = shopify_gql_request(null, $query, ['namespace' => 'omni_signups']);

    if (!$res['ok']) {

        return ['ok' => false, 'error' => $res['error']];

    }

    $out = [

        'you_are' => ['choices' => [], 'type' => 'single_line_text_field'],

        'how_did_you_hear' => ['choices' => [], 'type' => 'single_line_text_field'],

    ];

    $keyMap = [

        'you-are' => 'you_are',

        'how-did-you-hear-about-us' => 'how_did_you_hear',

    ];

    $edges = $res['data']['metafieldDefinitions']['edges'] ?? [];

    foreach ($edges as $edge) {

        $node = $edge['node'] ?? [];

        $key = (string)($node['key'] ?? '');

        if (!isset($keyMap[$key])) {

            continue;

        }

        $slot = $keyMap[$key];

        $out[$slot]['choices'] = parse_metafield_choices($node['validations'] ?? []);

        $typeName = $node['type']['name'] ?? 'single_line_text_field';

        if (is_string($typeName) && $typeName !== '') {

            $out[$slot]['type'] = $typeName;

        }

    }

    return ['ok' => true, 'fields' => $out];

}



if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['choices'])) {

    $defs = fetch_omni_signup_field_definitions();

    if (!$defs['ok']) {

        http_response_code(500);

        echo json_encode(['success' => false, 'error' => $defs['error']]);

        exit;

    }

    echo json_encode([

        'success' => true,

        'you_are' => $defs['fields']['you_are']['choices'],

        'how_did_you_hear' => $defs['fields']['how_did_you_hear']['choices'],

        'types' => [

            'you_are' => $defs['fields']['you_are']['type'],

            'how_did_you_hear' => $defs['fields']['how_did_you_hear']['type'],

        ],

    ]);

    exit;

}



if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    http_response_code(405);

    echo json_encode(['success' => false, 'error' => 'Method not allowed']);

    exit;

}



$raw = file_get_contents('php://input');

$body = $raw ? json_decode($raw, true) : null;

if (!is_array($body)) {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'Invalid JSON body']);

    exit;

}



$email = trim((string)($body['email'] ?? ''));

$firstName = trim((string)($body['first_name'] ?? ''));

$lastName = trim((string)($body['last_name'] ?? ''));

$company = trim((string)($body['company'] ?? ''));

$address = trim((string)($body['address'] ?? ''));

$city = trim((string)($body['city'] ?? ''));

$zip = trim((string)($body['zip'] ?? ''));

$phone = trim((string)($body['phone'] ?? ''));

$youAre = trim((string)($body['you_are'] ?? ''));

$howDidYouHear = trim((string)($body['how_did_you_hear'] ?? ''));



if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'Valid email is required']);

    exit;

}

if ($firstName === '') {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'First name is required']);

    exit;

}

if ($zip === '') {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'Zip / postal code is required']);

    exit;

}

if ($phone === '') {

    http_response_code(400);

    echo json_encode(['success' => false, 'error' => 'Telephone is required']);

    exit;

}



$defs = fetch_omni_signup_field_definitions();

$youAreType = 'single_line_text_field';

$howType = 'single_line_text_field';

if ($defs['ok']) {

    $youAreType = $defs['fields']['you_are']['type'] ?: $youAreType;

    $howType = $defs['fields']['how_did_you_hear']['type'] ?: $howType;

    if ($youAre !== '' && !empty($defs['fields']['you_are']['choices']) && !in_array($youAre, $defs['fields']['you_are']['choices'], true)) {

        http_response_code(400);

        echo json_encode(['success' => false, 'error' => 'Invalid selection for You are a']);

        exit;

    }

    if ($howDidYouHear !== '' && !empty($defs['fields']['how_did_you_hear']['choices']) && !in_array($howDidYouHear, $defs['fields']['how_did_you_hear']['choices'], true)) {

        http_response_code(400);

        echo json_encode(['success' => false, 'error' => 'Invalid selection for How did you hear about us?']);

        exit;

    }

}



$findQuery = <<<'GQL'

query findCustomerByEmail($query: String!) {

  customers(first: 1, query: $query) {

    edges { node { id email } }

  }

}

GQL;

$find = shopify_gql_request($gqlUrl, $findQuery, ['query' => 'email:' . $email]);

if (!$find['ok']) {

    http_response_code($find['http'] ?? 500);

    echo json_encode(['success' => false, 'error' => $find['error']]);

    exit;

}

$edges = $find['data']['customers']['edges'] ?? [];

if (empty($edges[0]['node']['id'])) {

    http_response_code(404);

    echo json_encode(['success' => false, 'error' => 'Customer not found for this email']);

    exit;

}

$customerGid = $edges[0]['node']['id'];



$metafields = [];

if ($youAre !== '') {

    $metafields[] = [

        'namespace' => 'omni_signups',

        'key'       => 'you-are',

        'type'      => $youAreType,

        'value'     => $youAre,

    ];

}

if ($howDidYouHear !== '') {

    $metafields[] = [

        'namespace' => 'omni_signups',

        'key'       => 'how-did-you-hear-about-us',

        'type'      => $howType,

        'value'     => $howDidYouHear,

    ];

}



$addressRow = [
    'zip'       => $zip,
    'phone'     => $phone,
    'firstName' => $firstName,
    'lastName'  => $lastName,
];
if ($company !== '') {
    $addressRow['company'] = $company;
}
if ($address !== '') {
    $addressRow['address1'] = $address;
}
if ($city !== '') {
    $addressRow['city'] = $city;
}

$input = [
    'id'        => $customerGid,
    'firstName' => $firstName,
    'lastName'  => $lastName,
    'phone'     => $phone,
    'addresses' => [$addressRow],
];

if (!empty($metafields)) {

    $input['metafields'] = $metafields;

}



$updateMutation = <<<'GQL'

mutation customerProfileUpdate($input: CustomerInput!) {

  customerUpdate(input: $input) {

    customer { id email firstName lastName phone }

    userErrors { field message }

  }

}

GQL;

$update = shopify_gql_request($gqlUrl, $updateMutation, ['input' => $input]);

if (!$update['ok']) {

    http_response_code($update['http'] ?? 500);

    echo json_encode(['success' => false, 'error' => $update['error']]);

    exit;

}

$userErrors = $update['data']['customerUpdate']['userErrors'] ?? [];

if (!empty($userErrors)) {

    http_response_code(400);

    echo json_encode([

        'success' => false,

        'error'   => implode('; ', array_column($userErrors, 'message')),

    ]);

    exit;

}



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

