<?php
// generate_contribution_pdf.php
// Generates a PDF report using TCPDF for partner contributions within a date range.

// -----------------------------------------------------
// 1. Session and Database Connection
// -----------------------------------------------------
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// NOTE: Use the provided path for TCPDF
require_once('tcpdf/tcpdf_main/tcpdf.php');
// NOTE: Replace 'db_connect.php' with your actual database connection file
include 'db_connect.php'; 

// -----------------------------------------------------
// 2. Retrieve and Validate URL Parameters
// -----------------------------------------------------
function get_safe_data($param, $default = '')
{
    return isset($_REQUEST[$param]) ? $_REQUEST[$param] : $default; // Not using htmlspecialchars here since we are generating PDF, but cleaning the input is still wise
}

$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');

// Basic validation (same as in contribution_by_date.php)
if ($partner_id === 0 || $agreement_id === 0 || empty($start_date) || empty($end_date)) {
    // Show a simple error message instead of redirecting from a PDF script
    die('Error: Missing required parameters for PDF generation.');
}

// -----------------------------------------------------
// 3. Data Fetching (Re-using the logic from contribution_by_date.php)
// -----------------------------------------------------
$partner_name = "N/A";
$partner_code = "N/A";
$commitment_amount = 0;
$commitment_currency = '';
$total_paid = 0;
$contributions = [];

// Fetch Partner and Agreement Details
$sql_partner = "
    SELECT 
        p.partner_name, 
        p.partner_code, 
        pa.commitment_amount, 
        pa.commitment_currency
    FROM Partners p
    JOIN Partnership_Agreements pa ON p.partner_id = pa.partner_id
    WHERE p.partner_id = ? AND pa.agreement_id = ?
";
$stmt_partner = $conn->prepare($sql_partner);
if ($stmt_partner) {
    $stmt_partner->bind_param("ii", $partner_id, $agreement_id);
    $stmt_partner->execute();
    $result_partner = $stmt_partner->get_result();
    if ($row_partner = $result_partner->fetch_assoc()) {
        $partner_name = $row_partner['partner_name'];
        $partner_code = $row_partner['partner_code'];
        $commitment_amount = $row_partner['commitment_amount'];
        $commitment_currency = $row_partner['commitment_currency'];
    }
    $stmt_partner->close();
}

// Fetch Financial Contributions within the Date Range
$sql_contributions = "
    SELECT 
        fc.amount, 
        fc.contribution_date, 
        fc.description, 
        sc.category_name,
        fc.currency
    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 ?
        AND sc.category_name = 'Partnership Contribution'
    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();
}
// NOTE: Reopen the connection if you need to use it again, but for this script, we can close it here.
$conn->close();

$remaining_amount = $commitment_amount - $total_paid;

// -----------------------------------------------------
// 4. TCPDF Generation
// -----------------------------------------------------

// Extend TCPDF to create a custom Header and Footer
class MYPDF extends TCPDF {
    // Page header
    public function Header() {
        // You can add a logo or title here
        $this->SetFont('helvetica', 'B', 12);
        $this->Cell(0, 15, 'Financial Contribution Report', 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->SetLineWidth(0.5);
        $this->Line(5, 20, 205, 20); // Horizontal line
    }

    // Page footer
    public function Footer() {
        $this->SetY(-15);
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

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

// Set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your System Name');
$pdf->SetTitle('Contributions for ' . $partner_name);
$pdf->SetSubject('Financial Contribution Report');

// Set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 'Financial Contribution Report', 'Generated: ' . date('Y-m-d'));

// Set margins
$pdf->SetMargins(15, 25, 15);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

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

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

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

// --- HTML Content for PDF ---

// 1. Partner and Summary Details
$html_summary = '
<h2 style="text-align: center; color: #333;">Financial Contributions by Date Range</h2>
<hr style="height: 1px; background-color: #ccc;">

<table cellspacing="0" cellpadding="5" border="1" style="width: 100%; border-collapse: collapse; background-color: #e9ecef;">
    <tr>
        <td colspan="2" style="font-weight: bold; background-color: #ddd;">Partner Details</td>
    </tr>
    <tr>
        <td style="width: 50%;"><strong>Partner Name:</strong> ' . $partner_name . '</td>
        <td style="width: 50%;"><strong>Start Date:</strong> ' . $start_date . '</td>
    </tr>
    <tr>
        <td><strong>Partner Code:</strong> ' . $partner_code . '</td>
        <td><strong>End Date:</strong> ' . $end_date . '</td>
    </tr>
    <tr>
        <td><strong>Commitment Amount:</strong> ' . number_format($commitment_amount, 2) . ' ' . $commitment_currency . '</td>
        <td style="color: darkgreen;"><strong>Total Paid in Range:</strong> ' . number_format($total_paid, 2) . ' ' . $commitment_currency . '</td>
    </tr>
    <tr>
        <td colspan="2" style="text-align: right; color: ' . (($remaining_amount > 0) ? 'red' : 'red') . '; font-weight: bold;">
            Remaining Commitment (Current Period): ' . number_format($remaining_amount, 2) . ' ' . $commitment_currency . '
        </td>
    </tr>
</table>
<br><br>
';

// Write the summary block
$pdf->writeHTML($html_summary, true, false, true, false, '');

// 2. Contributions Table Title
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Write(0, 'Individual Contributions (' . $start_date . ' to ' . $end_date . ')', '', 0, 'L', true, 0, false, false, 0);
$pdf->Ln(2);

// 3. Contributions Table
// Re-balanced Column Widths:
// 5% (#) + 18% (Date) + 17% (Amount) + 10% (Currency) + 50% (Description) = 100%
$html_table = '
<table cellspacing="0" cellpadding="5" border="1" style="width: 100%; border-collapse: collapse;">
    <thead>
        <tr style="background-color: #f2f2f2;">
            <th style="width: 5%; font-weight: bold;">#</th>
            <th style="width: 18%; font-weight: bold;">Date</th>
            <th style="width: 17%; font-weight: bold;">Amount</th>
            <th style="width: 10%; font-weight: bold;">Curr.</th>
            <th style="width: 50%; font-weight: bold;">Description</th>
        </tr>
    </thead>
    <tbody>
';

if (count($contributions) > 0) {
    $index = 1;
    foreach ($contributions as $contribution) {
        $html_table .= '
        <tr>
            <td style="width: 5%;">' . $index++ . '</td>
            <td style="width: 18%;">' . trim($contribution['contribution_date']) . '</td>
            <td style="width: 17%;">' . number_format($contribution['amount'], 2) . '</td>
            <td style="width: 10%;">' . $contribution['currency'] . '</td>
            <td style="width: 50%;">' . $contribution['description'] . '</td>
        </tr>
        ';
    }
} else {
    $html_table .= '
        <tr>
            <td colspan="5" style="text-align: center;">No partnership contributions recorded in this date range.</td>
        </tr>
    ';
}

$html_table .= '
    </tbody>
</table>
';

// Write the contributions table
$pdf->SetFont('helvetica', '', 9);
$pdf->writeHTML($html_table, true, false, true, false, '');


// Close and output PDF document
$pdf_filename = 'Contribution_Report_' . $partner_code . '_' . $start_date . '_to_' . $end_date . '.pdf';
$pdf->Output($pdf_filename, 'I'); // 'I' for Inline output (browser) or 'D' for Download

?>