<?php 
include "top.php"; // Include database connection
require 'smsgate/vendor/autoload.php';
use AndroidSmsGateway\Client;
use AndroidSmsGateway\Encryptor;
use AndroidSmsGateway\Domain\Message;    

header('Content-Type: application/json'); // Set JSON header

$action = $_REQUEST['action'] ?? '';
$smstype = $_REQUEST['tpe'] ?? '';

if ($action === 'sendsms') {
    $response = ['success' => false, 'count' => 0];
    
    try {
        

        $smsissent = "";
        $retso = "";
        
        // Get sender ID details
        $sender_id = $_POST['sender_id'] ?? null;
        if($sender_id) {
            $getsms = mysqli_query($con, "SELECT * FROM sender_ids WHERE id = '$sender_id'");
            $sender = mysqli_fetch_assoc($getsms);
            
            if(!$sender) {
                throw new Exception("Invalid sender ID");
            }
            
            // Check daily limit
            if($sender['last_reset'] != $today) {
                mysqli_query($con, "UPDATE sender_ids SET sms_count = 0, last_reset = '$today' WHERE id = '$sender_id'");
                $sender['sms_count'] = 0;
            }
            
            if($sender['sms_count'] >= 100) {
                throw new Exception("Daily limit of 100 SMS reached for this sender ID");
            }
        } else {
            // Fallback to random sender if not specified
            $getsms = mysqli_query($con, "SELECT * FROM sender_ids WHERE is_active=1 ORDER BY RAND() LIMIT 1");
            $sender = mysqli_fetch_assoc($getsms);
            
            if(!$sender) {
                throw new Exception("No sender IDs configured");
            }
        }
                    
        $login = $sender['username'];
        $password = $sender['password'];
        $p_cphone = $_POST['cphone'];
        $smsph = "+91".$p_cphone;
        $msgs = base64_decode($_POST['msgs']);
        $msgs = LINK_NAME."\n".$msgs;

        $client = new Client($login, $password);
        
        $message = new Message($msgs, [$smsph]);
        
        try {
            $messageState = $client->Send($message);
            // Update sender's SMS count
            mysqli_query($con, "UPDATE sender_ids SET sms_count = sms_count + 1 WHERE id = '{$sender['id']}'");
            $retso = "Message sent with ID: " . $messageState->ID() . PHP_EOL;

            if (strpos($retso, "Message sent with ID") !== false) {
                $smsissent = "Message sent";
                $response['success'] = true;
            } 
            
        } catch (Exception $e) {
            $retso = "Error sending message: " . $e->getMessage() . PHP_EOL;
            $response['error'] = $e->getMessage();
            throw $e;
        }
        
        try {
            $messageState = $client->GetState($messageState->ID());
            $rets = "Message state: " . $messageState->State() . PHP_EOL;
        } catch (Exception $e) {
            $rets = "Error getting message state: " . $e->getMessage() . PHP_EOL;
        }
        
    } catch (Exception $e) {
        $response['error'] = $e->getMessage();
    }
    
    echo json_encode($response);
    exit;
}

// If we reach here, it's not a sendsms action or something went wrong
echo json_encode(['success' => false, 'error' => 'Invalid action']);
?>