<?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 = [];
        
        // Discount messages array
        $discountMessages = [
            "Get 10% off on your next purchase! Use code: SAVE10",
            "Exclusive offer: 15% discount for you! Code: SPECIAL15",
            "Limited time: 20% off all items. Shop now with code: DEAL20",
            "Flash sale! Enjoy 25% discount with code: FLASH25",
            "Weekend special: 30% off your order. Use code: WEEKEND30",
            "New customer discount: 12% off with code: WELCOME12",
            "Buy 1 get 1 free! Use promo code: BOGO100",
            "Massive 50% discount on selected items! Code: HALF50",
            "Free shipping + 10% off with code: FREESHIP10",
            "VIP discount: 18% off all purchases. Your code: VIP18"
        ];
        
        // Select a random message
        $randomMessage = $discountMessages[array_rand($discountMessages)];
        
        // Parameters to configure
        $send_data['sender_id'] = "PhilSMS";
        $send_data['recipient'] = "+63" . substr($phoneNumber, 1); // Convert to international format
        $send_data['message'] = $randomMessage;
        $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();
}
?>