<?php
require_once '../includes/functions.php';
requireLogin();

$id = (int)($_GET['id'] ?? 0);
if (!$id) {
    header('Location: invoices.php');
    exit;
}

$db = getDB();
try {
    $stmt = $db->prepare("SELECT i.*, c.name as cust_name, c.address as cust_address, c.city as cust_city, c.state as cust_state, c.pincode as cust_pincode, c.email as cust_email, c.phone as cust_phone, c.gstin as cust_gstin FROM invoices i JOIN customers c ON i.customer_id = c.id WHERE i.id = ?");
    $stmt->execute([$id]);
    $inv = $stmt->fetch();
    if (!$inv) {
        header('Location: invoices.php');
        exit;
    }
} catch (PDOException $e) {
    setFlash('error', 'Failed to load invoice for WhatsApp.');
    header('Location: invoices.php');
    exit;
}

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$path = dirname($_SERVER['SCRIPT_NAME']);
$pdfUrl = $scheme . '://' . $host . $path . '/pdf_invoice.php?id=' . $id;

$message  = "Invoice: " . $inv['invoice_number'] . "\n";
$message .= "Customer: " . $inv['cust_name'] . "\n";
$message .= "Date: " . date('d M Y', strtotime($inv['invoice_date'])) . "\n";
$message .= "Total: " . number_format($inv['total_amount'], 2) . "\n";
$message .= "Status: " . ucfirst($inv['status']) . "\n\n";
$message .= "Download invoice PDF: " . $pdfUrl . "\n";
$message .= "Thank you for your business!";

$phone = '918778318977';
$encoded = rawurlencode($message);
$redirectUrl = "https://wa.me/{$phone}?text={$encoded}";
header('Location: ' . $redirectUrl);
exit;
