<?php
$title .= "WA Channel Ultimate Manager";

// 1. WhatsApp API की सेटिंग्स लोड करना
$wa_settings = $conn->query("SELECT * FROM whatsapp_broadcast_settings WHERE id='1'")->fetch(PDO::FETCH_ASSOC);

/**
 * 🔥 [ADVANCE FIX] 
 * 'updates' और 'whatsapp_price_logs' का डेटा UNION के साथ।
 * इससे पुरानी एडमिन हिस्ट्री और नए मैनुअल मैसेज एक साथ दिखेंगे।
 */
$price_logs = $conn->query("
    (SELECT u_id as id, service_id, action as service_name, description as price_info, date, 'AUTO' as type FROM updates)
    UNION 
    (SELECT id, service_id, service_name, CONCAT('₹', old_price, ' -> ₹', new_price) as price_info, date, 'MANUAL' as type FROM whatsapp_price_logs)
    ORDER BY date DESC LIMIT 100
")->fetchAll(PDO::FETCH_ASSOC);

// --- AJAX Magic (बिना पेज रिफ्रेश के लिए) ---
if( isset($_POST['is_ajax']) ){
    $api_key = $wa_settings['mpwa_api_key'];
    $sender  = $wa_settings['mpwa_sender'];
    $url     = $wa_settings['channel_url'];
    $footer  = $wa_settings['footer_text'];

    // Action: Test, Send Message या Smart Resend
    if($_POST['action'] == "test" || $_POST['action'] == "send" || $_POST['action'] == "send_formatted"){
        
        if($_POST['action'] == "send_formatted"){
            $msg = $_POST['manual_msg'];
            
            /**
             * 🛠️ [SMART ROUNDING LOGIC]
             * अगर मैसेज में लंबे पॉइंट्स वाले नंबर्स हैं (जैसे 41.1421...), 
             * तो ये उन्हें ढूंढकर केवल 2 डेसिमल (41.14) तक सीमित कर देगा।
             */
            $msg = preg_replace_callback('/(\d+\.\d{2})\d+/', function($matches) {
                return $matches[1];
            }, $msg);

        } else {
            $msg = ($_POST['action'] == "test") ? "🚀 *Test Success!* Your WhatsApp Channel is linked." : $_POST['manual_msg'];
        }
        
        $api_url = "https://ads.alixdeal.info/send-text-channel";
        $post_data = json_encode([
            "api_key" => $api_key, 
            "sender"  => $sender, 
            "url"     => $url, 
            "message" => $msg, 
            "footer"  => $footer
        ]);

        $ch = curl_init($api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        $response = curl_exec($ch);
        $res_arr = json_decode($response, true);
        curl_close($ch);

        // ✅ अगर मैनुअल मैसेज सफल रहा, तो उसे व्हाट्सएप लॉग्स में सेव करें
        if($_POST['action'] == "send" && isset($res_arr['status']) && $res_arr['status'] == true){
            $ins = $conn->prepare("INSERT INTO whatsapp_price_logs SET service_id='0', service_name='Manual Broadcast', old_price='0', new_price='0', date=:date");
            $ins->execute(['date' => date('Y-m-d H:i:s')]);
        }

        echo $response;
        exit();
    }

    // 🔥 [FIXED DELETE LOGIC] Action: Single Delete
    if($_POST['action'] == "delete_log"){
        $id = $_POST['id'];
        
        // दोनों टेबल्स से डेटा हटाने के लिए पक्का तरीका
        $del1 = $conn->prepare("DELETE FROM whatsapp_price_logs WHERE id=:id");
        $del1->execute(['id' => $id]);

        $del2 = $conn->prepare("DELETE FROM updates WHERE u_id=:id");
        $del2->execute(['id' => $id]);

        echo json_encode(["status" => true]);
        exit();
    }

    // Action: Clear All (सिर्फ व्हाट्सएप लॉग्स साफ़ करने के लिए)
    if($_POST['action'] == "clear_all"){
        $conn->query("TRUNCATE TABLE whatsapp_price_logs");
        echo json_encode(["status" => true]);
        exit();
    }
}

// --- Settings Save करना ---
if( isset($_POST['save_all']) ){
    $api    = htmlspecialchars($_POST['api']);
    $sender = htmlspecialchars($_POST['sender']);
    $url    = htmlspecialchars($_POST['url']);
    $foot   = htmlspecialchars($_POST['footer']);

    $update = $conn->prepare("UPDATE whatsapp_broadcast_settings SET mpwa_api_key=:api, mpwa_sender=:sender, channel_url=:url, footer_text=:foot WHERE id=1");
    $update->execute(['api'=>$api, 'sender'=>$sender, 'url'=>$url, 'foot'=>$foot]);
    
    header("Location: ".site_url('admin/whatsapp_settings?success=1'));
    exit();
}

require admin_view('whatsapp_settings');