import os

file_path = r"C:\Users\ahmed\Downloads\smartlogicchatbot\bot.php"

with open(file_path, "r", encoding="utf-8") as f:
    content = f.read()

# 1. Modify notifySalesOnNewChat to save the assigned number
target1 = """        if ($assignedNumber) {
            @sendInternalAlert($assignedNumber, $msg);
            logMessage("Sales notified for new chat via Round-Robin: $assignedNumber", 'CONVERSION', $phone);
        }"""
replacement1 = """        if ($assignedNumber) {
            @sendInternalAlert($assignedNumber, $msg);
            logMessage("Sales notified for new chat via Round-Robin: $assignedNumber", 'CONVERSION', $phone);
            $customer['assigned_sales_number'] = $assignedNumber;
        }"""
if target1 in content:
    content = content.replace(target1, replacement1)
    print("Modified notifySalesOnNewChat successfully.")
else:
    print("Failed to find target1.")

# 2. Modify sendProposalToCustomer to forward the PDF to the sales rep
target2 = """    $caption = "تم تجهيز عرض مبدئي من Smart Logic. راجعه وأخبرني هل نحدد موعد بدء التنفيذ؟";
    $sent = sendWhatsAppDocument($phone, $mediaId, basename($filePath), $caption);
    if (!$sent) {
        throw new RuntimeException('WhatsApp document send failed.');
    }

    $customer['proposal_sent_at'] = time();"""

replacement2 = """    $caption = "تم تجهيز عرض مبدئي من Smart Logic. راجعه وأخبرني هل نحدد موعد بدء التنفيذ؟";
    $sent = sendWhatsAppDocument($phone, $mediaId, basename($filePath), $caption);
    if (!$sent) {
        throw new RuntimeException('WhatsApp document send failed.');
    }

    // Forward the PDF to the assigned sales rep
    $salesNumber = $customer['assigned_sales_number'] ?? null;
    if (!$salesNumber && !empty($config['sales_notify_numbers'])) {
        $nums = (array)$config['sales_notify_numbers'];
        $salesNumber = $nums[0]; // fallback
    }
    if ($salesNumber) {
        $salesCaption = "تم إرسال عرض السعر للعميل +$phone. ملف العرض مرفق للمراجعة.";
        sendWhatsAppDocument($salesNumber, $mediaId, basename($filePath), $salesCaption);
        logMessage("Proposal PDF forwarded to sales rep $salesNumber", 'INFO', $phone);
    }

    $customer['proposal_sent_at'] = time();"""

if target2 in content:
    content = content.replace(target2, replacement2)
    print("Modified sendProposalToCustomer successfully.")
else:
    print("Failed to find target2.")

with open(file_path, "w", encoding="utf-8") as f:
    f.write(content)

