<?php
// views/project/public_portfolio.php
defined('BASEPATH') OR exit('No direct script access allowed');

// Prepare model data
$model_info = $model_info ?: [];
$images = $images ?: [];
$all_image_ids = array_column($images, 'id');

// Function to extract model name
function getModelName($model_info, $pdf_name) {
    if (!empty($model_info['model_name'])) {
        return strtoupper($model_info['model_name']);
    }
    
    // Extract from PDF filename
    $name = preg_replace('/\.pdf$/i', '', $pdf_name);
    $name = preg_replace('/[0-9\-_]/', ' ', $name);
    $name = trim($name);
    
    // Convert to proper case and then uppercase
    $name = ucwords(strtolower($name));
    
    return strtoupper($name);
}

// Function to get measurements
function getMeasurement($model_info, $key) {
    $measurements = [
        'height' => ['model_height', 'height'],
        'chest' => ['model_chest', 'chest', 'model_chest_size'],
        'waist' => ['model_waist', 'waist', 'model_waist_size'],
        'hips' => ['model_hips', 'hips', 'model_hips_size'],
        'shoe_size' => ['model_shoe_size', 'shoe_size']
    ];
    
    if (isset($measurements[$key])) {
        foreach ($measurements[$key] as $field) {
            if (!empty($model_info[$field])) {
                return $model_info[$field];
            }
        }
    }
    
    return '';
}

// Function to split images into pages of 3
function paginateImages($images, $perPage = 3) {
    $pages = [];
    $pageCount = ceil(count($images) / $perPage);
    
    for ($i = 0; $i < $pageCount; $i++) {
        $pages[] = array_slice($images, $i * $perPage, $perPage);
    }
    
    return $pages;
}

// Get model name
$model_name = getModelName($model_info, $pdf_name);

// Get measurements
$height = getMeasurement($model_info, 'height');
$chest = getMeasurement($model_info, 'chest');
$waist = getMeasurement($model_info, 'waist');
$hips = getMeasurement($model_info, 'hips');
$shoe_size = getMeasurement($model_info, 'shoe_size');

// Get Instagram info
$instagram_handle = $model_info['instagram_handle'] ?? '';
$instagram_url = $model_info['instagram_url'] ?? '';

// Get extracted details text
$extracted_details = $model_info['extracted_text'] ?? $model_info['extracted_details'] ?? '';

