<?php
// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126
$jc = $data['jobcard'];
$settings = $data['settings'];

// Decide whether to show Partner details or System default details
$isPartner = !empty($jc->partner_name);

$headerName = $isPartner ? $jc->partner_name : ($settings['app_name'] ?? 'Jobcard Manager Pro');
$headerEmail = $isPartner ? $jc->partner_email : ($settings['contact_email'] ?? '');
$headerPhone = $isPartner ? $jc->partner_contact : ($settings['contact_mobile'] ?? '');

// Address Array for Header
if ($isPartner) {
    $headerAddr = array_filter([$jc->partner_street ?? '', $jc->partner_suburb ?? '', $jc->partner_city ?? '']);
} else {
    $headerAddr = array_filter([$settings['contact_address_street'] ?? '', $settings['contact_address_suburb'] ?? '', $settings['contact_address_city'] ?? '']);
}

// Duration Calculation
$duration = 'N/A';
if (!empty($jc->started_at) && !empty($jc->completed_at)) {
    $start = new DateTime($jc->started_at);
    $end = new DateTime($jc->completed_at);
    $diff = $start->diff($end);
    $hours = ($diff->days * 24) + $diff->h;
    $duration = $hours . 'h ' . $diff->i . 'm';
}

// Handle Image Base64 encoding for the PDF engine
$logoHtml = '';
if ($isPartner && !empty($jc->partner_logo)) {
    $logoPath = APPROOT . '/public/uploads/' . $jc->partner_logo;
    if (file_exists($logoPath)) {
        $type = pathinfo($logoPath, PATHINFO_EXTENSION);
        $dataUri = 'data:image/' . $type . ';base64,' . base64_encode(file_get_contents($logoPath));
        $logoHtml = '<img src="' . $dataUri . '" style="max-height: 60px; max-width: 250px; margin-bottom: 10px;">';
    }
} elseif (!$isPartner && !empty($settings['logo_light'])) {
    $logoPath = APPROOT . '/public/uploads/' . $settings['logo_light'];
    if (file_exists($logoPath)) {
        $type = pathinfo($logoPath, PATHINFO_EXTENSION);
        $dataUri = 'data:image/' . $type . ';base64,' . base64_encode(file_get_contents($logoPath));
        $logoHtml = '<img src="' . $dataUri . '" style="max-height: 60px; max-width: 250px; margin-bottom: 10px;">';
    }
} else {
    // Text Fallback
    $logoHtml = '<div class="title">' . htmlspecialchars($headerName) . '</div>';
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Jobcard <?php echo $jc->jobcard_number; ?></title>
    <style>
        body { font-family: Helvetica, Arial, sans-serif; font-size: 13px; color: #333; line-height: 1.4; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
        .header-table td { vertical-align: top; border: none; padding: 0; }
        .title { font-size: 24px; font-weight: bold; color: #1c70b4; margin-bottom: 5px; }
        .subtitle { font-size: 12px; color: #666; }
        .data-table th, .data-table td { border: 1px solid #ddd; padding: 10px; text-align: left; vertical-align: top; }
        .data-table th { background-color: #f8fafc; font-weight: bold; width: 30%; }
        .section-title { font-size: 16px; font-weight: bold; color: #1f2937; border-bottom: 2px solid #1c70b4; padding-bottom: 5px; margin-top: 30px; margin-bottom: 10px; }
        
        /* Layout overrides specifically for signatures */
        .signature-table { margin-top: 40px; border: none; }
        .signature-table td { border: none !important; width: 50%; text-align: center; padding: 10px; }
        .signature-img { height: 100px; max-width: 100%; border-bottom: 1px solid #333; margin-bottom: 10px; }
    </style>
</head>
<body>

    <table class="header-table">
        <tr>
            <td style="width: 50%;">
                <?php echo $logoHtml; ?>
                <div class="subtitle" style="margin-top: 10px;">
                    <strong><?php echo htmlspecialchars($headerName); ?></strong><br>
                    <?php if($headerEmail) echo htmlspecialchars($headerEmail) . '<br>'; ?>
                    <?php if($headerPhone) echo htmlspecialchars($headerPhone) . '<br>'; ?>
                    <?php if(!empty($headerAddr)) echo htmlspecialchars(implode(', ', $headerAddr)); ?>
                </div>
            </td>
            <td style="width: 50%; text-align: right;">
                <div style="font-size: 20px; font-weight: bold; color: #333;">JOBCARD</div>
                <div class="subtitle" style="font-size: 14px; font-weight: bold; color: #ef4444; margin-bottom: 15px;">
                    #<?php echo $jc->jobcard_number; ?>
                </div>
                <div class="subtitle" style="line-height: 1.6;">
                    <strong>Created:</strong> <?php echo date('Y-m-d H:i', strtotime($jc->created_at)); ?><br>
                    <strong>Completed:</strong> <?php echo $jc->completed_at ? date('Y-m-d H:i', strtotime($jc->completed_at)) : 'N/A'; ?><br>
                    <strong>Time On-Site:</strong> <?php echo $duration; ?>
                </div>
            </td>
        </tr>
    </table>

    <div class="section-title">Job Details</div>
    <table class="data-table">
        <tr>
            <th>Client</th>
            <td>
                <strong><?php echo htmlspecialchars($jc->client_name); ?></strong>
                <?php if(!empty($jc->company_name)): ?>
                    <br><span style="color: #666; font-size: 12px;"><?php echo htmlspecialchars($jc->company_name); ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <th>Client Address</th>
            <td>
                <?php 
                $clientAddr = array_filter([$jc->address_street, $jc->address_suburb, $jc->address_city, $jc->address_country]);
                echo htmlspecialchars(implode(', ', $clientAddr)); 
                ?>
            </td>
        </tr>
        
        <tr>
            <th>Contracting Company</th>
            <td>
                <strong><?php echo htmlspecialchars($settings['app_name'] ?? 'System Owner'); ?></strong><br>
                <?php 
                $sysContactArr = array_filter([$settings['contact_email'] ?? '', $settings['contact_mobile'] ?? '', $settings['contact_landline'] ?? '']);
                echo htmlspecialchars(implode(' | ', $sysContactArr));
                ?>
            </td>
        </tr>

        <?php if($isPartner): ?>
        <tr>
            <th>Partner Agency</th>
            <td>
                <strong><?php echo htmlspecialchars($jc->partner_name); ?></strong><br>
                <?php 
                $partnerContactArr = array_filter([$jc->partner_email ?? '', $jc->partner_contact ?? '']);
                echo htmlspecialchars(implode(' | ', $partnerContactArr));
                ?>
            </td>
        </tr>
        <?php endif; ?>

        <tr>
            <th>Service Technician</th>
            <td>
                <?php if (!empty($jc->tech_name)): ?>
                    <strong><?php echo htmlspecialchars($jc->tech_name); ?></strong><br>
                    <?php 
                    $techContactArr = array_filter([$jc->tech_email ?? '', $jc->tech_contact ?? '']);
                    echo htmlspecialchars(implode(' | ', $techContactArr));
                    ?>
                <?php else: ?>
                    <em>Unassigned</em>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <th>Work Requested</th>
            <td><?php echo nl2br(htmlspecialchars($jc->instructions)); ?></td>
        </tr>
    </table>

    <div class="section-title">Work Execution</div>
    <table class="data-table">
        <tr>
            <td style="background-color: #f8fafc; font-weight: bold;">Detailed Work Performed:</td>
        </tr>
        <tr>
            <td><?php echo nl2br(htmlspecialchars($jc->work_done)); ?></td>
        </tr>
    </table>

    <?php if(!empty($data['materials'])): ?>
    <div class="section-title">Materials Used</div>
    <table class="data-table">
        <tr>
            <th style="width: 70%;">Material / Description</th>
            <th style="width: 30%;">Quantity</th>
        </tr>
        <?php foreach($data['materials'] as $mat): ?>
        <tr>
            <td><?php echo htmlspecialchars($mat->material_name); ?></td>
            <td><?php echo htmlspecialchars($mat->quantity); ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php endif; ?>

    <!-- Signature Block Fixed with Table Layout -->
    <table class="signature-table">
        <tr>
            <td>
                <img src="<?php echo $jc->client_signature; ?>" class="signature-img">
                <div>
                    <strong>Client Signature</strong><br>
                    <?php echo htmlspecialchars($jc->client_sign_name ?? $jc->client_name); ?>
                </div>
            </td>
            <td>
                <img src="<?php echo $jc->tech_signature; ?>" class="signature-img">
                <div>
                    <strong>Technician Signature</strong><br>
                    <?php echo htmlspecialchars($jc->tech_sign_name ?? $jc->tech_name); ?>
                </div>
            </td>
        </tr>
    </table>

</body>
</html>