<?php
require 'vendor/autoload.php';
require 'settings.php';

use Twilio\Rest\Client;

require_once __DIR__ . '/includes/db.php';
if($conn->connect_error){ die("❌ فشل الاتصال: ".$conn->connect_error); }

// وظيفة إرسال رسالة
function sendMessage($phone, $text){
    global $settings;
    $sid = $settings['twilio_sid'];
    $token = $settings['twilio_token'];
    $from = $settings['sender_number'];

    $client = new Client($sid, $token);
    try {
        $client->messages->create($phone, ['from'=>$from, 'body'=>$text]);
        return true;
    } catch(Exception $e){
        return $e->getMessage();
    }
}

// أمثلة على حالات الرسائل
if(isset($_GET['action']) && isset($_GET['subscriber_id'])){
    $id = $_GET['subscriber_id'];
    $subscriber = $conn->query("SELECT * FROM subscribers WHERE id='$id'")->fetch_assoc();

    switch($_GET['action']){
        case 'install_line':
            $text = $settings['msg_install_line'];
            break;
        case 'payment_alert':
            $text = $settings['msg_payment_alert'];
            break;
        case 'paid':
            $text = $settings['msg_paid'];
            break;
        case 'package_activated':
            $text = $settings['msg_package_activated'];
            break;
        case 'speed_changed':
            $text = $settings['msg_speed_changed'];
            break;
        case 'blocked':
            $text = $settings['msg_subscription_blocked'];
            break;
        case 'reactivated':
            $text = $settings['msg_subscription_reactivated'];
            break;
        default:
            die("حالة غير معرفة");
    }

    $result = sendMessage($subscriber['phone'], $text);
    if($result===true){
        echo "<p style='color:green;'>✅ تم إرسال الرسالة للمشترك ".$subscriber['full_name']."</p>";
    } else {
        echo "<p style='color:red;'>❌ خطأ في الإرسال: ".$result."</p>";
    }
}
?>
