<?php
// generate_pdf.php
// Generates a PDF report for itemized financial contributions using TCPDF.

// -----------------------------------------------------
// 1. Setup TCPDF Library and Database Connection
// -----------------------------------------------------

// NOTE: Ensure 'db_connect.php' properly initializes and connects to the database ($conn)
include 'db_connect.php'; 

// Load TCPDF Library
// The path specified by the user:
require_once('tcpdf/tcpdf_main/tcpdf.php');

// -----------------------------------------------------
// 2. Data Retrieval and Calculation (Same logic as contribution_by_date.php)
// -----------------------------------------------------
function get_safe_data($param, $default = '')
{
    // Use POST if available, otherwise GET
    return isset($_REQUEST[$param]) ? htmlspecialchars($_REQUEST[$param]) : $default;
}

$partner_id     = (int)get_safe_data('partner_id');
$agreement_id   = (int)get_safe_data('agreement_id');
$start_date     = get_safe_data('start_date');
$end_date       = get_safe_data('end_date');

// *****************************************************
// FIX: Explicit Validation for clear error messages
// *****************************************************
if ($partner_id === 0) {
    die("Error: Invalid partner ID for PDF generation.");
}
if ($agreement_id === 0) {
    die("Error: Invalid agreement ID for PDF generation.");
}
if (empty($start_date) || empty($end_date)) {
    die("Error: Missing a valid date range for PDF generation.");
}
// *****************************************************


$partner_name = "N/A";
$agreement_code = "N/A";
$commitment_amount = 0;
$commitment_currency = 'TZS';
$total_paid = 0;
$contributions = [];

// --- Fetch Partner and Agreement Code ---
$sql_partner_agreement = "
    SELECT  
        p.partner_name, 
        pa.agreement_code
    FROM Partners p
    JOIN Partnership_Agreements pa ON p.partner_id = pa.partner_id
    WHERE p.partner_id = ? AND pa.agreement_id = ?
";
$stmt_pa = $conn->prepare($sql_partner_agreement);
if ($stmt_pa) {
    $stmt_pa->bind_param("ii", $partner_id, $agreement_id);
    $stmt_pa->execute();
    $result_pa = $stmt_pa->get_result();
    if ($row_pa = $result_pa->fetch_assoc()) {
        $partner_name = htmlspecialchars($row_pa['partner_name']);
        $agreement_code = htmlspecialchars($row_pa['agreement_code']);
    }
    $stmt_pa->close();
}

// --- Fetch Commitment Amount ---
$sql_commitment = "
    SELECT 
        commitment_amount, 
        commitment_currency
    FROM Agreement_Commitment_History 
    WHERE 
        agreement_id = ? AND 
        effective_start_date <= ? AND 
        (effective_end_date IS NULL OR effective_end_date >= ?)
    ORDER BY effective_start_date DESC
    LIMIT 1
";

$stmt_commitment = $conn->prepare($sql_commitment);
if ($stmt_commitment) {
    $stmt_commitment->bind_param("iss", $agreement_id, $start_date, $start_date);
    $stmt_commitment->execute();
    $result_commitment = $stmt_commitment->get_result();
    if ($row_commitment = $result_commitment->fetch_assoc()) {
        $commitment_amount = $row_commitment['commitment_amount'];
        $commitment_currency = htmlspecialchars($row_commitment['commitment_currency']);
    }
    $stmt_commitment->close();
}

// --- Fetch Financial Contributions ---
$sql_contributions = "
    SELECT  
        fc.receipt_number, fc.amount, fc.currency, fc.contribution_date, fc.description, sc.category_name
    FROM Financial_Contributions fc
    JOIN Sadaka_Categories sc ON fc.category_id = sc.category_id
    WHERE 
        fc.partner_id = ?  
        AND fc.agreement_id = ?
        AND fc.contribution_date BETWEEN ? AND ?
    ORDER BY fc.contribution_date ASC
";

$stmt_contributions = $conn->prepare($sql_contributions);
if ($stmt_contributions) {
    $stmt_contributions->bind_param("iiss", $partner_id, $agreement_id, $start_date, $end_date);
    $stmt_contributions->execute();
    $result_contributions = $stmt_contributions->get_result();
    
    while ($row = $result_contributions->fetch_assoc()) {
        $contributions[] = $row;
        if ($row['currency'] === $commitment_currency) {
            $total_paid += $row['amount'];
        }
    }
    $stmt_contributions->close();
}

// Calculate Remaining Amount
$remaining_amount = $commitment_amount - $total_paid;
$status_text = ($remaining_amount > 0) ? '(Deficit)' : '(Surplus/Matched)';
// Determine color for the Remaining Amount text
$remaining_color_style = ($remaining_amount > 0) ? 'color: #dc3545;' : 'color: #28a745;'; // Red for Deficit, Green for Surplus
$abs_remaining = abs($remaining_amount);

$conn->close();

