<?php

function admin_controller($controllerName){
  $controllerName = $controllerName;
  return PATH.'/admin/controller/'.$controllerName.'.php';
}

function admin_view($viewName){
  $viewName = $viewName;
  return PATH.'/admin/views/'.$viewName.'.php';
}

function servicePackageType($type){
  switch ($type) {
    case '1':
      return "Default";
      break;
    case '2':
      return "Package";
      break;
    case '3':
      return "Special comments";
      break;
    case '4':
      return "Package comments";
      break;
    default:
      return "Subscriptions";
      break;
  } 
}

/**
 * Abu Shehma Bhai, Ye naya function hai jo WhatsApp Channel par message bhejega
 * aur Updates table mein history record karega.
 */
function logAndBroadcastUpdate($service_id, $service_name, $old_p, $new_p) {
    global $conn;
    
    // 1. Admin Updates Table (Original panel history)
    $msg = "Service price updated: #$service_id - $service_name | Old: ₹$old_p | New: ₹$new_p";
    $insert = $conn->prepare("INSERT INTO updates SET service_id=:id, action=:msg, date=:date");
    $insert->execute([
        'id'   => $service_id, 
        'msg'  => $msg, 
        'date' => date('Y-m-d H:i:s')
    ]);

    // 2. WhatsApp Price Logs Table (Naya dashboard jo humne banaya)
    $log = $conn->prepare("INSERT INTO whatsapp_price_logs SET service_id=:id, service_name=:name, old_price=:old, new_price=:new, date=:date");
    $log->execute([
        'id'   => $service_id, 
        'name' => $service_name, 
        'old'  => $old_p, 
        'new'  => $new_p, 
        'date' => date('Y-m-d H:i:s')
    ]);

    // 3. MPWA Channel API Call
    $wa = $conn->query("SELECT * FROM whatsapp_broadcast_settings WHERE id='1'")->fetch(PDO::FETCH_ASSOC);
    
    if($wa && !empty($wa['mpwa_api_key'])){
        $status = ($new_p < $old_p) ? "✅ Price Dropped!" : "📈 Price Updated";
        $text = "*$status*\n\n";
        $text .= "*Service:* $service_name (ID: $service_id)\n";
        $text .= "*Old Price:* ₹".round($old_p, 2)."\n";
        $text .= "*New Price:* ₹".round($new_p, 2)."\n\n";
        $text .= "🔗 Order: alixdeal.shop";

        $post_data = json_encode([
            "api_key" => $wa['mpwa_api_key'],
            "sender"  => $wa['mpwa_sender'],
            "url"     => $wa['channel_url'],
            "message" => $text,
            "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);
    }
}