<?php
// pages/roster_export_view.php
requireRole('any');

$service_id = isset($_GET['service_id']) ? (int)$_GET['service_id'] : null;
if (!$service_id) die("Service not selected.");

$stmt = $pdo->prepare("SELECT * FROM services WHERE id = ?");
$stmt->execute([$service_id]);
$service = $stmt->fetch();
if (!$service) die("Service not found.");

$r_stmt = $pdo->prepare("SELECT id, status FROM rosters WHERE service_id = ?");
$r_stmt->execute([$service_id]);
$roster = $r_stmt->fetch();
$roster_id = $roster['id'] ?? null;
$roster_status = $roster['status'] ?? 'Draft';

if (!$roster_id) die("Roster not found.");

// Fetch assignments
$matrix = [];
$as_stmt = $pdo->prepare("SELECT * FROM roster_assignments WHERE roster_id = ?");
$as_stmt->execute([$roster_id]);
while ($row = $as_stmt->fetch()) {
    if (!isset($matrix[$row['role_name']])) $matrix[$row['role_name']] = [];
    $matrix[$row['role_name']][] = $row['person_name'];
}

require_once 'includes/role_config.php';

// Group sections for separate images
$export_sections = [
    [
        'title' => 'Tabernacle Operations',
        'subgroups' => [
            'Audio' => $role_categories['Tabernacle Audio Operations'],
            'Video' => $role_categories['Tabernacle Video Operations']
        ]
    ],
    [
        'title' => 'Additional Operations & Technical Support',
        'subgroups' => [
            'General' => $role_categories['Additional Operations & Technical Support']
        ]
    ],
    [
        'title' => 'Basement and Other Centres',
        'subgroups' => [
            'General' => $role_categories['Basement and Other Centres']
        ]
    ]
];
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
    <h1>Generate Sharing Images</h1>
    <a href="index.php?page=roster&service_id=<?php echo $service_id; ?>" class="btn" style="background:#444;">&laquo; Back to Roster</a>
</div>

<div class="alert alert-info">
    <i class="fas fa-info-circle"></i> We have split the schedule into <strong><?php echo count($export_sections); ?> sections</strong> to match the PDF layout. Click "Download as Image" for each section to share it on WhatsApp.
</div>

<div class="export-preview-grid">
    <?php foreach ($export_sections as $idx => $section): ?>
    <div class="export-card">
        <div class="export-card-header">
            <h3>Page <?php echo $idx + 1; ?>: <?php echo $section['title']; ?></h3>
            <button class="btn btn-sm btn-download" onclick="exportSection(<?php echo $idx; ?>, '<?php echo addslashes($section['title']); ?>')">
                <i class="fas fa-download"></i> Download as Image
            </button>
        </div>
        
        <!-- The actual container to capture -->
        <div id="capture-container-<?php echo $idx; ?>" class="capture-box">
            <div class="print-header">
                <h1>APOSTOLIC FAITH CHURCH</h1>
                <h2>OPERATIONS SCHEDULE</h2>
                <div class="status-badge-outline"><?php echo strtoupper($roster_status); ?></div>
            </div>
            
            <div class="print-date-line">
                SERVICE DATE: <?php echo strtoupper(date('l, F j, Y', strtotime($service['service_date']))); ?> | TYPE: <?php echo strtoupper($service['type']); ?>
            </div>
            
            <div class="print-section-header">
                <?php echo ($idx + 1) . ". " . $section['title']; ?>
            </div>
            
            <?php foreach ($section['subgroups'] as $sub_title => $roles): ?>
                <?php if ($sub_title !== 'General'): ?>
                    <div class="print-sub-title"><?php echo $sub_title; ?></div>
                <?php endif; ?>
                
                <table class="print-table">
                    <thead>
                        <tr>
                            <th style="width: 40%;">Assignment</th>
                            <th style="width: 60%;">Assigned Personnel</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($roles as $r): ?>
                        <tr>
                            <td><?php echo $r; ?></td>
                            <td><?php 
                                $vals = $matrix[$r] ?? [];
                                echo !empty($vals) ? implode(', ', $vals) : '<span style="color:#ccc;">---</span>';
                            ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endforeach; ?>
            
            <div class="print-footer">
                Generated from WCS Admin on <?php echo date('Y-m-d H:i'); ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
async function exportSection(id, title) {
    const el = document.getElementById('capture-container-' + id);
    const btn = event.currentTarget;
    const oldHtml = btn.innerHTML;
    
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    btn.disabled = true;
    
    try {
        const canvas = await html2canvas(el, {
            scale: 2,
            backgroundColor: '#ffffff',
            useCORS: true,
            logging: false
        });
        
        const link = document.createElement('a');
        link.download = `Schedule-${title.replace(/\s+/g, '_')}-${"<?php echo $service['service_date']; ?>"}.jpg`;
        link.href = canvas.toDataURL('image/jpeg', 0.9);
        link.click();
    } catch (err) {
        console.error(err);
        alert('Failed to generate image');
    } finally {
        btn.innerHTML = oldHtml;
        btn.disabled = false;
    }
}
</script>

<style>
    .export-preview-grid { display: flex; flex-direction: column; gap: 30px; margin-top: 20px; }
    .export-card { background: #222; border-radius: 8px; border: 1px solid #333; overflow: hidden; }
    .export-card-header { padding: 15px 20px; border-bottom: 1px solid #333; display: flex; justify-content: space-between; align-items: center; background: #2a2a2a; }
    .export-card-header h3 { margin: 0; font-size: 1.1rem; }
    
    /* CAPTURE BOX STYLING - MUST MATCH PDF CLOSELY */
    .capture-box {
        background: #ffffff !important; /* Force white background */
        color: #000000 !important;
        padding: 40px;
        width: 800px; /* Fixed width for consistent output */
        margin: 0 auto;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .print-header { text-align: center; margin-bottom: 20px; color: #000 !important; }
    .print-header h1 { font-size: 22px; margin: 0; letter-spacing: 1px; color: #000 !important; }
    .print-header h2 { font-size: 18px; margin: 5px 0; color: #333 !important; }
    .status-badge-outline { 
        display: inline-block; 
        border: 2px solid #000; 
        padding: 4px 12px; 
        font-weight: bold; 
        font-size: 12px; 
        margin-top: 5px;
        color: #000 !important;
    }
    
    .print-date-line { 
        border-top: 1px solid #000; 
        padding-top: 15px; 
        margin-bottom: 25px; 
        font-weight: bold; 
        font-size: 14px; 
        color: #000 !important;
    }
    
    .print-section-header {
        background: #f0f0f0 !important;
        border: 1px solid #000;
        padding: 10px;
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 15px;
        color: #000 !important;
    }
    
    .print-sub-title {
        font-weight: bold;
        text-decoration: underline;
        margin: 15px 0 10px 0;
        font-size: 14px;
        color: #000 !important;
    }
    
    .print-table { 
        width: 100%; 
        border-collapse: collapse; 
        margin-bottom: 15px; 
        background-color: #ffffff !important; 
    }
    .print-table th, .print-table td { 
        border: 1px solid #000000 !important; 
        padding: 10px; 
        font-size: 14px; 
        text-align: left; 
        color: #000000 !important;
        background-color: #ffffff !important; 
    }
    .print-table th { background: #f8f8f8 !important; font-weight: bold; }
    
    .print-footer { border-top: 1px dotted #ccc; padding-top: 10px; font-size: 10px; color: #888; text-align: right; }
    
    .btn-download { background: var(--success-color); color: #000; border: none; font-weight: bold; border-radius: 4px; padding: 8px 15px; cursor: pointer; }
</style>