// -----------------------------------------------------
// 3. TCPDF Document Generation
// -----------------------------------------------------

// Create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// Set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Financial System');
$pdf->SetTitle("Contributions Report: $partner_name ($agreement_code)");
$pdf->SetSubject('Financial Contribution Details');

// Remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// Set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// Set margins (equivalent to Bootstrap container padding)
$pdf->SetMargins(15, 15, 15);

// Set auto page breaks
$pdf->SetAutoPageBreak(TRUE, 15);

// Set font
$pdf->SetFont('helvetica', '', 10);

// Add a page
$pdf->AddPage();

// Define custom styles for HTML output (mimicking UI colors)
$html_styles = '
    <style>
        h1 { color: #007bff; font-size: 20pt; font-weight: bold; }
        h4 { font-size: 14pt; }
        .summary-box { 
            background-color: #e9f5ff; 
            border: 1px solid #cce5ff; 
            padding: 10px;
            margin-bottom: 15px;
        }
        .summary-table { 
            width: 100%; 
            border-collapse: collapse;
        }
        .summary-table td { 
            padding: 5px; 
            font-size: 10pt;
        }
        .table-header { 
            background-color: #343a40; 
            color: #ffffff; 
            font-weight: bold;
        }
        .table-row-odd { background-color: #f8f9fa; }
        .table-row-even { background-color: #ffffff; }
        .color-green { ' . $remaining_color_style . ' } 
        .color-paid { color: #28a745; font-weight: bold; }
    </style>
';

// Build the HTML content to match the UI layout
$html_content = '
    <h1>Detailed Contributions by Date Range</h1>
    <h4 style="margin-bottom: 15px;">Partner: ' . $partner_name . ' (Agreement: ' . $agreement_code . ')</h4>
    <hr style="height: 1px; background-color: #007bff; border: none;">

    <!-- Summary Box -->
    <div class="summary-box">
        <h4>Summary for <span style="font-style: italic; color: #555;">' . $start_date . ' to ' . $end_date . '</span></h4>
        <table class="summary-table">
            <tr>
                <td width="50%">
                    <p><strong>Effective Commitment:</strong> ' . number_format($commitment_amount, 2) . ' ' . $commitment_currency . 
                    ($commitment_amount == 0 ? ' <span style="color: #dc3545;">(No commitment found for this period)</span>' : '') . '</p>
                </td>
                <td width="50%">
                    <p><strong>Remaining Amount:</strong>  
                        <span class="color-green">' . number_format($abs_remaining, 2) . ' ' . $commitment_currency . '</span>
                        ' . $status_text . '
                    </p>
                </td>
            </tr>
            <tr>
                <td width="50%">
                    <p><strong>Total Paid in Range:</strong>  
                        <span class="color-paid">' . number_format($total_paid, 2) . ' ' . $commitment_currency . '</span>
                    </p>
                </td>
                <td width="50%">
                    <p><strong>Number of Contributions:</strong> ' . count($contributions) . '</p>
                </td>
            </tr>
        </table>
    </div>
    <br>

    <h4>Itemized Contributions</h4>
';

if (count($contributions) > 0) {
    // Start of Contributions Table
    $html_content .= '<table cellspacing="0" cellpadding="4" border="1" style="width: 100%; border-collapse: collapse;">
        <tr class="table-header">
            <td width="5%" align="center">#</td>
            <td width="15%">Receipt Number</td>
            <td width="15%">Date</td>
            <td width="15%" align="right">Amount</td>
            <td width="10%">Currency</td>
            <td width="15%">Category</td>
            <td width="25%">Description</td>
        </tr>';

    $index = 1; 
    foreach ($contributions as $contribution) {
        $row_class = ($index % 2 == 0) ? 'table-row-even' : 'table-row-odd';
        $html_content .= '
        <tr class="' . $row_class . '">
            <td width="5%" align="center">' . $index++ . '</td>
            <td width="15%">' . htmlspecialchars($contribution['receipt_number']) . '</td>
            <td width="15%">' . htmlspecialchars($contribution['contribution_date']) . '</td>
            <td width="15%" align="right">' . number_format($contribution['amount'], 2) . '</td>
            <td width="10%">' . htmlspecialchars($contribution['currency']) . '</td>
            <td width="15%">' . htmlspecialchars($contribution['category_name']) . '</td>
            <td width="25%">' . htmlspecialchars($contribution['description']) . '</td>
        </tr>';
    }

    $html_content .= '</table>';
} else {
    $html_content .= '<p style="text-align: center; color: #6c757d; padding: 10px; border: 1px solid #adb5bd; background-color: #f8f9fa;">No contributions found for this agreement in the selected date range.</p>';
}

// Write the HTML content to the PDF
$pdf->writeHTML($html_styles . $html_content, true, false, true, false, '');

// Close and output PDF document
$pdf->Output("Contribution_Report_{$partner_id}_{$agreement_id}.pdf", 'I'); 

?>