<?php
/**
 * Receipt Generation Functions
 */

/**
 * Generate a receipt for a transaction
 */
function generateReceipt($transaction_id, $auto_email = false) {
    global $pdo;
    
    if (!isset($pdo)) {
        return false;
    }
    
    // Ensure receipts table exists
    try {
        $pdo->query('SELECT 1 FROM receipts LIMIT 1');
    } catch (PDOException $e) {
        try {
            $pdo->exec("
                CREATE TABLE IF NOT EXISTS receipts (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    receipt_number VARCHAR(50) NOT NULL UNIQUE,
                    transaction_id INT NOT NULL,
                    member_id INT NULL,
                    fund_id INT NOT NULL,
                    amount DECIMAL(12,2) NOT NULL,
                    transaction_date DATE NOT NULL,
                    issued_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    issued_by INT NULL,
                    emailed TINYINT(1) DEFAULT 0,
                    emailed_at DATETIME NULL,
                    notes TEXT NULL,
                    INDEX idx_transaction_id (transaction_id),
                    INDEX idx_receipt_number (receipt_number),
                    INDEX idx_member_id (member_id),
                    INDEX idx_issued_at (issued_at),
                    FOREIGN KEY (transaction_id) REFERENCES transactions(id) ON DELETE CASCADE,
                    FOREIGN KEY (member_id) REFERENCES members(id) ON DELETE SET NULL,
                    FOREIGN KEY (fund_id) REFERENCES funds(id),
                    FOREIGN KEY (issued_by) REFERENCES users(id) ON DELETE SET NULL
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ");
        } catch (PDOException $e2) {
            error_log('Failed to create receipts table: ' . $e2->getMessage());
            return false;
        }
    }
    
    // Get transaction details
    try {
        $stmt = $pdo->prepare("
            SELECT t.*, f.name AS fund_name, m.first_name, m.last_name, m.email, m.phone,
                   CONCAT(m.first_name, ' ', m.last_name) AS member_name
            FROM transactions t
            JOIN funds f ON t.fund_id = f.id
            LEFT JOIN members m ON t.member_id = m.id
            WHERE t.id = ?
        ");
        $stmt->execute([$transaction_id]);
        $transaction = $stmt->fetch();
        
        if (!$transaction) {
            return false;
        }
        
        // Check if receipt already exists
        $existing = $pdo->prepare('SELECT id FROM receipts WHERE transaction_id = ?');
        $existing->execute([$transaction_id]);
        if ($existing->fetch()) {
            return false; // Receipt already exists
        }
        
        // Generate receipt number
        $receiptNumber = generateReceiptNumber();
        
        // Insert receipt
        $stmt = $pdo->prepare("
            INSERT INTO receipts (receipt_number, transaction_id, member_id, fund_id, amount, transaction_date, issued_by, notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $receiptNumber,
            $transaction_id,
            $transaction['member_id'] ?: null,
            $transaction['fund_id'],
            $transaction['amount'],
            $transaction['transaction_date'],
            currentUserId(),
            $transaction['note'] ?: null
        ]);
        
        $receiptId = $pdo->lastInsertId();
        
        // Auto-email if requested and member has email
        if ($auto_email && !empty($transaction['email'])) {
            emailReceipt($receiptId);
        }
        
        // In development (no thermal printer): write receipt HTML to file
        if (defined('RECEIPT_PRINT_TO_FILE') && RECEIPT_PRINT_TO_FILE) {
            printReceiptToFile($receiptId);
        }
        
        return $receiptId;
    } catch (PDOException $e) {
        error_log('Receipt generation error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Generate unique receipt number
 */
function generateReceiptNumber() {
    global $pdo;
    
    $prefix = 'RCP';
    $year = date('Y');
    $month = date('m');
    
    // Get last receipt number for this month
    try {
        $stmt = $pdo->prepare("
            SELECT receipt_number FROM receipts 
            WHERE receipt_number LIKE ? 
            ORDER BY id DESC LIMIT 1
        ");
        $pattern = $prefix . $year . $month . '%';
        $stmt->execute([$pattern]);
        $last = $stmt->fetchColumn();
        
        if ($last) {
            // Extract sequence number
            $seq = (int)substr($last, -4);
            $seq++;
        } else {
            $seq = 1;
        }
    } catch (PDOException $e) {
        $seq = 1;
    }
    
    return $prefix . $year . $month . str_pad($seq, 4, '0', STR_PAD_LEFT);
}

/**
 * Email receipt to member
 */
function emailReceipt($receipt_id) {
    global $pdo;
    
    require_once __DIR__ . '/settings.php';
    require_once __DIR__ . '/mail.php';
    
    try {
        $stmt = $pdo->prepare("
            SELECT r.*, t.note AS transaction_note,
                   m.first_name, m.last_name, m.email,
                   CONCAT(m.first_name, ' ', m.last_name) AS member_name,
                   f.name AS fund_name
            FROM receipts r
            JOIN transactions t ON r.transaction_id = t.id
            JOIN funds f ON r.fund_id = f.id
            LEFT JOIN members m ON r.member_id = m.id
            WHERE r.id = ?
        ");
        $stmt->execute([$receipt_id]);
        $receipt = $stmt->fetch();
        
        if (!$receipt || empty($receipt['email'])) {
            return false;
        }
        
        $churchName = defined('SITE_FULL_NAME') ? SITE_FULL_NAME : 'PCG Nazareth';
        $shortName = defined('SITE_NAME') ? SITE_NAME : 'Nazareth';
        
        // Get receipt template
        $template = getSetting('receipt_email_template', '');
        if (empty($template)) {
            $template = "Dear {member_name},\n\nReceipt Number: {receipt_number}\nDate: {date}\nFund: {fund_name}\nAmount: GH₵ {amount}\n\nThank you for your contribution.\n\n— {church_name}";
        }
        
        $replacements = [
            '{member_name}' => $receipt['member_name'] ?: 'Valued Member',
            '{receipt_number}' => $receipt['receipt_number'],
            '{date}' => date('F j, Y', strtotime($receipt['transaction_date'])),
            '{fund_name}' => $receipt['fund_name'],
            '{amount}' => number_format($receipt['amount'], 2),
            '{church_name}' => $churchName,
        ];
        
        $emailBody = str_replace(array_keys($replacements), array_values($replacements), $template);
        $emailSubject = getSetting('receipt_email_subject', 'Receipt - ' . $shortName) ?: 'Receipt - ' . $shortName;
        
        $emailBodyHtml = wrapReceiptEmailHtml(nl2br(htmlspecialchars($emailBody)), $churchName);
        
        $result = sendMail($receipt['email'], $emailSubject, $emailBodyHtml, $emailBody);
        
        if ($result['sent']) {
            // Update receipt
            $pdo->prepare('UPDATE receipts SET emailed = 1, emailed_at = NOW() WHERE id = ?')
                ->execute([$receipt_id]);
            return true;
        }
        
        return false;
    } catch (PDOException $e) {
        error_log('Email receipt error: ' . $e->getMessage());
        return false;
    }
}

// Note: wrapReceiptEmailHtml() is defined in includes/mail.php to avoid duplication

/**
 * Fetch receipt data for printing (same structure as receipt-print.php)
 */
function getReceiptForPrint($receipt_id) {
    global $pdo;
    if (!isset($pdo)) return null;
    try {
        $stmt = $pdo->prepare("
            SELECT r.*,
                   f.name AS fund_name, f.description AS fund_description,
                   m.first_name, m.last_name, m.email, m.phone, m.address,
                   CONCAT(m.first_name, ' ', m.last_name) AS member_name,
                   u.username AS issued_by_username
            FROM receipts r
            JOIN funds f ON r.fund_id = f.id
            LEFT JOIN members m ON r.member_id = m.id
            LEFT JOIN users u ON r.issued_by = u.id
            WHERE r.id = ?
        ");
        $stmt->execute([$receipt_id]);
        return $stmt->fetch();
    } catch (PDOException $e) {
        error_log('getReceiptForPrint error: ' . $e->getMessage());
        return null;
    }
}

/**
 * Render receipt as a full HTML document (print-friendly, thermal-style)
 */
function renderReceiptHtml($receipt) {
    if (!$receipt) return '';
    require_once __DIR__ . '/settings.php';
    $churchName = defined('SITE_FULL_NAME') ? SITE_FULL_NAME : 'PCG Nazareth';
    $churchAddress = getSetting('church_address', '');
    $receiptNumber = htmlspecialchars($receipt['receipt_number']);
    $transactionDate = date('F j, Y', strtotime($receipt['transaction_date']));
    $memberName = $receipt['member_name'] ? htmlspecialchars($receipt['member_name']) : '';
    $address = !empty($receipt['address']) ? htmlspecialchars($receipt['address']) : '';
    $fundName = htmlspecialchars($receipt['fund_name']);
    $notes = !empty($receipt['notes']) ? htmlspecialchars($receipt['notes']) : '';
    $amount = number_format((float)$receipt['amount'], 2);
    $issuedAt = date('F j, Y \a\t g:i A', strtotime($receipt['issued_at']));
    $issuedBy = !empty($receipt['issued_by_username']) ? htmlspecialchars($receipt['issued_by_username']) : '';
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'Nazareth';
    ob_start();
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt <?= $receiptNumber ?> - <?= htmlspecialchars($siteName) ?></title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Times New Roman', serif; padding: 40px; background: #fff; color: #000; line-height: 1.6; }
        @media print { body { padding: 20px; } }
        .receipt-container { max-width: 800px; margin: 0 auto; border: 2px solid #000; padding: 40px; }
        .header { text-align: center; border-bottom: 2px solid #000; padding-bottom: 20px; margin-bottom: 30px; }
        .header h1 { font-size: 24px; font-weight: bold; margin-bottom: 10px; }
        .header p { font-size: 14px; margin: 5px 0; }
        .receipt-title { text-align: center; font-size: 20px; font-weight: bold; margin: 30px 0; text-decoration: underline; }
        .receipt-info table { width: 100%; border-collapse: collapse; }
        .receipt-info td { padding: 10px; border-bottom: 1px solid #ddd; }
        .receipt-info td:first-child { font-weight: bold; width: 40%; }
        .amount-section { text-align: center; margin: 40px 0; padding: 20px; border: 2px solid #000; }
        .amount-section .label { font-size: 16px; margin-bottom: 10px; }
        .amount-section .amount { font-size: 32px; font-weight: bold; }
        .footer { margin-top: 50px; padding-top: 20px; border-top: 1px solid #000; text-align: center; font-size: 12px; }
        .signature-section { margin-top: 60px; display: flex; justify-content: space-between; }
        .signature-box { width: 45%; text-align: center; }
        .signature-line { border-top: 1px solid #000; margin-top: 50px; padding-top: 5px; }
    </style>
</head>
<body>
    <div class="receipt-container">
        <div class="header">
            <h1><?= htmlspecialchars($churchName) ?></h1>
            <?php if ($churchAddress): ?><p><?= htmlspecialchars($churchAddress) ?></p><?php endif; ?>
            <p>Official Receipt</p>
        </div>
        <div class="receipt-title">RECEIPT</div>
        <div class="receipt-info">
            <table>
                <tr><td>Receipt Number:</td><td><?= $receiptNumber ?></td></tr>
                <tr><td>Date:</td><td><?= $transactionDate ?></td></tr>
                <?php if ($memberName): ?>
                <tr><td>Received from:</td><td><?= $memberName ?></td></tr>
                <?php if ($address): ?><tr><td>Address:</td><td><?= $address ?></td></tr><?php endif; ?>
                <?php endif; ?>
                <tr><td>Fund:</td><td><?= $fundName ?></td></tr>
                <?php if ($notes): ?><tr><td>Notes:</td><td><?= $notes ?></td></tr><?php endif; ?>
            </table>
        </div>
        <div class="amount-section">
            <div class="label">Amount Received</div>
            <div class="amount">GH&#8373; <?= $amount ?></div>
        </div>
        <div class="footer">
            <p>This receipt serves as confirmation of your contribution.</p>
            <p style="margin-top: 10px;">Issued on: <?= $issuedAt ?></p>
            <?php if ($issuedBy): ?><p>Issued by: <?= $issuedBy ?></p><?php endif; ?>
        </div>
        <div class="signature-section">
            <div class="signature-box"><div class="signature-line">Member Signature</div></div>
            <div class="signature-box"><div class="signature-line">Authorized Signature</div></div>
        </div>
    </div>
</body>
</html>
    <?php
    return ob_get_clean();
}

/**
 * Write receipt HTML to a file (for development when thermal printer is not available).
 * Files are saved under storage/receipts/ with filename receipt-{number}-{Y-m-d-His}.html
 */
function printReceiptToFile($receipt_id) {
    $receipt = getReceiptForPrint($receipt_id);
    if (!$receipt) return false;
    $html = renderReceiptHtml($receipt);
    if ($html === '') return false;
    $baseDir = defined('ROOT_PATH') ? ROOT_PATH : (dirname(__DIR__));
    $dir = $baseDir . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'receipts';
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
        if (!is_dir($dir)) {
            error_log('Receipt print-to-file: could not create directory ' . $dir);
            return false;
        }
    }
    $safeNumber = preg_replace('/[^A-Za-z0-9\-_]/', '-', $receipt['receipt_number']);
    $filename = 'receipt-' . $safeNumber . '-' . date('Y-m-d-His') . '.html';
    $path = $dir . DIRECTORY_SEPARATOR . $filename;
    $ok = @file_put_contents($path, $html);
    if ($ok === false) {
        error_log('Receipt print-to-file: could not write ' . $path);
        return false;
    }
    return $path;
}