// Paginate images (3 per page)
$image_pages = paginateImages($images, 3);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo htmlspecialchars($model_name); ?> Portfolio | GO Productions</title>
  <meta name="description" content="Professional model portfolio - <?php echo htmlspecialchars($model_name); ?> - GO Productions">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
  <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
  
  <style>
    /* EXACT DESIGN FROM PREVIEW PORTFOLIO - MINIMAL CHANGES */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Inter', sans-serif;
      background-color: #f7f7f7;
      color: #141414;
      min-height: 100vh;
      padding: 40px;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }

    /* Model Page Container */
    .model-page {
      background: white;
      padding: 40px;
      margin-bottom: 40px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      page-break-after: always;
      position: relative;
    }

    /* Last page shouldn't have page break */
    .model-page:last-child {
      page-break-after: avoid;
    }

    /* Header */
    .model-page header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 24px;
    }

    .model-name {
      font-family: 'Bebas Neue', sans-serif;
      font-size: 72px;
      font-weight: 400;
      letter-spacing: 0.02em;
      line-height: 1;
    }

    .stats-container {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      width: 400px;
    }

    .measurements-row {
      display: flex;
      gap: 32px;
      text-align: right;
      margin-bottom: 15px;
    }

    .stats-column {
      display: flex;
      flex-direction: column;
      gap: 2px;
    }

    .stat {
      font-size: 12px;
      font-weight: 400;
      letter-spacing: 0.05em;
    }

    /* EXTRACTED DETAILS */
    .extracted-details {
      font-size: 11px;
      color: #666666;
      line-height: 1.4;
      text-align: right;
      max-width: 400px;
      max-height: 100px;
      overflow: hidden;
      word-wrap: break-word;
    }

    /* Photo Grid */
    .model-page main {
      flex: 1;
      display: flex;
      align-items: center;
      margin-bottom: 30px;
    }

    .photo-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 4px;
      width: 100%;
    }

    .photo-container {
      aspect-ratio: 3 / 4;
      overflow: hidden;
      position: relative;
    }

    .photo-container img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }

    /* Footer */
    .model-page footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 24px;
      padding-top: 20px;
      border-top: 1px solid #e0e0e0;
    }

    .footer-links {
      display: flex;
      gap: 24px;
    }

    .footer-link {
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 0.05em;
      color: #141414;
      text-decoration: underline;
      text-underline-offset: 4px;
      transition: opacity 0.2s ease;
    }

    .footer-link:hover {
      opacity: 0.7;
    }

    .logo {
      width: 200px;
      height: auto;
    }

    /* Print Controls */
    .print-controls {
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 1000;
      display: flex;
      gap: 10px;
      background: rgba(255, 255, 255, 0.95);
      padding: 15px;
      border-radius: 10px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      border: 1px solid #e0e0e0;
    }

    .control-btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px 20px;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 600;
      text-decoration: none;
      cursor: pointer;
      transition: all 0.3s ease;
      background: #000000;
      color: #ffffff;
      border: 2px solid #000000;
      font-family: 'Inter', sans-serif;
    }

    .control-btn:hover {
      background: #333333;
      border-color: #333333;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    }

    .control-btn.secondary {
      background: transparent;
      color: #333333;
      border: 2px solid #e0e0e0;
    }

    .control-btn.secondary:hover {
      background: #f5f5f5;
      border-color: #333333;
    }

    /* Page Number */
    .page-number {
      position: absolute;
      bottom: 10px;
      right: 10px;
      font-size: 12px;
      color: #999;
    }

    /* Print Styles */
    @media print {
      .print-controls {
        display: none !important;
      }
      
      body {
        padding: 0 !important;
        background: white !important;
        margin: 0 !important;
      }
      
      .model-page {
        padding: 20px;
        margin: 0;
        box-shadow: none;
        height: 100vh;
        page-break-after: always;
        break-after: page;
      }
      
      .model-page:last-child {
        page-break-after: avoid;
        break-after: avoid;
      }
      
      @page {
        size: legal landscape;
        margin: 0.5in;
      }
      
      /* Ensure footer stays at bottom */
      .model-page {
        display: flex;
        flex-direction: column;
        min-height: 100vh;
      }
      
      .model-page main {
        flex: 1;
      }
      
      .logo {
        width: 220px !important;
      }
      
      .extracted-details {
        max-height: none;
        overflow: visible;
      }
    }

    /* Responsive */
    @media (max-width: 768px) {
      body {
        padding: 24px;
      }

      .model-page {
        padding: 24px;
      }

      .model-name {
        font-size: 48px;
      }

      .stats-container {
        width: 300px;
      }
      
      .measurements-row {
        gap: 16px;
      }

      .stat {
        font-size: 10px;
      }

      .logo {
        width: 180px;
      }
      
      .print-controls {
        top: 10px;
        right: 10px;
        left: 10px;
        justify-content: center;
        flex-wrap: wrap;
      }
    }

    @media (max-width: 480px) {
      .model-page header {
        flex-direction: column;
        gap: 16px;
      }

      .stats-container {
        width: 100%;
        align-items: flex-start;
      }
      
      .measurements-row {
        text-align: left;
      }
      
      .extracted-details {
        text-align: left;
      }

      .model-name {
        font-size: 36px;
      }

      .photo-grid {
        grid-template-columns: 1fr;
        gap: 4px;
      }

      .model-page footer {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
      }
      
      .logo {
        width: 160px;
      }
    }
  </style>
  
  
  <!-- Font Awesome for Icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
  <!-- Print Controls -->
<div class="print-controls">
    <button onclick="printPortfolio()" class="control-btn">
        <i class="fas fa-print"></i> Print Portfolio
    </button>
    <button onclick="downloadPDFOptimized()" class="control-btn">
        <i class="fas fa-download"></i> Save as PDF
    </button>
</div>

  <?php 
  $page_counter = 1;
  // Create a page for each set of 3 images
  foreach ($image_pages as $page_num => $page_images):
  ?>
  
  <div class="model-page"
     data-instagram="<?php echo htmlspecialchars($instagram_url ?: ''); ?>"
     data-portfolio="<?php echo base_url('portfolio/' . $project_id . '/' . urlencode(strtolower(str_replace(' ', '-', $model_name)))); ?>">
    <!-- Header -->
    <header>
      <h1 class="model-name"><?php echo htmlspecialchars($model_name); ?></h1>
      
      <div class="stats-container">
        <!-- Measurements Row -->
        <div class="measurements-row">
          <div class="stats-column">
            <?php if (!empty($height)): ?>
            <p class="stat">HEIGHT- <?php echo htmlspecialchars($height); ?></p>
            <?php endif; ?>
            
            <?php if (!empty($shoe_size)): ?>
            <p class="stat">SHOE SIZE – <?php echo htmlspecialchars($shoe_size); ?></p>
            <?php endif; ?>
            
            <?php if (!empty($hips)): ?>
            <p class="stat">HIPS – <?php echo htmlspecialchars($hips); ?></p>
            <?php endif; ?>
          </div>
          <div class="stats-column">
            <?php if (!empty($chest)): ?>
            <p class="stat">CHEST- <?php echo htmlspecialchars($chest); ?></p>
            <?php endif; ?>
            
            <?php if (!empty($waist)): ?>
            <p class="stat">WAIST- <?php echo htmlspecialchars($waist); ?></p>
            <?php endif; ?>
          </div>
        </div>
        
        <!-- EXTRACTED DETAILS -->
        <?php if (!empty($extracted_details)): ?>
        <div class="extracted-details">
          <?php echo nl2br(htmlspecialchars($extracted_details)); ?>
        </div>
        <?php endif; ?>
      </div>
    </header>

    <!-- Photo Grid - 3 images per page -->
    <main>
      <div class="photo-grid">
        <?php foreach ($page_images as $image): ?>
          <div class="photo-container">
            <img src="<?php echo base_url($image['image_path']); ?>" 
                 alt="<?php echo htmlspecialchars($image['image_name']); ?>"
                 data-image-id="<?php echo $image['id']; ?>">
          </div>
        <?php endforeach; ?>
        
        <!-- Fill empty slots if less than 3 images -->
        <?php for ($i = count($page_images); $i < 3; $i++): ?>
          <div class="photo-container" style="background: #f5f5f5;"></div>
        <?php endfor; ?>
      </div>
    </main>

    <!-- Footer -->
    <footer>
      <div class="footer-links">
        <?php if (!empty($instagram_url)): ?>
        <a href="<?php echo htmlspecialchars($instagram_url); ?>" 
           target="_blank" 
           class="footer-link">
          INSTAGRAM
        </a>
        <?php elseif (!empty($instagram_handle)): ?>
        <a href="https://instagram.com/<?php echo ltrim(htmlspecialchars($instagram_handle), '@'); ?>" 
           target="_blank" 
           class="footer-link">
          INSTAGRAM
        </a>
        <?php else: ?>
        <span class="footer-link">INSTAGRAM</span>
        <?php endif; ?>
        <span class="footer-link">PORTFOLIO</span>
      </div>
      
      <!-- GO Productions Logo -->
      <img src="<?php echo base_url('assets/images/logogo.png'); ?>" 
           alt="GO Productions" 
           class="logo">
    </footer>
    
    <!-- Page Number -->
    <div class="page-number">Page <?php echo $page_counter++; ?></div>
  </div>
  
  <?php 
  endforeach; // End image pages loop
  ?>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<script>
// Store image IDs for JavaScript
const allImageIds = <?php echo json_encode($all_image_ids); ?>;

// Function to trigger print dialog
function printPortfolio() {
    window.print();
}

// Optimized PDF generation
async function downloadPDFOptimized() {
    showLoading('Preparing PDF...');
    
    const printStyles = `
        <style>
            @media print {
                body { margin: 0 !important; padding: 0 !important; }
                .print-controls { display: none !important; }
            }
            
            .model-page {
                width: 13in !important;
                height: 8.5in !important;
                margin: 0 !important;
                padding: 0.5in !important;
                box-sizing: border-box;
                position: relative;
                background: white !important;
                break-after: page;
            }
            
            .model-page:last-child {
                break-after: avoid;
            }
        </style>
    `;
    
    const styleEl = document.createElement('style');
    styleEl.textContent = printStyles;
    document.head.appendChild(styleEl);
    
    try {
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF({
            orientation: 'landscape',
            unit: 'in',
            format: 'legal'
        });
        
        const modelPages = document.querySelectorAll('.model-page');
        
        for (let i = 0; i < modelPages.length; i++) {
            updateLoadingProgress(`Capturing page ${i + 1}/${modelPages.length}...`);
            
            const canvas = await html2canvas(modelPages[i], {
                scale: 1.5,
                useCORS: true,
                backgroundColor: '#ffffff',
                imageTimeout: 15000,
                removeContainer: true,
                onclone: function(clonedDoc) {
                    const images = clonedDoc.querySelectorAll('img');
                    images.forEach(img => {
                        if (!img.complete) {
                            img.onload = function() {
                                console.log('Image loaded:', img.src);
                            };
                            img.onerror = function() {
                                console.log('Image failed:', img.src);
                                img.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjQwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMzAwIiBoZWlnaHQ9IjQwMCIgZmlsbD0iI2Y1ZjVmNSIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0iQXJpYWwiIGZvbnQtc2l6ZT0iMTQiIGZpbGw9IiNjY2NjY2MiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj5JbWFnZSBMb2FkaW5nLi4uPC90ZXh0Pjwvc3ZnPg==';
                            };
                        }
                    });
                }
            });
            
            const imgData = canvas.toDataURL('image/jpeg', 0.92);
            
            if (i > 0) {
                pdf.addPage();
            }
            
            const pageWidth = pdf.internal.pageSize.getWidth();
            const pageHeight = pdf.internal.pageSize.getHeight();
            const margin = 0.5;
            const contentWidth = pageWidth - (2 * margin);
            const contentHeight = (canvas.height * contentWidth) / canvas.width;
            
            const xPos = margin;
            const yPos = margin + (pageHeight - contentHeight - (2 * margin)) / 2;
            
            pdf.addImage(imgData, 'JPEG', xPos, yPos, contentWidth, contentHeight);
            
            // Add clickable links
            const instagramURL = modelPages[i].dataset.instagram || "";
            const portfolioURL = modelPages[i].dataset.portfolio || "";
            
            const linkY = pageHeight - 0.9;
            const instaX = 0.8;
            const portX = 3.0;
            const boxWidth = 1.2;
            const boxHeight = 0.3;
            
            if (instagramURL) {
                pdf.link(instaX, linkY, boxWidth, boxHeight, { url: instagramURL });
            }
            
            if (portfolioURL) {
                pdf.link(portX, linkY, boxWidth, boxHeight, { url: portfolioURL });
            }
            
            pdf.setFontSize(9);
            pdf.setTextColor(100);
            pdf.text(`Page ${i + 1}`, pageWidth - 1, pageHeight - 0.3);
        }
        
        styleEl.remove();
        
        const modelName = '<?php echo addslashes($model_name); ?>';
        pdf.save(`portfolio-${modelName}.pdf`);
        
        hideLoading();
        showNotification('PDF ready for download!', 'success');
        
    } catch (error) {
        styleEl.remove();
        hideLoading();
        console.error('Error:', error);
        showNotification('Failed to generate PDF. Try printing instead.', 'error');
    }
}

// Loading functions
function showLoading(message = 'Processing...') {
    let loadingModal = document.getElementById('loadingModal');
    if (!loadingModal) {
        loadingModal = document.createElement('div');
        loadingModal.id = 'loadingModal';
        loadingModal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.85);
            z-index: 10001;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            color: white;
            font-family: 'Inter', sans-serif;
        `;
        
        loadingModal.innerHTML = `
            <div style="text-align: center; max-width: 500px; padding: 30px;">
                <div class="spinner" style="
                    width: 60px;
                    height: 60px;
                    border: 4px solid rgba(255,255,255,0.3);
                    border-top: 4px solid #ffffff;
                    border-radius: 50%;
                    animation: spin 1s linear infinite;
                    margin: 0 auto 20px auto;
                "></div>
                <h3 id="loadingMessage" style="margin: 0 0 10px 0; font-weight: 500;">${message}</h3>
                <div id="loadingProgress" style="margin-top: 10px; font-size: 14px; opacity: 0.8;"></div>
            </div>
        `;
        
        const style = document.createElement('style');
        style.textContent = `
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(loadingModal);
    } else {
        loadingModal.style.display = 'flex';
        document.getElementById('loadingMessage').textContent = message;
    }
}

function updateLoadingProgress(message) {
    const progressEl = document.getElementById('loadingProgress');
    if (progressEl) {
        progressEl.textContent = message;
    }
}

function hideLoading() {
    const loadingModal = document.getElementById('loadingModal');
    if (loadingModal) {
        loadingModal.style.display = 'none';
    }
}

// Notification function
function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 25px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10002;
        background: ${type === 'success' ? '#28a745' : '#dc3545'};
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        animation: slideIn 0.3s ease;
    `;
    
    notification.innerHTML = `
        <div style="display: flex; align-items: center; gap: 10px;">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}" 
               style="font-size: 18px;"></i>
            <span>${message}</span>
        </div>
    `;
    
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
    `;
    document.head.appendChild(style);
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => notification.remove(), 300);
    }, 4000);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    console.log('Public Portfolio loaded. Model: <?php echo addslashes($model_name); ?>');
});
</script>
</body>
</html>

