<?php
/**
 * PandaDoc: create document from template.
 * Accepts quote builder payload and fills the template's pricing table.
 *
 * POST JSON:
 *   template_uuid   (required)
 *   name            (optional)
 *   recipients      (required) [ { "email", "first_name?", "last_name?", "role?" } ]
 *   pricing_table   (optional) e.g. "Pricing Table 1"
 *   section_name   (optional) e.g. "Quote Table"
 *   currency       (optional) e.g. "INR"
 *   rows            (optional) [ { "name", "description?", "qty", "price" } ] — Total = price×qty
 *   fields          (optional) { "MergeFieldName": { "value": "..." } }
 *
 * Returns: { "success": true, "id", "status", "document_link" } or { "success": false, "error" }
 */

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
ini_set('display_errors', '0');

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$configPath = dirname(__DIR__) . '/conf.php';
if (!is_file($configPath)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'config.php not found']);
    exit;
}
require $configPath;

$apiKey = defined('PANDADOC_API_KEY') ? PANDADOC_API_KEY : '';
if ($apiKey === '') {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Set PANDADOC_API_KEY in config.php']);
    exit;
}

$raw = file_get_contents('php://input');
$input = $raw && (strpos($_SERVER['CONTENT_TYPE'] ?? '', 'application/json') !== false)
    ? json_decode($raw, true)
    : null;

$useDummy = isset($_GET['dummy']) || isset($_GET['demo']);
if (!is_array($input)) {
    $input = [];
}

$input['template_uuid'] = 'bHJdsx3L836fqxRD7C4qvR';
if (!empty($input['template_uuid'])) {
  
        $input = [
            'template_uuid'  => PANDADOC_DUMMY_TEMPLATE_ID,
            'name'           => 'Quote Demo ' . date('Y-m-d H:i'),
            'pricing_table'  => 'Pricing Table 1',
            'section_name'   => 'Quote Table',
            'currency'       => 'INR',
            'recipients'     => [
                ['email' => 'client@example.com', 'first_name' => 'Jane', 'last_name' => 'Doe', 'role' => 'Client'],
            ],
            'rows' => [
                ['name' => 'Standard Installation', 'description' => 'Full install and setup', 'qty' => 1, 'price' => 499.00],
                ['name' => 'Premium Support (1 year)', 'description' => '24/7 support and updates', 'qty' => 1, 'price' => 199.00],
                ['name' => 'Extra License', 'description' => 'Additional user seat', 'qty' => 2, 'price' => 89.50],
            ],
        ];
    } else {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error'   => 'JSON body with template_uuid is required, or use ?dummy=1 with PANDADOC_DUMMY_TEMPLATE_ID set in config.php',
        ]);
        exit;
   
}

$templateUuid = 'bHJdsx3L836fqxRD7C4qvR';
$name = isset($input['name']) ? trim((string)$input['name']) : 'Quote ' . date('Y-m-d H:i');
$recipients = isset($input['recipients']) && is_array($input['recipients']) ? $input['recipients'] : [];
$fields = isset($input['fields']) && is_array($input['fields']) ? $input['fields'] : [];
$pricingTableName = isset($input['pricing_table']) ? trim((string)$input['pricing_table']) : 'Pricing Table 1';
$sectionName = isset($input['section_name']) ? trim((string)$input['section_name']) : 'Quote Table';
$currency = isset($input['currency']) ? trim((string)$input['currency']) : 'INR';
$rows = isset($input['rows']) && is_array($input['rows']) ? $input['rows'] : [];

if (empty($recipients)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'At least one recipient (email) is required']);
    exit;
}

$recipientsPayload = [];
foreach ($recipients as $r) {
    $email = isset($r['email']) ? trim((string)$r['email']) : '';
    if ($email === '') continue;
    $recipientsPayload[] = [
        'email'      => $email,
        'first_name' => isset($r['first_name']) ? trim((string)$r['first_name']) : '',
        'last_name'  => isset($r['last_name']) ? trim((string)$r['last_name']) : '',
        'role'       => isset($r['role']) ? trim((string)$r['role']) : 'Client',
    ];
}
if (empty($recipientsPayload)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'At least one valid recipient email required']);
    exit;
}

$body = [
    'name'          => $name,
    'template_uuid' => $templateUuid,
    'recipients'    => $recipientsPayload,
];
if (!empty($fields)) {
    $body['fields'] = $fields;
}

if (!empty($rows)) {
    // Template columns (merge_name): Name, Description, Price, Quantity, Total; optional SKU, Cost
    $tableRows = [];
    foreach ($rows as $row) {
        $rName = isset($row['name']) ? trim((string)$row['name']) : 'Item';
        $rDesc = isset($row['description']) ? trim((string)$row['description']) : '';
        $rQty  = isset($row['qty']) ? max(1, (int)$row['qty']) : 1;
        $rPrice = (float)($row['price'] ?? 0);
        $rTotal = round($rPrice * $rQty, 2);
        $tableRows[] = [
            'options' => ['optional' => false, 'optional_selected' => false, 'qty_editable' => false],
            'data'    => [
                'name'        => $rName,
                'description' => $rDesc,
                'price'       => round($rPrice, 2),
                'qty'         => $rQty,
            ],
        ];
    }
    $body['pricing_tables'] = [
        [
            'name'       => $pricingTableName,
           // 'data_merge' => true,
            'options'    => ['currency' => $currency],
            'sections'   => [
                ['title' => $sectionName, 'default' => true, 'rows' => $tableRows],
            ],
        ],
    ];
}

echo "<pre>";
print_r($body);
die;

$base = defined('PANDADOC_API_BASE') ? PANDADOC_API_BASE : 'https://api.pandadoc.com/public/v1';
$url = rtrim($base, '/') . '/documents';
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($body),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: API-Key ' . $apiKey,
    ],
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);

if ($curlErr) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Request failed: ' . $curlErr]);
    exit;
}

$data = json_decode($response, true);
if ($httpCode >= 200 && $httpCode < 300 && !empty($data['id'])) {
    $docLink = null;
    if (!empty($data['links'])) {
        $docLink = is_array($data['links']) ? ($data['links'][0]['href'] ?? null) : $data['links'];
    }
    echo json_encode([
        'success'       => true,
        'id'            => $data['id'],
        'status'        => $data['status'] ?? 'document.uploaded',
        'document_link' => $docLink,
    ]);
} else {
    http_response_code($httpCode >= 400 ? $httpCode : 500);
    $err = 'Unknown error';
    if (is_array($data)) {
        if (!empty($data['detail'])) $err = is_string($data['detail']) ? $data['detail'] : json_encode($data['detail']);
        elseif (!empty($data['error'])) $err = is_string($data['error']) ? $data['error'] : json_encode($data['error']);
        elseif (!empty($data['errors'])) $err = is_string($data['errors']) ? $data['errors'] : json_encode($data['errors']);
    } else {
        $err = substr((string)$response, 0, 500);
    }
    echo json_encode(['success' => false, 'error' => $err]);
}
