<?php
// --- CONFIGURATION ---
$bot_token = "8443153324:AAG_iRBgbU93YWPxRMaNimzzjRq06I2vf7s"; // <--- YOUR TOKEN
$db_host = "localhost";
$db_user = "spartanm_invoice";
$db_pass = "f+f%h-(};[2mwJ8?";
$db_name = "spartanm_invoice";

// --- RECEIVE DATA ---
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if (!$update) exit;

if (isset($update["message"])) {
    $message = $update["message"];
    $chat_id = $message["chat"]["id"];
    $text = $message["text"] ?? '';

    if (!$text) exit;

    // Connect to DB
    $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

    // --- SMART MERGE CHECK ---
    // Look for an invoice created by 'Telegram Import' in the last 2 minutes
    $check = $conn->query("SELECT id, full_data FROM invoices WHERE client_name = 'Telegram Import' AND created_at >= (NOW() - INTERVAL 2 MINUTE) ORDER BY id DESC LIMIT 1");
    
    $existing_id = null;
    $combined_text = $text; 

    // If a recent invoice exists, append the new text to it
    if ($check && $check->num_rows > 0) {
        $row = $check->fetch_assoc();
        $existing_id = $row['id'];
        $existing_data = json_decode($row['full_data'], true);
        
        $combined_text = $existing_data['inputData'] . "\n" . $text;
    }

    // --- RE-CALCULATE TOTAL ---
    $blocks = preg_split('/Item\s*\/\s*description/i', $combined_text);
    $grand_total = 0;
    
    foreach ($blocks as $block) {
        if (trim($block) === '') continue;
        if (preg_match('/Amount\s*-\s*(.*)/i', $block, $match)) {
            $raw_amt = $match[1];
            // Remove commas and non-numeric chars (except decimal point)
            $clean = floatval(preg_replace('/[^0-9.]/', '', $raw_amt));
            $grand_total += $clean;
        }
    }

    $formatted_total = "MYR " . number_format($grand_total, 2);

    // --- PREPARE DATA ---
    $inv_num = date("dmY");
    $inv_date = date("d/m/Y");
    $default_from = '<div class="company-name">Spartanz Management</div><div>Jalan Taman Ibu Kota</div><div>Taman Setapak Indah</div><div>53300 Kuala Lumpur</div><div>Email: ahkuan241136@gmail.com</div><div>Phone: 017-8724946</div>';
    $default_to = '<div class="label">Billed To</div><div>Chuan Sin Sdn. Bhd.</div><div>NO 1, Jalan Sitar 33/6</div><div>Seksyen 33, 40400 Shah Alam</div>';

    $full_data_payload = [
        "inputData" => $combined_text,
        "invNum" => $inv_num,
        "date" => $inv_date,
        "billTo" => $default_to,
        "from" => $default_from,
        "total" => $formatted_total
    ];
    $json_str = json_encode($full_data_payload);

    // --- UPDATE OR INSERT ---
    if ($existing_id) {
        // UPDATE existing row
        $stmt = $conn->prepare("UPDATE invoices SET total_amount = ?, full_data = ? WHERE id = ?");
        $stmt->bind_param("ssi", $formatted_total, $json_str, $existing_id);
        
        if ($stmt->execute()) {
            $reply = "🔗 <b>Merged!</b>\n💰 Total: " . $formatted_total . "\n📄 <a href='https://invoice.spartanz.info'>View Invoice</a>";
        } else {
            $reply = "❌ Update Error";
        }
    } else {
        // INSERT new row
        $stmt = $conn->prepare("INSERT INTO invoices (invoice_number, invoice_date, client_name, total_amount, full_data) VALUES (?, ?, ?, ?, ?)");
        $client_name = "Telegram Import";
        $stmt->bind_param("sssss", $inv_num, $inv_date, $client_name, $formatted_total, $json_str);
        
        if ($stmt->execute()) {
            $reply = "✅ <b>Started!</b>\n💰 Total: " . $formatted_total . "\n(Send more text to merge)";
        } else {
            $reply = "❌ Insert Error";
        }
    }

    $stmt->close();
    $conn->close();

    // --- SEND REPLY (USING cURL - THE RELIABLE METHOD) ---
    sendTelegramMessage($chat_id, $reply, $bot_token);
}

// --- HELPER FUNCTION ---
function sendTelegramMessage($chat_id, $message, $token) {
    $url = "https://api.telegram.org/bot$token/sendMessage";
    $data = [
        'chat_id' => $chat_id,
        'text' => $message,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
?>