<?php
require_once "../config/db.php";

$id = (int) ($_GET['id'] ?? 0);

$data = $conn->query("
SELECT 
customers.name,
customers.phone,
SUM(invoices.total) as total_due
FROM invoices
JOIN customers ON invoices.customer_id = customers.id
WHERE customers.id = $id
AND invoices.payment_status='pending'
")->fetch_assoc();

$phone = preg_replace('/[^0-9]/', '', $data['phone']);

if(strlen($phone) == 10){
    $phone = "91" . $phone;
}

$message = "Hello {$data['name']},\n";
$message .= "Your total outstanding is Rs. {$data['total_due']}.\n";

$message = urlencode($message);

header("Location: https://wa.me/$phone?text=$message");
exit;
