<?php
// Error reporting aur time limit set karein
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('max_execution_time', '1200');
set_time_limit(1200);

define("BASEPATH", TRUE);
require $_SERVER["DOCUMENT_ROOT"]."/vendor/autoload.php";
require $_SERVER["DOCUMENT_ROOT"]."/app/init.php";

$SMM_API = new SMMApi();

// 1. WhatsApp Settings load karein
$wa = $conn->query("SELECT * FROM whatsapp_broadcast_settings WHERE id='1'")->fetch(PDO::FETCH_ASSOC);

// 2. Active Providers nikalein
$SELLERS_STMT = $conn->prepare("SELECT id, api_name, api_url, api_key, currency FROM service_api WHERE api_sync=:sync");
$SELLERS_STMT->execute(["sync" => 1]);
$SELLERS_DATA = $SELLERS_STMT->fetchAll(PDO::FETCH_ASSOC);

foreach ($SELLERS_DATA as $seller) {
    $api_id = $seller["id"];
    $api_url = $seller["api_url"];
    $api_key = $seller["api_key"];
    $api_currency = $seller["currency"];

    // Is seller ki synced services nikalein
    $SERVICES_STMT = $conn->prepare("SELECT * FROM services WHERE service_api=:apITYPE AND service_sync=:sync");
    $SERVICES_STMT->execute(["apITYPE" => $api_id, "sync" => 1]);
    $SERVICES_LIST = $SERVICES_STMT->fetchAll(PDO::FETCH_ASSOC);

    if (count($SERVICES_LIST) > 0) {
        // API se data mangwayein
        $API_SERVICES_RAW = $SMM_API->action(['key' => $api_key, 'action' => 'services'], $api_url);

        if (is_array($API_SERVICES_RAW)) {
            $API_SERVICES_INDEXED = [];
            foreach ($API_SERVICES_RAW as $item) {
                if(isset($item['service'])){ $API_SERVICES_INDEXED[$item['service']] = $item; }
            }

            foreach ($SERVICES_LIST as $row) {
                $PANEL_SERVICE_ID = $row["service_id"];
                $PANEL_API_SERVICE_ID = $row["api_service"];
                $API_DETAIL_ARRAY = json_decode($row["api_detail"], true);
                
                if (isset($API_SERVICES_INDEXED[$PANEL_API_SERVICE_ID])) {
                    $API_DATA = $API_SERVICES_INDEXED[$PANEL_API_SERVICE_ID];
                    $API_SERVICE_PRICE = $API_DATA["rate"];
                    $API_SERVICE_MIN = $API_DATA["min"];
                    $API_SERVICE_MAX = $API_DATA["max"];

                    // --- PRICE UPDATE LOGIC ---
                    if ($API_DETAIL_ARRAY["rate"] != $API_SERVICE_PRICE) {
                        
                        $OLD_PANEL_PRICE = $row["service_price"]; 
                        $API_DETAIL_ARRAY["rate"] = $API_SERVICE_PRICE;
                        
                        // Database Update (JSON aur Price)
                        $conn->prepare("UPDATE services SET api_detail=? WHERE service_id=?")->execute([json_encode($API_DETAIL_ARRAY), $PANEL_SERVICE_ID]);

                        $NEW_BASE_PRICE = from_to(get_currencies_array("all"), $api_currency, $settings["site_base_currency"], $API_SERVICE_PRICE);
                        $FINAL_PRICE = $NEW_BASE_PRICE + (($row["price_profit"] / 100) * $NEW_BASE_PRICE);

                        $conn->prepare("UPDATE services SET service_price=? WHERE service_id=?")->execute([$FINAL_PRICE, $PANEL_SERVICE_ID]);

                        // Admin Panel 'Updates' Table Logic
                        $status_text = ($FINAL_PRICE < $OLD_PANEL_PRICE) ? "Price Decreased" : "Price Increased";
                        $desc = "Service rate changed from <b>$OLD_PANEL_PRICE</b> to <b>$FINAL_PRICE</b>";

                        // updates table entry
                        $ins_update = $conn->prepare("INSERT INTO updates SET service_id=:sid, action=:act, description=:desc, date=:dt");
                        $ins_update->execute(["sid" => $PANEL_SERVICE_ID, "act" => $status_text, "desc" => $desc, "dt" => date("Y-m-d H:i:s")]);

                        // sync_logs table entry
                        $conn->prepare("INSERT INTO sync_logs (service_id, api_id, action, description, date) VALUES (?, ?, ?, ?, ?)")
                             ->execute([$PANEL_SERVICE_ID, $api_id, "PRICE UPDATED", strip_tags($desc), date("Y-m-d H:i:s")]);

                        // --- WHATSAPP NOTIFICATION ---
                        if(!empty($wa['mpwa_api_key'])){
                            $s_name = $row["service_name"];
                            // Price ko 3 decimal tak round karein
                            $p_old = round($OLD_PANEL_PRICE, 3);
                            $p_new = round($FINAL_PRICE, 3);
                            
                            $wa_msg = "🔔 *ALIXDEAL PRICE UPDATE*\n\n";
                            $wa_msg .= "📦 *Service:* " . $s_name . " (#".$PANEL_SERVICE_ID.")\n";
                            $wa_msg .= "📢 *Status:* " . $status_text . "\n";
                            $wa_msg .= "💰 *Old Price:* ₹" . $p_old . "\n";
                            $wa_msg .= "✅ *New Price:* ₹" . $p_new . "\n\n";
                            $wa_msg .= "🌐 alixdeal.shop";

                            $post_data = json_encode([
                                "api_key" => $wa['mpwa_api_key'], 
                                "sender"  => $wa['mpwa_sender'],
                                "url"     => $wa['channel_url'], 
                                "message" => $wa_msg, 
                                "footer"  => $wa['footer_text']
                            ]);

                            $ch = curl_init("https://ads.alixdeal.info/send-text-channel");
                            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']);
                            curl_exec($ch);
                            curl_close($ch);
                        }
                    }

                    // --- MIN/MAX UPDATE LOGIC ---
                    if ($API_DETAIL_ARRAY["min"] != $API_SERVICE_MIN || $API_DETAIL_ARRAY["max"] != $API_SERVICE_MAX) {
                        $API_DETAIL_ARRAY["min"] = $API_SERVICE_MIN;
                        $API_DETAIL_ARRAY["max"] = $API_SERVICE_MAX;
                        $conn->prepare("UPDATE services SET api_detail=?, service_min=?, service_max=? WHERE service_id=?")
                             ->execute([json_encode($API_DETAIL_ARRAY), $API_SERVICE_MIN, $API_SERVICE_MAX, $PANEL_SERVICE_ID]);
                    }

                    // Re-enable if disabled by API earlier
                    if ($row["api_servicetype"] == 1) {
                        $conn->prepare("UPDATE services SET api_servicetype=2, service_type=2 WHERE service_id=?")->execute([$PANEL_SERVICE_ID]);
                    }

                } else {
                    // Disable if service removed from Provider
                    if ($row["api_servicetype"] == 2) {
                        $conn->prepare("UPDATE services SET api_servicetype=1, service_type=1 WHERE service_id=?")->execute([$PANEL_SERVICE_ID]);
                    }
                }
            }
        }
    }
}
echo "Full Sync with WhatsApp & Admin Updates Completed!";
?>