<!-- project_view.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GO Productions - <?php echo $project->name; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Black & White Theme Styles */
        :root {
            --sidebar-bg: #000000;
            --main-bg: #f8f9fa;
            --text-color: #333333;
            --light-text: #6c757d;
            --card-bg: #ffffff;
            --white: #ffffff;
            --black: #000000;
            --border-color: #e0e0e0;
            --hover-color: #f8f9fa;
            --success-color: #000000ff;
            --danger-color: #dc3545;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, 'Roboto', sans-serif;
        }

        body {
            background-color: var(--main-bg);
            color: var(--text-color);
            line-height: 1.6;
        }

        /* Main Content */
        .main-content {
            background-color: var(--main-bg);
            padding: 30px;
            min-height: 100vh;
            transition: margin-top 0.3s ease;
        }

        .main-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 30px;
        }

        .main-header h1 {
            font-size: 32px;
            color: var(--text-color);
            margin-bottom: 8px;
            font-weight: 800;
            letter-spacing: -0.5px;
        }

        .welcome-text {
            font-size: 15px;
            color: var(--light-text);
            font-weight: 500;
        }

        /* Fixed Header Actions */
        .fixed-actions-header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: var(--card-bg);
            padding: 15px 30px;
            border-bottom: 2px solid var(--border-color);
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            z-index: 1000;
            display: none;
            align-items: center;
            justify-content: space-between;
        }

        .fixed-actions-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .selected-count {
            font-weight: 700;
            color: var(--black);
            font-size: 16px;
        }

        .fixed-actions-right {
            display: flex;
            gap: 10px;
        }

        /* Button Styles */
        .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;
            text-align: center;
            line-height: 1;
        }

        .btn-primary {
            background: var(--black);
            color: var(--white);
            border: 2px solid var(--black);
        }

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

        .btn-secondary {
            background: transparent;
            color: var(--text-color);
            border: 2px solid var(--border-color);
        }

        .btn-secondary:hover {
            background: var(--border-color);
            border-color: var(--text-color);
            transform: translateY(-2px);
        }

        .btn-success {
            background: var(--success-color);
            color: white;
            border: 2px solid var(--success-color);
        }

        .btn-success:hover {
            background: #000000ff;
            border-color: #070f09ff;
            transform: translateY(-2px);
        }

        .btn-danger {
            background: var(--danger-color);
            color: white;
            border: 2px solid var(--danger-color);
        }

        .btn-danger:hover {
            background: #c82333;
            border-color: #c82333;
            transform: translateY(-2px);
        }

        .btn-outline {
            background: transparent;
            color: var(--text-color);
            border: 2px solid var(--border-color);
        }

        .btn-outline:hover {
            background: var(--border-color);
            transform: translateY(-2px);
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 12px;
        }

        /* Content Area */
        .content-area {
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        }

        .navigation-buttons {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        /* Bulk Actions Bar */
        .bulk-actions-bar {
            background: #f8f9fa;
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 2px solid var(--border-color);
            display: none;
        }

        .bulk-actions-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .bulk-actions-buttons {
            display: flex;
            gap: 10px;
        }

        /* Project Stats */
        .project-stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: var(--card-bg);
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            border: 1px solid var(--border-color);
        }

        .stat-card h3 {
            margin: 0;
            color: var(--black);
            font-size: 24px;
        }

        .stat-card p {
            margin: 5px 0 0;
            color: var(--light-text);
        }

        /* PDF Cards */
        .pdf-card {
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 30px;
            background: var(--card-bg);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .pdf-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .pdf-header h3 {
            margin: 0;
            color: var(--text-color);
            font-size: 1.4rem;
        }

        .pdf-header-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .badge {
            background: var(--success-color);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
        }

        /* Model Section */
        .model-section {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 25px;
        }

        .model-info {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .model-info h4 {
            margin-top: 0;
            color: var(--text-color);
            border-bottom: 2px solid var(--black);
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            font-weight: bold;
            display: block;
            margin-bottom: 5px;
            color: var(--text-color);
        }

        .form-input, .form-textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
            background: var(--card-bg);
            color: var(--text-color);
        }

        .form-input:focus, .form-textarea:focus {
            outline: none;
            border-color: var(--black);
        }

        .form-textarea {
            resize: vertical;
            min-height: 120px;
        }

        .form-actions {
            display: flex;
            gap: 10px;
            margin-top: 25px;
        }

        /* Images Section */
        .images-section h4 {
            margin: 0 0 15px 0;
            color: var(--text-color);
        }

        .images-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .image-actions {
            display: flex;
            gap: 10px;
        }

        .images-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 15px;
            max-height: 500px;
            overflow-y: auto;
            padding: 10px;
        }

        .image-item {
            text-align: center;
            position: relative;
            transition: transform 0.3s ease;
        }

        .image-item:hover {
            transform: translateY(-5px);
        }

        .image-checkbox {
            position: absolute;
            top: 5px;
            left: 5px;
            z-index: 2;
        }

        .image-checkbox input {
            transform: scale(1.2);
            cursor: pointer;
        }

        .selectable-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid var(--border-color);
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .selectable-image.selected {
            border-color: var(--black);
            box-shadow: 0 0 15px rgba(0,0,0,0.3);
        }

        .image-meta {
            font-size: 11px;
            color: var(--light-text);
            margin-top: 8px;
            background: #f8f9fa;
            padding: 4px;
            border-radius: 4px;
        }

        /* Additional Photos */
        .additional-photos-section {
            margin-top: 40px;
        }

        .photos-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .photos-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }

        .photo-item {
            text-align: center;
            position: relative;
            transition: transform 0.3s ease;
        }

        .photo-item:hover {
            transform: translateY(-5px);
        }

        /* Empty States */
        .empty-state {
            text-align: center;
            padding: 40px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 2px dashed var(--border-color);
        }

        .empty-state h3 {
            color: var(--text-color);
            margin-bottom: 10px;
        }

        .empty-state p {
            color: var(--light-text);
            margin-bottom: 15px;
        }

        /* Modal Styles */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            z-index: 10000;
            display: none;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .modal-content {
            background: var(--card-bg);
            padding: 30px;
            border-radius: 12px;
            max-width: 600px;
            width: 90%;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            border: 1px solid var(--border-color);
        }

        .modal-image {
            max-width: 100%;
            max-height: 80vh;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.5);
        }

        .modal-close {
            position: absolute;
            top: -50px;
            right: 0;
            background: #fff;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            cursor: pointer;
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }

        /* Loading Modal */
        .loading-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 10001;
            display: none;
            justify-content: center;
            align-items: center;
        }

        .loading-content {
            background: white;
            padding: 30px;
            border-radius: 12px;
            text-align: center;
            min-width: 300px;
        }

        .spinner {
            width: 3rem;
            height: 3rem;
            border: 2px solid var(--border-color);
            border-top: 2px solid var(--black);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Drag & Drop Area */
        .drag-drop-area {
            border: 3px dashed var(--border-color);
            border-radius: 12px;
            padding: 40px;
            text-align: center;
            background: #f8f9fa;
            margin-bottom: 20px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .drag-drop-area:hover {
            border-color: var(--black);
            background: #f0f0f0;
        }

        .drag-drop-area i {
            font-size: 48px;
            color: var(--light-text);
            margin-bottom: 15px;
        }

        .drag-drop-area h4 {
            color: var(--text-color);
            margin-bottom: 10px;
        }

        .drag-drop-area p {
            color: var(--light-text);
            margin-bottom: 15px;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .main-content {
                padding: 20px;
            }
            
            .content-area {
                padding: 20px;
            }
            
            .model-section {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .images-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            }
            
            .fixed-actions-header {
                padding: 12px 20px;
                flex-direction: column;
                gap: 10px;
            }
            
            .fixed-actions-left,
            .fixed-actions-right {
                width: 100%;
                justify-content: center;
            }
            
            .bulk-actions-content {
                flex-direction: column;
                gap: 15px;
            }
            
            .bulk-actions-buttons {
                flex-wrap: wrap;
                justify-content: center;
            }
        }

        @media (max-width: 480px) {
            .main-content {
                padding: 15px;
            }
            
            .pdf-card {
                padding: 15px;
            }
            
            .project-stats-grid {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .images-header {
                flex-direction: column;
                gap: 10px;
                align-items: flex-start;
            }
            
            .image-actions {
                width: 100%;
                justify-content: space-between;
            }
        }
    </style>
</head>
<body>
    <!-- Fixed Header Actions -->
    <div class="fixed-actions-header" id="fixedActionsHeader">
        <div class="fixed-actions-left">
            <span class="selected-count" id="fixedSelectedCount">0</span> images selected
        </div>
         <button onclick="previewSelectedImages()" class="btn btn-primary btn-sm">
        <i class="fas fa-eye"></i> Preview
    </button>
        

        <div class="fixed-actions-right">
            <button onclick="exportSelectedToPDF()" class="btn btn-success btn-sm">
                <i class="fas fa-file-pdf"></i> Export to PDF
            </button>
            <button onclick="deleteSelectedImages()" class="btn btn-danger btn-sm">
                <i class="fas fa-trash"></i> Delete
            </button>
            <button onclick="clearSelection()" class="btn btn-secondary btn-sm">
                <i class="fas fa-times"></i> Clear
            </button>
        </div>
    </div>

    <main class="main-content" id="mainContent">
        <header class="main-header">
            <div>
                <h1>PROJECT: <?php echo strtoupper($project->name); ?></h1>
                <p class="welcome-text">View and manage all extracted data from your PDFs</p>
            </div>
        </header>

        <div class="content-area">
            <!-- Navigation -->
            <div class="navigation-buttons">
                  <button onclick="previewAllImages()" class="btn btn-primary">
        <i class="fas fa-eye"></i> Preview All Images
    </button>
                <a href="<?php echo site_url('project'); ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Projects
                </a>
                <a href="<?php echo site_url('project/upload/' . $project->id); ?>" class="btn btn-primary">
                    <i class="fas fa-file-upload"></i> Upload More PDFs
                </a>
                <button onclick="refreshProject()" class="btn btn-outline">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>

            <!-- Bulk Actions Bar -->
            <div class="bulk-actions-bar" id="bulkActionsBar">
                <div class="bulk-actions-content">
                    <div>
                        <strong id="selectedCount">0</strong> images selected
                    </div>
                    <div class="bulk-actions-buttons">
                           <button onclick="previewSelectedImages()" class="btn btn-primary">
        <i class="fas fa-eye"></i> Preview Portfolio
    </button>
                        <button onclick="exportSelectedToPDF()" class="btn btn-success">
                            <i class="fas fa-file-pdf"></i> Export Selected to PDF
                        </button>
                        <button onclick="deleteSelectedImages()" class="btn btn-danger">
                            <i class="fas fa-trash"></i> Delete Selected
                        </button>
                        <button onclick="clearSelection()" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Clear Selection
                        </button>
                    </div>
                </div>
            </div>

            <!-- Project Stats -->
            <div class="project-stats-grid">
                <div class="stat-card">
                    <h3><?php echo count($project_data['pdfs']); ?></h3>
                    <p>Total PDFs</p>
                </div>
                <div class="stat-card">
                    <h3><?php echo array_sum(array_column($project_data['pdfs'], 'image_count')); ?></h3>
                    <p>Extracted Images</p>
                </div>
                <div class="stat-card">
                    <h3><?php echo count($project_data['additional_photos']); ?></h3>
                    <p>Additional Photos</p>
                </div>
            </div>

            <!-- PDFs and Extracted Data -->
            <?php if (!empty($project_data['pdfs'])): ?>
                <div class="pdfs-section">
                    <h2>Models & Extracted Data</h2>
                    <?php foreach ($project_data['pdfs'] as $pdf): ?>
                        <div class="pdf-card">
                            <!-- PDF Header -->
                            <div class="pdf-header">
                                <h3><i class="fas fa-file-pdf"></i> <?php echo htmlspecialchars($pdf['original_name']); ?></h3>
                                <div class="pdf-header-actions">
                                    <span class="badge">
                                        <?php echo $pdf['image_count']; ?> images
                                    </span>
                                    <button onclick="toggleModelSection(<?php echo $pdf['id']; ?>)" class="btn btn-sm btn-outline">
                                        Toggle View
                                    </button>
                                </div>
                            </div>

                            <div id="model-section-<?php echo $pdf['id']; ?>">
                                <div class="model-section">
                                    <!-- Model Information -->
                                    <div class="model-info">
                                        <h4>Model Information</h4>
                                        <form class="model-form" data-pdf-id="<?php echo $pdf['id']; ?>">
                                            <div class="form-group">
                                                <label class="form-label">Model Name:</label>
                                                <input type="text" name="model_name" value="<?php echo htmlspecialchars($pdf['model_name'] ?? $pdf['original_name']); ?>"
                                                       class="form-input">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label class="form-label">Instagram Handle:</label>
                                                <input type="text" name="instagram_handle" value="<?php echo htmlspecialchars($pdf['instagram_handle'] ?? ''); ?>"
                                                       class="form-input" placeholder="@username">
                                            </div>
                                            
                                            
                                            <div class="form-group">
                                                <label class="form-label">Instagram URL:</label>
                                                <input type="url" name="instagram_url" value="<?php echo htmlspecialchars($pdf['instagram_url'] ?? ''); ?>"
                                                       class="form-input" placeholder="https://instagram.com/username">
                                            </div>
                                            

                                            <div class="form-group">
                                                <label class="form-label">Extracted Details:</label>
                                                <textarea name="extracted_details" rows="6" class="form-textarea"
                                                          placeholder="All extracted text from PDF will appear here"><?php echo htmlspecialchars($pdf['extracted_details'] ?? $pdf['extracted_text'] ?? ''); ?></textarea>
                                            </div>
                                            

                                            <div class="form-actions">
                                                <button type="button" onclick="updateModelInfo(<?php echo $pdf['id']; ?>)" 
                                                        class="btn btn-primary">
                                                    <i class="fas fa-save"></i> Update Info
                                                </button>
                                                <button type="button" onclick="openModelImageUpload(<?php echo $pdf['id']; ?>)" 
                                                        class="btn btn-success">
                                                    <i class="fas fa-camera"></i> Add Images
                                                </button>
                                            </div>
                                        </form>
                                    </div>

                                    <!-- Extracted Images -->
                                    <div class="images-section">
                                        <div class="images-header">
                                            <h4>Model Images</h4>
                                            <div class="image-actions">
                                                <button onclick="selectAllImages(<?php echo $pdf['id']; ?>)" class="btn btn-sm btn-outline">
                                                    Select All
                                                </button>
                                                <button onclick="openModelImageUpload(<?php echo $pdf['id']; ?>)" class="btn btn-sm btn-success">
                                                    <i class="fas fa-plus"></i> Add More Images
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <?php if (!empty($pdf['images'])): ?>
                                            <div class="images-grid">
                                                <?php foreach ($pdf['images'] as $image): ?>
                                                    <div class="image-item">
                                                        <div class="image-checkbox">
                                                            <input type="checkbox" class="image-selector" data-image-id="<?php echo $image['id']; ?>" data-pdf-id="<?php echo $pdf['id']; ?>">
                                                        </div>
                                                        <img src="<?php echo base_url($image['image_path']); ?>" 
                                                             alt="<?php echo htmlspecialchars($image['image_name']); ?>"
                                                             class="selectable-image"
                                                             data-image-id="<?php echo $image['id']; ?>"
                                                             onclick="toggleImageSelection(<?php echo $image['id']; ?>)">
                                                        <div class="image-meta">
                                                            <?php if ($image['page_number'] > 0): ?>
                                                                Page <?php echo $image['page_number']; ?>
                                                            <?php else: ?>
                                                                Added Manually
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            <div class="empty-state">
                                                <p>No images extracted from this PDF yet.</p>
                                                <button onclick="openModelImageUpload(<?php echo $pdf['id']; ?>)" class="btn btn-primary">
                                                    Add First Image
                                                </button>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <h3>No PDFs Processed Yet</h3>
                    <p>Start by uploading some PDFs to see extracted data here.</p>
                    <a href="<?php echo site_url('project/upload/' . $project->id); ?>" class="btn btn-primary">
                        Upload PDFs
                    </a>
                </div>
            <?php endif; ?>

            <!-- Additional Photos Section -->
            <div class="additional-photos-section">
                <div class="photos-header">
                    <h2>Additional Project Photos</h2>
                    <button onclick="openPhotoUpload()" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add More Photos
                    </button>
                </div>

                <?php if (!empty($project_data['additional_photos'])): ?>
                    <div class="photos-grid">
                        <?php foreach ($project_data['additional_photos'] as $photo): ?>
                            <div class="photo-item">
                                <div class="image-checkbox">
                                    <input type="checkbox" class="image-selector" data-image-id="<?php echo $photo['id']; ?>" data-type="additional">
                                </div>
                                <img src="<?php echo base_url($photo['image_path']); ?>" 
                                     alt="<?php echo htmlspecialchars($photo['image_name']); ?>"
                                     class="selectable-image"
                                     data-image-id="<?php echo $photo['id']; ?>"
                                     data-type="additional"
                                     onclick="toggleImageSelection(<?php echo $photo['id']; ?>, 'additional')">
                                <div class="image-meta">
                                    <?php echo date('M j, Y', strtotime($photo['uploaded_at'])); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <p>No additional photos added yet.</p>
                        <button onclick="openPhotoUpload()" class="btn btn-primary">
                            Add Your First Photo
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <!-- Image Modal -->
    <div class="modal" id="imageModal">
        <div class="modal-content">
            <img id="modalImage" src="" class="modal-image">
            <div id="modalImageName" style="color: white; margin-top: 15px; font-size: 16px;"></div>
            <button onclick="closeImageModal()" class="modal-close">×</button>
        </div>
    </div>

    <!-- Photo Upload Modal -->
    <div class="modal" id="photoUploadModal">
        <div class="modal-content">
            <h3 style="margin-top: 0;">Upload Additional Photo</h3>
            <form id="photoUploadForm" enctype="multipart/form-data">
                <input type="file" name="additional_photo" accept="image/*" required 
                       style="width: 100%; padding: 15px; border: 2px dashed #ddd; border-radius: 8px; margin-bottom: 20px; background: #f8f9fa;">
                <div class="form-actions">
                    <button type="button" onclick="closePhotoUpload()" class="btn btn-secondary">Cancel</button>
                    <button type="submit" class="btn btn-primary">Upload Photo</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Model Image Upload Modal -->
    <div class="modal" id="modelImageUploadModal">
        <div class="modal-content">
            <h3 style="margin-top: 0;">Add Images to Model</h3>
            
            <!-- Drag & Drop Area -->
            <div id="dragDropArea" class="drag-drop-area">
                <i class="fas fa-cloud-upload-alt"></i>
                <h4>Drag & Drop Images Here</h4>
                <p>or click to select multiple images</p>
                <button type="button" onclick="document.getElementById('modelImageFiles').click()" class="btn btn-primary">
                    Select Images
                </button>
            </div>

            <!-- File Input -->
            <form id="modelImageUploadForm" enctype="multipart/form-data">
                <input type="hidden" name="pdf_id" id="modelImagePdfId">
                <input type="file" name="model_image[]" id="modelImageFiles" accept="image/*" multiple required 
                       style="display: none;" onchange="handleModelImageSelect(this)">
            </form>

            <!-- Preview Area -->
            <div id="imagePreviewArea" style="display: none; margin-top: 20px;">
                <h5>Selected Images:</h5>
                <div id="imagePreviews" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 10px; max-height: 200px; overflow-y: auto; padding: 10px; border: 1px solid #eee; border-radius: 8px;"></div>
            </div>

            <div class="form-actions">
                <button type="button" onclick="closeModelImageUpload()" class="btn btn-secondary">Cancel</button>
                <button type="button" onclick="uploadModelImages()" class="btn btn-primary">Upload Images</button>
            </div>
        </div>
    </div>

    <!-- Loading Modal -->
    <div class="loading-modal" id="loadingModal">
        <div class="loading-content">
            <div class="spinner"></div>
            <h5 id="loadingMessage">Processing...</h5>
            <div id="loadingProgress" style="margin-top: 10px;"></div>
        </div>
    </div>

    <script>
    // Global variables
    let selectedImages = new Set();
    let currentModelImages = [];

    // Fixed header functionality
    window.addEventListener('scroll', function() {
        const fixedHeader = document.getElementById('fixedActionsHeader');
        const mainContent = document.getElementById('mainContent');
        
        if (selectedImages.size > 0 && window.scrollY > 100) {
            fixedHeader.style.display = 'flex';
            mainContent.style.marginTop = '70px';
        } else {
            fixedHeader.style.display = 'none';
            mainContent.style.marginTop = '0';
        }
    });

    function toggleModelSection(pdfId) {
        const section = document.getElementById(`model-section-${pdfId}`);
        if (section.style.display === 'none') {
            section.style.display = 'block';
        } else {
            section.style.display = 'none';
        }
    }

    // Image Selection Functions
    function toggleImageSelection(imageId, type = 'model') {
        const checkbox = document.querySelector(`.image-selector[data-image-id="${imageId}"]`);
        const image = document.querySelector(`.selectable-image[data-image-id="${imageId}"]`);
        
        if (checkbox.checked) {
            selectedImages.delete(imageId);
            checkbox.checked = false;
            image.classList.remove('selected');
        } else {
            selectedImages.add(imageId);
            checkbox.checked = true;
            image.classList.add('selected');
        }
        
        updateBulkActionsBar();
    }

    function selectAllImages(pdfId) {
        const checkboxes = document.querySelectorAll(`.image-selector[data-pdf-id="${pdfId}"]`);
        const images = document.querySelectorAll(`.selectable-image[data-image-id]`);
        
        checkboxes.forEach(checkbox => {
            const imageId = checkbox.getAttribute('data-image-id');
            const image = document.querySelector(`.selectable-image[data-image-id="${imageId}"]`);
            
            if (!checkbox.checked) {
                selectedImages.add(imageId);
                checkbox.checked = true;
                image.classList.add('selected');
            }
        });
        
        updateBulkActionsBar();
    }

    function clearSelection() {
        selectedImages.clear();
        const checkboxes = document.querySelectorAll('.image-selector');
        const images = document.querySelectorAll('.selectable-image');
        
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
        });
        
        images.forEach(image => {
            image.classList.remove('selected');
        });
        
        updateBulkActionsBar();
    }

    function updateBulkActionsBar() {
        const bulkActionsBar = document.getElementById('bulkActionsBar');
        const selectedCount = document.getElementById('selectedCount');
        const fixedSelectedCount = document.getElementById('fixedSelectedCount');
        
        selectedCount.textContent = selectedImages.size;
        fixedSelectedCount.textContent = selectedImages.size;
        
        if (selectedImages.size > 0) {
            bulkActionsBar.style.display = 'block';
        } else {
            bulkActionsBar.style.display = 'none';
        }
    }
    // Add this function to preview all images
function previewAllImages() {
    // Select all image checkboxes
    const allCheckboxes = document.querySelectorAll('.image-selector');
    const allImageIds = Array.from(allCheckboxes).map(cb => cb.getAttribute('data-image-id'));
    
    if (allImageIds.length === 0) {
        showNotification('No images available to preview', 'error');
        return;
    }
    
    // Create a form to submit the data
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '<?php echo site_url("project/preview_portfolio/"); ?><?php echo $project->id; ?>';
    form.target = '_blank';
    form.style.display = 'none';
    
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'image_ids';
    input.value = JSON.stringify(allImageIds);
    
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

    // Bulk Actions
    function deleteSelectedImages() {
        if (selectedImages.size === 0) {
            showNotification('Please select images to delete', 'error');
            return;
        }
        
        if (confirm(`Are you sure you want to delete ${selectedImages.size} selected images?`)) {
            showLoading('Deleting selected images...');
            
            const deletePromises = Array.from(selectedImages).map(imageId => {
                return fetch(`<?php echo site_url('project/delete_image/'); ?>${imageId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(result => {
                    if (!result.success) {
                        throw new Error(result.error);
                    }
                    return imageId;
                });
            });
            
            Promise.all(deletePromises)
                .then(deletedIds => {
                    hideLoading();
                    // Remove deleted images from DOM
                    deletedIds.forEach(imageId => {
                        const imageElement = document.querySelector(`.image-item [data-image-id="${imageId}"]`);
                        if (imageElement) {
                            imageElement.closest('.image-item').remove();
                        }
                    });
                    
                    showNotification(`Successfully deleted ${deletedIds.length} images`, 'success');
                    clearSelection();
                    setTimeout(() => location.reload(), 1000);
                })
                .catch(error => {
                    hideLoading();
                    showNotification('Error deleting some images: ' + error.message, 'error');
                });
        }
    }

    function exportSelectedToPDF() {
        if (selectedImages.size === 0) {
            showNotification('Please select images to export', 'error');
            return;
        }
        
        showLoading('Generating PDF...');
        
        const imageIds = Array.from(selectedImages);
        const projectId = '<?php echo $project->id; ?>';
        
        fetch(`<?php echo site_url('project/export_images_pdf'); ?>`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                image_ids: imageIds,
                project_id: projectId
            })
        })
        .then(response => response.blob())
        .then(blob => {
            hideLoading();
            // Create download link
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = `model-portfolio-${projectId}.pdf`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            
            showNotification('PDF exported successfully!', 'success');
            clearSelection();
        })
        .catch(error => {
            hideLoading();
            showNotification('Error generating PDF: ' + error, 'error');
        });
    }

    // Enhanced Drag & Drop for Model Images
    function handleModelImageSelect(input) {
        const files = input.files;
        currentModelImages = Array.from(files);
        displayImagePreviews(currentModelImages);
    }

    function displayImagePreviews(files) {
        const previewArea = document.getElementById('imagePreviewArea');
        const previewsContainer = document.getElementById('imagePreviews');
        
        previewsContainer.innerHTML = '';
        
        if (files.length === 0) {
            previewArea.style.display = 'none';
            return;
        }
        
        previewArea.style.display = 'block';
        
        files.forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.createElement('div');
                preview.style.position = 'relative';
                preview.innerHTML = `
                    <img src="${e.target.result}" style="width: 100%; height: 80px; object-fit: cover; border-radius: 4px;">
                    <button type="button" onclick="removeImagePreview(${index})" 
                            style="position: absolute; top: 2px; right: 2px; background: #dc3545; color: white; border: none; border-radius: 50%; width: 20px; height: 20px; font-size: 12px; cursor: pointer;">×</button>
                `;
                previewsContainer.appendChild(preview);
            };
            reader.readAsDataURL(file);
        });
    }
// Add this function to your project_view.php JavaScript
function previewSelectedImages() {
    if (selectedImages.size === 0) {
        showNotification('Please select images to preview', 'error');
        return;
    }
    
    const imageIds = Array.from(selectedImages);
    const projectId = '<?php echo $project->id; ?>';
    
    // Create a form to submit the data
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '<?php echo site_url("project/preview_portfolio/"); ?>' + projectId;
    form.target = '_blank';
    form.style.display = 'none';
    
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'image_ids';
    input.value = JSON.stringify(imageIds);
    
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}
    function removeImagePreview(index) {
        currentModelImages.splice(index, 1);
        displayImagePreviews(currentModelImages);
        
        // Update file input
        const dataTransfer = new DataTransfer();
        currentModelImages.forEach(file => dataTransfer.items.add(file));
        document.getElementById('modelImageFiles').files = dataTransfer.files;
    }

    function uploadModelImages() {
        if (currentModelImages.length === 0) {
            showNotification('Please select images to upload', 'error');
            return;
        }
        
        const pdfId = document.getElementById('modelImagePdfId').value;
        const formData = new FormData();
        
        currentModelImages.forEach((file, index) => {
            formData.append(`model_image_${index}`, file);
        });
        formData.append('pdf_id', pdfId);
        
        showLoading(`Uploading ${currentModelImages.length} images...`);
        
        fetch(`<?php echo site_url('project/upload_model_images_bulk/'); ?>${pdfId}`, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            hideLoading();
            if (result.success) {
                showNotification('Images uploaded successfully!', 'success');
                closeModelImageUpload();
                setTimeout(() => location.reload(), 1000);
            } else {
                showNotification('Error: ' + result.error, 'error');
            }
        })
        .catch(error => {
            hideLoading();
            showNotification('Error uploading images: ' + error, 'error');
        });
    }

    // Drag & Drop functionality
    const dragDropArea = document.getElementById('dragDropArea');
    const modelImageFiles = document.getElementById('modelImageFiles');

    dragDropArea.addEventListener('click', () => {
        modelImageFiles.click();
    });

    dragDropArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        dragDropArea.style.background = '#e3f2fd';
        dragDropArea.style.borderColor = '#2196f3';
    });

    dragDropArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        dragDropArea.style.background = '#f8f9fa';
        dragDropArea.style.borderColor = '#ddd';
    });

    dragDropArea.addEventListener('drop', (e) => {
        e.preventDefault();
        dragDropArea.style.background = '#f8f9fa';
        dragDropArea.style.borderColor = '#ddd';
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            modelImageFiles.files = files;
            handleModelImageSelect(modelImageFiles);
        }
    });

    // Loading functions
    function showLoading(message = 'Processing...') {
        document.getElementById('loadingMessage').textContent = message;
        document.getElementById('loadingModal').style.display = 'flex';
    }

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

    function updateLoadingProgress(progress) {
        document.getElementById('loadingProgress').textContent = progress;
    }

    // Existing functions
    function updateModelInfo(pdfId) {
        const form = document.querySelector(`.model-form[data-pdf-id="${pdfId}"]`);
        const formData = new FormData(form);
        const data = {
            model_name: formData.get('model_name'),
            instagram_handle: formData.get('instagram_handle'),
            instagram_url: formData.get('instagram_url'),
            extracted_details: formData.get('extracted_details'),
            project_id: '<?php echo $project->id; ?>'
        };

        fetch(`<?php echo site_url('project/update_model_info/'); ?>${pdfId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                showNotification('Model information updated successfully!', 'success');
            } else {
                showNotification('Error: ' + result.error, 'error');
            }
        })
        .catch(error => {
            showNotification('Error updating model information: ' + error, 'error');
        });
    }

    function openImageModal(imageSrc, imageName) {
        document.getElementById('modalImage').src = imageSrc;
        document.getElementById('modalImageName').textContent = imageName;
        document.getElementById('imageModal').style.display = 'flex';
    }

    function closeImageModal() {
        document.getElementById('imageModal').style.display = 'none';
    }

    function openPhotoUpload() {
        document.getElementById('photoUploadModal').style.display = 'flex';
    }

    function closePhotoUpload() {
        document.getElementById('photoUploadModal').style.display = 'none';
    }

    function openModelImageUpload(pdfId) {
        document.getElementById('modelImagePdfId').value = pdfId;
        document.getElementById('modelImageUploadModal').style.display = 'flex';
        // Reset form
        document.getElementById('modelImageFiles').value = '';
        document.getElementById('imagePreviewArea').style.display = 'none';
        currentModelImages = [];
    }

    function closeModelImageUpload() {
        document.getElementById('modelImageUploadModal').style.display = 'none';
    }

    function refreshProject() {
        location.reload();
    }

    function showNotification(message, type) {
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            font-weight: bold;
            z-index: 10001;
            transition: all 0.3s ease;
            background: ${type === 'success' ? '#28a745' : '#dc3545'};
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    // Close modals when clicking outside
    document.getElementById('imageModal').addEventListener('click', function(e) {
        if (e.target === this) closeImageModal();
    });

    document.getElementById('photoUploadModal').addEventListener('click', function(e) {
        if (e.target === this) closePhotoUpload();
    });

    document.getElementById('modelImageUploadModal').addEventListener('click', function(e) {
        if (e.target === this) closeModelImageUpload();
    });

    document.getElementById('loadingModal').addEventListener('click', function(e) {
        if (e.target === this) hideLoading();
    });

    // Close modals with Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeImageModal();
            closePhotoUpload();
            closeModelImageUpload();
            hideLoading();
        }
    });
    
    </script>
</body>
</html>