<?php
require_once '../includes/db.php';

$bill_number = $_POST['bill_number'] ?? '';
if (!$bill_number) {
    http_response_code(400);
    exit("Bill number missing.");
}

$stmt = $pdo->prepare("SELECT b.bill_number, c.name, c.contact_number FROM bills b JOIN customers c ON b.customer_id = c.customer_id WHERE b.bill_number = ?");
$stmt->execute([$bill_number]);
$bill = $stmt->fetch();

if (!$bill) {
    http_response_code(404);
    exit("Bill not found.");
}

$phone = $bill['contact_number'];
$name = $bill['name'];
$link = "https://wash-house.lka.ovh/invoice.php?bill=" . urlencode($bill_number);

// ✅ Compose the message
$message = "Hi $name, your invoice #$bill_number is ready. View it here: $link";

// ✅ Send SMS using SMSlenz API
$apiUrl = "https://smslenz.lk/api/send-sms";
$postData = [
    'user_id'   => '190',
    'api_key'   => '82ea81df-b596-45f4-9fb7-dde0f75fb7c6',
    'sender_id' => 'SMSlenzDEMO', // or your real sender ID
    'contact'   => '+94' . ltrim($phone, '0'),
    'message'   => $message
];

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    http_response_code(500);
    exit("SMS Error: " . $error);
}

echo "SMS sent to $name successfully.";
