<?php
/**
 * Payment Receipt
 * LandSales Pro - Generate printable payment receipt
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$paymentId = intval($_GET['id'] ?? 0);

if (!$paymentId) {
    header('Location: index.php');
    exit;
}

// Get payment details
$payment = db_fetch_one("SELECT py.*, s.sale_number, s.total_price, s.sale_date,
    b.full_name as buyer_name, b.phone as buyer_phone, b.email as buyer_email, b.address as buyer_address,
    p.plot_number, p.size, p.size_unit, p.block,
    pr.name as project_name, pr.location as project_location
    FROM payments py
    JOIN sales s ON py.sale_id = s.id
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    WHERE py.id = ? AND py.user_id = ?", 'ii', [$paymentId, $userId]);

if (!$payment) {
    setFlashMessage('error', 'Payment not found');
    header('Location: index.php');
    exit;
}

// Calculate totals
$totalPaid = db_fetch_one("SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE sale_id = ? AND status = 'confirmed'", 'i', [$payment['sale_id']])['total'];
$balance = $payment['total_price'] - $totalPaid;

// Get company settings
$user = db_fetch_one("SELECT company_name, company_phone, company_email, company_address FROM users WHERE id = ?", 'i', [$userId]);
$companyName = $user['company_name'] ?: APP_NAME;
$companyPhone = $user['company_phone'] ?: '';
$companyEmail = $user['company_email'] ?: '';
$companyAddress = $user['company_address'] ?: '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt <?php echo $payment['payment_number']; ?> - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header no-print">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Payment Receipt</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <button onclick="window.print()" class="btn btn-primary">
                    <i class="fas fa-print"></i> Print
                </button>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="receipt-container">
                <div class="receipt">
                    <!-- Header -->
                    <div class="receipt-header">
                        <div class="company-info">
                            <h1><?php echo htmlspecialchars($companyName); ?></h1>
                            <?php if ($companyAddress): ?>
                            <p><?php echo htmlspecialchars($companyAddress); ?></p>
                            <?php endif; ?>
                            <?php if ($companyPhone): ?>
                            <p>Phone: <?php echo htmlspecialchars($companyPhone); ?></p>
                            <?php endif; ?>
                            <?php if ($companyEmail): ?>
                            <p>Email: <?php echo htmlspecialchars($companyEmail); ?></p>
                            <?php endif; ?>
                        </div>
                        <div class="receipt-title">
                            <h2>PAYMENT RECEIPT</h2>
                            <div class="receipt-number"><?php echo $payment['payment_number']; ?></div>
                        </div>
                    </div>

                    <!-- Receipt Info -->
                    <div class="receipt-meta">
                        <div class="meta-row">
                            <div class="meta-item">
                                <span class="meta-label">Receipt Date:</span>
                                <span class="meta-value"><?php echo date('F j, Y', strtotime($payment['payment_date'])); ?></span>
                            </div>
                            <div class="meta-item">
                                <span class="meta-label">Sale Reference:</span>
                                <span class="meta-value"><?php echo $payment['sale_number']; ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Received From -->
                    <div class="receipt-section">
                        <h3>Received From</h3>
                        <div class="info-block">
                            <p><strong><?php echo htmlspecialchars($payment['buyer_name']); ?></strong></p>
                            <p><?php echo htmlspecialchars($payment['buyer_phone']); ?></p>
                            <?php if ($payment['buyer_email']): ?>
                            <p><?php echo htmlspecialchars($payment['buyer_email']); ?></p>
                            <?php endif; ?>
                            <?php if ($payment['buyer_address']): ?>
                            <p><?php echo htmlspecialchars($payment['buyer_address']); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Property Details -->
                    <div class="receipt-section">
                        <h3>Property Details</h3>
                        <table class="detail-table">
                            <tr>
                                <td>Plot Number:</td>
                                <td><strong><?php echo htmlspecialchars($payment['plot_number']); ?></strong></td>
                            </tr>
                            <tr>
                                <td>Project:</td>
                                <td><?php echo htmlspecialchars($payment['project_name']); ?></td>
                            </tr>
                            <?php if ($payment['project_location']): ?>
                            <tr>
                                <td>Location:</td>
                                <td><?php echo htmlspecialchars($payment['project_location']); ?></td>
                            </tr>
                            <?php endif; ?>
                            <tr>
                                <td>Size:</td>
                                <td><?php echo number_format($payment['size']); ?> <?php echo $payment['size_unit']; ?></td>
                            </tr>
                            <?php if ($payment['block']): ?>
                            <tr>
                                <td>Block:</td>
                                <td><?php echo htmlspecialchars($payment['block']); ?></td>
                            </tr>
                            <?php endif; ?>
                        </table>
                    </div>

                    <!-- Payment Details -->
                    <div class="receipt-section">
                        <h3>Payment Details</h3>
                        <table class="payment-table">
                            <thead>
                                <tr>
                                    <th>Description</th>
                                    <th class="text-right">Amount (TZS)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>
                                        Payment for Plot <?php echo htmlspecialchars($payment['plot_number']); ?>
                                        <br><small>Method: <?php echo ucfirst($payment['payment_method']); ?>
                                        <?php if ($payment['reference']): ?> | Ref: <?php echo htmlspecialchars($payment['reference']); ?><?php endif; ?></small>
                                    </td>
                                    <td class="text-right"><?php echo number_format($payment['amount']); ?></td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr class="total-row">
                                    <td><strong>Amount Paid</strong></td>
                                    <td class="text-right"><strong><?php echo number_format($payment['amount']); ?></strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <!-- Summary -->
                    <div class="receipt-summary">
                        <div class="summary-row">
                            <span>Total Sale Price:</span>
                            <span>TZS <?php echo number_format($payment['total_price']); ?></span>
                        </div>
                        <div class="summary-row">
                            <span>Total Paid to Date:</span>
                            <span class="text-success">TZS <?php echo number_format($totalPaid); ?></span>
                        </div>
                        <div class="summary-row highlight">
                            <span>Outstanding Balance:</span>
                            <span class="<?php echo $balance > 0 ? 'text-warning' : 'text-success'; ?>">
                                TZS <?php echo number_format($balance); ?>
                            </span>
                        </div>
                    </div>

                    <?php if ($payment['notes']): ?>
                    <div class="receipt-notes">
                        <strong>Notes:</strong> <?php echo htmlspecialchars($payment['notes']); ?>
                    </div>
                    <?php endif; ?>

                    <!-- Amount in Words -->
                    <div class="amount-words">
                        <strong>Amount in Words:</strong>
                        <?php echo ucfirst(numberToWords($payment['amount'])); ?> Tanzanian Shillings Only
                    </div>

                    <!-- Footer -->
                    <div class="receipt-footer">
                        <div class="signature-block">
                            <div class="signature-line"></div>
                            <p>Authorized Signature</p>
                        </div>
                        <div class="receipt-stamp">
                            <p class="stamp-text">PAID</p>
                            <p class="stamp-date"><?php echo date('d/m/Y', strtotime($payment['payment_date'])); ?></p>
                        </div>
                    </div>

                    <div class="receipt-disclaimer">
                        <p>This is a computer-generated receipt. For any queries, please contact us.</p>
                        <p>Thank you for your payment!</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .receipt-container { max-width: 800px; margin: 0 auto; }

        .receipt {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            padding: 3rem;
            position: relative;
        }

        .receipt-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding-bottom: 1.5rem;
            border-bottom: 2px solid #667eea;
            margin-bottom: 1.5rem;
        }

        .company-info h1 { margin: 0 0 0.5rem; font-size: 1.5rem; color: #1e293b; }
        .company-info p { margin: 0.25rem 0; font-size: 0.85rem; color: #64748b; }

        .receipt-title { text-align: right; }
        .receipt-title h2 { margin: 0; font-size: 1.25rem; color: #667eea; letter-spacing: 2px; }
        .receipt-number { font-family: monospace; font-size: 1.1rem; font-weight: 700; color: #1e293b; margin-top: 0.5rem; }

        .receipt-meta { background: #f8fafc; border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem; }
        .meta-row { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 1rem; }
        .meta-item { }
        .meta-label { color: #64748b; font-size: 0.85rem; }
        .meta-value { font-weight: 600; color: #1e293b; margin-left: 0.5rem; }

        .receipt-section { margin-bottom: 1.5rem; }
        .receipt-section h3 { font-size: 0.9rem; color: #667eea; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.75rem; border-bottom: 1px solid #e2e8f0; padding-bottom: 0.5rem; }

        .info-block { background: #f8fafc; border-radius: 8px; padding: 1rem; }
        .info-block p { margin: 0.25rem 0; font-size: 0.9rem; }

        .detail-table { width: 100%; border-collapse: collapse; }
        .detail-table td { padding: 0.5rem 0; font-size: 0.9rem; border-bottom: 1px solid #f1f5f9; }
        .detail-table td:first-child { color: #64748b; width: 140px; }

        .payment-table { width: 100%; border-collapse: collapse; }
        .payment-table th { background: #f8fafc; padding: 0.75rem; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; border-bottom: 2px solid #e2e8f0; }
        .payment-table td { padding: 1rem 0.75rem; border-bottom: 1px solid #f1f5f9; }
        .payment-table small { color: #94a3b8; }
        .payment-table .total-row { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .payment-table .total-row td { border: none; }
        .text-right { text-align: right; }

        .receipt-summary { background: #f8fafc; border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem; }
        .summary-row { display: flex; justify-content: space-between; padding: 0.5rem 0; font-size: 0.9rem; }
        .summary-row.highlight { font-weight: 700; border-top: 1px solid #e2e8f0; padding-top: 0.75rem; margin-top: 0.5rem; }
        .text-success { color: #16a34a; }
        .text-warning { color: #d97706; }

        .receipt-notes { background: #fef3c7; border-radius: 8px; padding: 1rem; font-size: 0.85rem; color: #92400e; margin-bottom: 1.5rem; }

        .amount-words { background: #dbeafe; border-radius: 8px; padding: 1rem; font-size: 0.9rem; color: #1e40af; margin-bottom: 2rem; }

        .receipt-footer { display: flex; justify-content: space-between; align-items: flex-end; margin-top: 3rem; padding-top: 1rem; }

        .signature-block { text-align: center; }
        .signature-line { width: 200px; border-bottom: 2px solid #1e293b; margin-bottom: 0.5rem; }
        .signature-block p { margin: 0; font-size: 0.85rem; color: #64748b; }

        .receipt-stamp {
            border: 3px solid #22c55e;
            border-radius: 8px;
            padding: 0.5rem 1rem;
            text-align: center;
            transform: rotate(-10deg);
        }
        .stamp-text { font-size: 1.5rem; font-weight: 800; color: #22c55e; margin: 0; letter-spacing: 3px; }
        .stamp-date { font-size: 0.75rem; color: #16a34a; margin: 0; }

        .receipt-disclaimer { text-align: center; margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #e2e8f0; }
        .receipt-disclaimer p { margin: 0.25rem 0; font-size: 0.8rem; color: #94a3b8; }

        @media print {
            body { background: white; }
            .no-print, .sidebar, .main-content::before { display: none !important; }
            .main-content { margin-left: 0; padding: 0; }
            .content-wrapper { padding: 0; }
            .receipt { box-shadow: none; padding: 0; }
            .receipt-container { max-width: 100%; }
        }

        @media (max-width: 576px) {
            .receipt { padding: 1.5rem; }
            .receipt-header { flex-direction: column; gap: 1rem; }
            .receipt-title { text-align: left; }
            .meta-row { flex-direction: column; }
            .receipt-footer { flex-direction: column; gap: 2rem; align-items: center; }
        }
    </style>
</body>
</html>

<?php
// Helper function to convert number to words
function numberToWords($number) {
    $ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
             'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
    $tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

    $number = intval($number);
    if ($number == 0) return 'zero';

    $words = '';

    if ($number >= 1000000000) {
        $words .= numberToWords(floor($number / 1000000000)) . ' billion ';
        $number %= 1000000000;
    }

    if ($number >= 1000000) {
        $words .= numberToWords(floor($number / 1000000)) . ' million ';
        $number %= 1000000;
    }

    if ($number >= 1000) {
        $words .= numberToWords(floor($number / 1000)) . ' thousand ';
        $number %= 1000;
    }

    if ($number >= 100) {
        $words .= $ones[floor($number / 100)] . ' hundred ';
        $number %= 100;
    }

    if ($number >= 20) {
        $words .= $tens[floor($number / 10)] . ' ';
        $number %= 10;
    }

    if ($number > 0) {
        $words .= $ones[$number] . ' ';
    }

    return trim($words);
}
?>
