#!/usr/bin/env python3
# Invoice VAT-gate fix: only professionals (with a VAT number) can request an invoice.
# Applies to a theme base dir passed as argv[1] (e.g. ~/staging/.../themes/halabi or ~/www/.../themes/halabi).
# Exact-match, asserts each replacement happens exactly once, backs up each file first.
import sys, os, io

base = sys.argv[1].rstrip('/')
SUFFIX = '.bak-invoice-vat-gate-20260625'

PHP_TPL = base + '/components/appointment-form/appointment-form.php'
JS      = base + '/components/appointment-form/appointment-form.js'
PHP_API = base + '/includes/systeme-io-api.php'

edits = {
 PHP_TPL: [
   # A1: VAT placeholder optional -> required
   (
"""<input type="text" id="invoice-vat" placeholder="<?= $lang === 'en' ? 'VAT number (optional)' : 'N° TVA (optionnel)' ?>">""",
"""<input type="text" id="invoice-vat" placeholder="<?= $lang === 'en' ? 'VAT number (required)' : 'N° TVA (obligatoire)' ?>">"""
   ),
   # A2: insert professionals-only notice before the invoice-choice-warning paragraph
   (
"""            <p id="invoice-choice-warning" style="display: none; color: #EA4335; font-size: 14px; text-align: center; margin-bottom: 16px;">""",
"""            <p id="invoice-vat-required-msg" style="display: none; font-size: 13px; color: #555; text-align: center; margin-bottom: 12px;">
                <?= $lang === 'en'
                    ? 'VAT invoices are for professionals: a VAT number is required. Individuals receive a receipt issued by the office after the consultation.'
                    : 'La facture avec TVA est réservée aux professionnels : un numéro de TVA est obligatoire. Les particuliers reçoivent un reçu remis par le cabinet après la consultation.' ?>
            </p>
            <p id="invoice-choice-warning" style="display: none; color: #EA4335; font-size: 14px; text-align: center; margin-bottom: 16px;">"""
   ),
 ],
 JS: [
   # B1: VAT-gated CTA logic
   (
"""    if (invoiceYes && invoiceNo && invoiceCheckbox) {
        invoiceYes.addEventListener('change', function() {
            invoiceCheckbox.checked = true;
            invoiceCheckbox.dispatchEvent(new Event('change'));
            enablePaymentButtons();
        });
        invoiceNo.addEventListener('change', function() {
            invoiceCheckbox.checked = false;
            invoiceCheckbox.dispatchEvent(new Event('change'));
            enablePaymentButtons();
        });
    }""",
"""    // CTA buttons gated until invoice choice resolved - "Oui" requires a VAT number (professionals only)
    var ctaButtons = ['stripe-pay-btn', 'bank-transfer-toggle-btn', 'bank-transfer-confirm-btn']
        .map(function(id) { return document.getElementById(id); })
        .filter(Boolean);
    function disablePaymentButtons() {
        ctaButtons.forEach(function(btn) {
            btn.classList.add('payment-btn-disabled');
            btn.style.opacity = '0.5';
            btn.style.pointerEvents = 'none';
        });
    }
    var vatInput = document.getElementById('invoice-vat');
    var vatRequiredMsg = document.getElementById('invoice-vat-required-msg');
    function applyInvoiceGate() {
        if (!(invoiceYes && invoiceYes.checked)) return;
        var vat = (vatInput && vatInput.value.trim()) || '';
        if (vat) { enablePaymentButtons(); } else { disablePaymentButtons(); }
    }
    if (vatInput) vatInput.addEventListener('input', applyInvoiceGate);
    if (invoiceYes && invoiceNo && invoiceCheckbox) {
        invoiceYes.addEventListener('change', function() {
            invoiceCheckbox.checked = true;
            invoiceCheckbox.dispatchEvent(new Event('change'));
            if (vatRequiredMsg) vatRequiredMsg.style.display = 'block';
            applyInvoiceGate();
        });
        invoiceNo.addEventListener('change', function() {
            invoiceCheckbox.checked = false;
            invoiceCheckbox.dispatchEvent(new Event('change'));
            if (vatRequiredMsg) vatRequiredMsg.style.display = 'none';
            enablePaymentButtons();
        });
    }"""
   ),
   # B2: only carry FACTURE in client_reference_id when a VAT number is present
   (
"""            if (invoiceCheckbox && invoiceCheckbox.checked && (billingName || company || vat)) {
                refParts.push('FACTURE|' + (billingName || company) + '|' + vat);
            }""",
"""            if (invoiceCheckbox && invoiceCheckbox.checked && vat.trim()) {
                refParts.push('FACTURE|' + (billingName || company) + '|' + vat);
            }"""
   ),
 ],
 PHP_API: [
   # C1: handle_payment_tag - require VAT for the invoice block
   (
"""        // Invoice: write billing fields to S.io BEFORE adding the tag
        if (!empty($_POST['invoice_requested'])) {""",
"""        // Invoice: write billing fields to S.io BEFORE adding the tag - professionals only (VAT required)
        if (!empty($_POST['invoice_requested']) && trim($_POST['invoice_vat'] ?? '') !== '') {"""
   ),
   # C2: handle_bank_transfer_confirm - require VAT for has_invoice (field + tag)
   (
"""        $has_invoice = !empty($_POST['has_invoice']);""",
"""        $has_invoice = !empty($_POST['has_invoice']) && trim($_POST['invoice_vat'] ?? '') !== '';"""
   ),
   # C3: handle_save_invoice - only add invoice_asked tag when VAT present
   (
"""        // Add invoice_asked tag AFTER fields are saved
        $this->add_tag($contact_id, 'invoice_asked');
        error_log('[Systeme.io] save_invoice — invoice_asked tag added for contact ' . $contact_id);""",
"""        // Add invoice_asked tag AFTER fields are saved - professionals only (VAT required)
        if (trim($vat) !== '') {
            $this->add_tag($contact_id, 'invoice_asked');
            error_log('[Systeme.io] save_invoice — invoice_asked tag added for contact ' . $contact_id);
        } else {
            error_log('[Systeme.io] save_invoice — no VAT, invoice_asked NOT added for contact ' . $contact_id);
        }"""
   ),
 ],
}

for path, repls in edits.items():
    if not os.path.exists(path):
        print('MISSING FILE:', path); sys.exit(2)
    with io.open(path, encoding='utf-8') as f:
        txt = f.read()
    orig = txt
    for old, new in repls:
        c = txt.count(old)
        if c != 1:
            print('ABORT: anchor count %d (expected 1) in %s for snippet:\n   %s' % (c, path, old[:80]))
            sys.exit(3)
        txt = txt.replace(old, new)
    # backup then write
    with io.open(path + SUFFIX, 'w', encoding='utf-8') as f:
        f.write(orig)
    with io.open(path, 'w', encoding='utf-8') as f:
        f.write(txt)
    print('PATCHED:', os.path.basename(path), '(%d edits, backup %s)' % (len(repls), os.path.basename(path)+SUFFIX))

print('ALL PATCHES APPLIED OK')
