<?php
// generate_pdf.php

// Ensure NO whitespace or newlines before this opening PHP tag.
// Double-check this file and db_connect.php for any characters outside the PHP tags.
ob_start();
// 1. Include the TCPDF library first.
require_once('tcpdf/tcpdf_main/tcpdf.php'); // Adjust this path as needed
// 2. Include the database connection.
include 'db_connect.php';

// Function to format phone numbers (it's better to put this in a separate utilities file)
function formatPhoneNumber($phone) {
    $phone = preg_replace('/[^\d+]/', '', $phone);
    if (strpos($phone, '+255') === 0) {
        return '255' . substr($phone, 4);
    } elseif (strpos($phone, '0') === 0) {
        return '255' . substr($phone, 1);
    }
    return $phone;
}

// --- Fetch existing data based on ID from the URL parameter ---
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid partner ID for PDF generation.");
}
$partner_id = $_GET['id'];

// Fetch partner details and agreement details in one go to reduce database queries
$stmt = $conn->prepare("
    SELECT
        p.*,
        pa.*,
        pt.type_name
    FROM
        Partners p
    LEFT JOIN
        Partnership_Agreements pa ON p.partner_id = pa.partner_id
    LEFT JOIN
        Partnership_Types pt ON pa.partnership_type_id = pt.partnership_type_id
    WHERE
        p.partner_id = ?
    ORDER BY
        pa.created_at DESC
    LIMIT 1
");

$stmt->bind_param("i", $partner_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    $data = $result->fetch_assoc();
    $partner_data = [
        'partner_id' => $data['partner_id'],
        'partner_code' => $data['partner_code'],
        'partner_name' => $data['partner_name'],
        'contact_person_name' => $data['contact_person_name'],
        'is_organization' => $data['is_organization'],
        'member_id' => $data['member_id'],
        'phone_number1' => $data['phone_number1'],
        'phone_number2' => $data['phone_number2'],
        'email_address' => $data['email_address'],
        'address' => $data['address'],
        'description' => $data['description'],
        'profile_image_url' => $data['profile_image_url']
    ];
    $agreement_data = [
        'partnership_type_id' => $data['partnership_type_id'],
        'commitment_amount' => $data['commitment_amount'],
        'commitment_currency' => $data['commitment_currency'],
        'commitment_frequency' => $data['commitment_frequency'],
        'start_date' => $data['start_date'],
        'end_date' => $data['end_date'],
        'status' => $data['status'],
        'description' => $data['description'], // Note: This will be the partner's description if agreement doesn't have one
    ];
    $partnership_type_name = $data['type_name'] ?? '';
} else {
    die("Partner not found for PDF 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('Your Organization');
$pdf->SetTitle('Partnership Document - ' . $partner_data['partner_name']);
$pdf->SetSubject('Partnership Agreement');
$pdf->SetKeywords('TCPDF, PDF, partnership, agreement, form');

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

// Set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

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

// --- Header Banner and Title ---
$banner_path = 'uploads/banner2.png'; // Make sure this path is correct
if (file_exists($banner_path)) {
    $pdf->Image($banner_path, 5, 5, 200, 30, '', '', '', false, 300, '', false, false, 0);
}
/*
Image(
    $file,          // Path to the image file (e.g., 'images/banner.png').
    $x = '',        // X-coordinate (horizontal position) of the image's top-left corner.
    $y = '',        // Y-coordinate (vertical position) of the image's top-left corner.
    $w = 0,         // Width of the image. If 0 and $h is set, the width is calculated.
    $h = 0,         // Height of the image. If 0 and $w is set, the height is calculated.
    $type = '',     // Image format (e.g., 'JPG', 'PNG'). Usually detected automatically.
    $link = '',     // URL for a hyperlink if the image is clickable.
    $align = '',    // Alignment of the image within the given coordinates ('L', 'C', 'R').
    $resize = false,// A boolean to enable or disable automatic resizing to fit $w and $h.
    $dpi = 300,     // Resolution for the image in DPI.
    $palign = '',   // Horizontal alignment of the image on the page ('L', 'C', 'R', 'J').
    $ismask = false,// A boolean to specify if the image is a transparency mask.
    $imgmask = false,// ID of the image to be used as a mask.
    $border = 0,    // Border around the image (e.g., '1', 'TLBR').
    $fitbox = false,// A boolean to fit the image inside a specified box, preserving the aspect ratio.
    $hidden = false,// A boolean to make the image hidden.
    $fitonpage = false, // A boolean to fit the image on a single page if it is too large.
    $alt = false,   // Alternative text for accessibility.
    $altimgs = array() // An array of alternative images for different resolutions.
)

*/



// Set a new Y position below the banner
$pdf->SetY(35);
$pdf->SetTextColor(0, 0, 255); // Blue color
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 10, 'PARTNERSHIP FORM', 0, 1, 'C', 0, '', 0, false, 'T', 'M');
$pdf->Ln(5); // Add a little space
$pdf->SetTextColor(0, 0, 0); // Reset to black

// --- Partner Profile Image at top-right ---
$partner_image_path = $partner_data['profile_image_url'];
// Check if the image file exists before trying to display it
if (!empty($partner_image_path) && file_exists($partner_image_path)) {
    list($width, $height) = getimagesize($partner_image_path);
    $image_ratio = $height / $width;
    $image_width = 40; // Desired width
    $image_height = $image_width * $image_ratio; // Calculate height
    $pdf->Image($partner_image_path, 160, 40, $image_width, $image_height, '', '', '', false, 300, '', false, false, 0);
}

// --- PDF Content Structure using a classic, clean table layout ---
$pdf->SetFont('helvetica', '', 11);
$html = '
<style>
    .section-title {
        font-size: 14pt;
        font-weight: bold;
        color: #444444;
        margin-top: 15px;
        margin-bottom: 5px;
        border-bottom: 1px solid #cccccc;
    }
    .data-label {
        font-weight: bold;
        color: #666666;
        width: 35%;
    }
    .data-value {
        width: 65%;
    }
    table {
        width: 100%;
        border-collapse: collapse;
    }
    td {
        padding: 8px;
        border-bottom: 1px solid #dddddd;
        line-height: 1.4;
    }
</style>';

//$html .= '<h1>Partnership Document</h1>';
//$html .= '<p></p>';
$html .= '<p><b>PartnerID :</b> ' . htmlspecialchars($partner_data['partner_code']) . '</p>';
$html .= '<p><b>Date of Generation:</b> ' . date('Y-m-d H:i:s') . '</p>';
$html .= '<hr>';
    
// Partner Details Section
$html .= '<h2 class="section-title">1. Partner Details</h2>';
$html .= '<table>';
$html .= '<tr><td class="data-label">Partner Name:</td><td class="data-value">' . htmlspecialchars($partner_data['partner_name']) . '</td></tr>';
$html .= '<tr><td class="data-label">Contact Person:</td><td class="data-value">' . htmlspecialchars($partner_data['contact_person_name']) . '</td></tr>';
$html .= '<tr><td class="data-label">Is Organization?:</td><td class="data-value">' . ($partner_data['is_organization'] == 1 ? 'Yes' : 'No') . '</td></tr>';
if (!empty($partner_data['member_id'])) {
    $html .= '<tr><td class="data-label">Member ID:</td><td class="data-value">' . htmlspecialchars($partner_data['member_id']) . '</td></tr>';
}
$html .= '<tr><td class="data-label">Phone Number 1:</td><td class="data-value">' . htmlspecialchars($partner_data['phone_number1']) . '</td></tr>';
if (!empty($partner_data['phone_number2'])) {
    $html .= '<tr><td class="data-label">Phone Number 2:</td><td class="data-value">' . htmlspecialchars($partner_data['phone_number2']) . '</td></tr>';
}
$html .= '<tr><td class="data-label">Email Address:</td><td class="data-value">' . htmlspecialchars($partner_data['email_address']) . '</td></tr>';
$html .= '<tr><td class="data-label">Address:</td><td class="data-value">' . htmlspecialchars($partner_data['address']) . '</td></tr>';
$html .= '<tr><td class="data-label">Description:</td><td class="data-value">' . nl2br(htmlspecialchars($partner_data['description'])) . '</td></tr>';
$html .= '</table>';

// Partnership Agreement Section
$html .= '<h2 class="section-title">2. Partnership Agreement</h2>';
$html .= '<table>';
$html .= '<tr><td class="data-label">Partnership Type:</td><td class="data-value">' . htmlspecialchars($partnership_type_name) . '</td></tr>';
$html .= '<tr><td class="data-label">Commitment Amount:</td><td class="data-value">' . htmlspecialchars($agreement_data['commitment_amount']) . ' ' . htmlspecialchars($agreement_data['commitment_currency']) . '</td></tr>';
$html .= '<tr><td class="data-label">Frequency:</td><td class="data-value">' . htmlspecialchars($agreement_data['commitment_frequency']) . '</td></tr>';
$html .= '<tr><td class="data-label">Start Date:</td><td class="data-value">' . htmlspecialchars($agreement_data['start_date']) . '</td></tr>';
$html .= '<tr><td class="data-label">End Date:</td><td class="data-value">' . (empty($agreement_data['end_date']) ? 'N/A' : htmlspecialchars($agreement_data['end_date'])) . '</td></tr>';
$html .= '<tr><td class="data-label">Status:</td><td class="data-value">' . htmlspecialchars($agreement_data['status']) . '</td></tr>';
$html .= '<tr><td class="data-label">Agreement Description:</td><td class="data-value">' . nl2br(htmlspecialchars($agreement_data['description'])) . '</td></tr>';
$html .= '</table>';

$pdf->writeHTML($html, true, false, true, false, '');

// Close and output PDF document, forcing it to download
$pdf->Output('partnership_document_' . $partner_data['partner_code'] . '.pdf', 'I');
ob_end_flush();
exit;