<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}

$title .= "New Service Control Center";

// 1. Is page ki apni exclusive settings load karna
$settings = $conn->query("SELECT * FROM whatsapp_new_service_settings WHERE id='1'")->fetch(PDO::FETCH_ASSOC);

// 2. Sari current services load karna (Taki history khali na dikhe)
$new_services = $conn->query("SELECT * FROM services ORDER BY service_id DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);

if( isset($_POST['is_ajax']) ){

    // 🎯 [REAL FIXED HOOK: DIRECT INSERTER WITHOUT REDIRECT ERROR]
    if($_POST['action'] == "add_top_service_action"){
        $service_id = isset($_POST['service_id']) ? intval($_POST['service_id']) : 0;
        
        if ($service_id > 0) {
            // Check karna ki table me duplicate insert na ho
            $check = $conn->prepare("SELECT id FROM top_services WHERE service_id = ?");
            $check->execute([$service_id]);
            
            if ($check->rowCount() == 0) {
                // Direct fresh insertion in top_services
                $insert = $conn->prepare("INSERT INTO top_services (service_id) VALUES (?)");
                if($insert->execute([$service_id])) {
                    echo json_encode(["status" => "success"]);
                } else {
                    echo json_encode(["status" => "failed"]);
                }
            } else {
                echo json_encode(["status" => "exists"]);
            }
        } else {
            echo json_encode(["status" => "error"]);
        }
        exit();
    }

    if($_POST['action'] == "save_settings"){
        $update = $conn->prepare("UPDATE whatsapp_new_service_settings SET api_key=:api, sender_number=:sender, channel_url=:url, footer_text=:footer WHERE id=1");
        $update->execute(['api' => $_POST['api'], 'sender' => $_POST['sender'], 'url' => $_POST['url'], 'footer' => $_POST['footer']]);
        echo json_encode(["status" => true]); exit();
    }

    if($_POST['action'] == "toggle_auto"){
        $conn->query("UPDATE whatsapp_new_service_settings SET auto_post='".$_POST['value']."' WHERE id=1");
        echo json_encode(["status" => true]); exit();
    }

    // --- Sending Broadcast ---
    if($_POST['action'] == "send_new_service"){
        $post_data = json_encode([
            "api_key" => $settings['api_key'], 
            "sender"  => $settings['sender_number'], 
            "url"     => $settings['channel_url'], 
            "message" => $_POST['manual_msg'], 
            "footer"  => $settings['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']);
        echo curl_exec($ch); exit();
    }
}
require admin_view('whatsapp_new_services');