<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['phoneNumber'])) {
    $phoneNumber = $_POST['phoneNumber'];
    
    // Validate the phone number (should be 11 digits)
    if (preg_match('/^\d{11}$/', $phoneNumber)) {
        $send_data = [];
        
        // Parameters to configure
        $send_data['sender_id'] = "PhilSMS";
        $send_data['recipient'] = "+63" . substr($phoneNumber, 1); // Convert to international format
        $send_data['message'] = "Discount 10% off on your next purchase! Use code: DISCOUNT10";
        $token = "1758|EN8QQai5z43aFvxR6GbxbwRF386abR6E89t8iTaO"; // Replace with your actual token
        
        // Send the SMS
        $parameters = json_encode($send_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://app.philsms.com/api/v3/sms/send");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $headers = [
            "Content-Type: application/json",
            "Authorization: Bearer $token"
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $result = curl_exec($ch);
        curl_close($ch);
        
        // Redirect back with success message
        header('Location: ../view/user/home.php?success=1');
        exit();
    } else {
        // Invalid phone number format
        header('Location: ../view/user/home.php?error=invalid_number');
        exit();
    }
} else {
    // Invalid request
    header('Location: ../view/user/home.php');
    exit();
}
?>