<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Project extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        $this->load->model('Project_model');
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->library('Pdf_service');
        
        if (!$this->session->userdata('logged_in')) {
            redirect('auth/login');
        }
    }
    public function update_model_agency() {
    try {
        $json_data = file_get_contents('php://input');
        $data = json_decode($json_data, true);
        
        if (!$data) {
            throw new Exception('No data received');
        }
        
        $pdf_id = $data['pdf_id'];
        $agency_id = $data['agency_id'];
        
        // Update in database
        $this->db->where('pdf_id', $pdf_id);
        $this->db->update('extracted_data', ['agency_id' => $agency_id]);
        
        echo json_encode(['success' => true, 'message' => 'Agency updated successfully']);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}
    // Add this to your Project controller
public function preview_portfolio($project_id) {
    try {
        $data['page_title'] = 'Preview Portfolio';
        
        // Get selected images from POST or GET
        $image_ids = $this->input->post('image_ids') ?: $this->input->get('image_ids');
        
        if (!$image_ids) {
            throw new Exception('No images selected for preview');
        }
        
        if (is_string($image_ids)) {
            $image_ids = json_decode($image_ids, true);
        }
        
        // Get images data
        $images = [];
        $model_data = [
            'name' => '',
            'height' => '',
            'chest' => '',
            'waist' => '',
            'hips' => '',
            'shoe_size' => '',
            'instagram' => '',
            'contact' => '',
            'specialties' => '',
            'details' => '',
            'instagram_url' => ''
        ];
        
        foreach ($image_ids as $image_id) {
            // Get image from database
            $image = $this->db->get_where('extracted_images', ['id' => $image_id])->row_array();
            if ($image) {
                $images[] = $image;
                
                // Get model data from the first image's PDF
                if (empty($model_data['name'])) {
                    $pdf_data = $this->db->get_where('project_pdfs', ['id' => $image['pdf_id']])->row_array();
                    if ($pdf_data) {
                        $extracted_data = $this->db->get_where('extracted_data', ['pdf_id' => $image['pdf_id']])->row_array();
                        if ($extracted_data) {
                            $model_data = array_merge($model_data, $extracted_data);
                        }
                        $model_data['name'] = $pdf_data['original_name'] ?? 'Model Portfolio';
                    }
                }
            }
        }
        
        if (empty($images)) {
            throw new Exception('No valid images found');
        }
        
        $data['images'] = $images;
        $data['model_data'] = $model_data;
        $data['model_name'] = $model_data['name'];
        $data['project_id'] = $project_id;

        
        // Load the preview view without header/sidebar/footer
        $this->load->view('project/preview_portfolio', $data);
        
    } catch (Exception $e) {
        // Show error page
        show_error($e->getMessage(), 400);
    }
}
    // Add this method to your Project controller
public function upload_model_images_bulk($pdf_id) {
    try {
        $uploaded_files = [];
        
        // Get all uploaded files
        foreach ($_FILES as $key => $file) {
            if (strpos($key, 'model_image_') === 0 && $file['error'] === UPLOAD_ERR_OK) {
                $uploaded_files[] = $file;
            }
        }
        
        if (empty($uploaded_files)) {
            throw new Exception('No valid image files received.');
        }
        
        $success_count = 0;
        $error_messages = [];
        
        foreach ($uploaded_files as $file) {
            $temp_path = $file['tmp_name'];
            
            $post_data = [
                'model_image' => new CURLFile($temp_path, $file['type'], $file['name'])
            ];
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => 'http://127.0.0.1:5000/upload-model-image/' . $pdf_id,
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => $post_data,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code === 200) {
                $result = json_decode($response, true);
                if ($result['success']) {
                    $success_count++;
                } else {
                    $error_messages[] = $file['name'] . ': ' . $result['error'];
                }
            } else {
                $error_messages[] = $file['name'] . ': Upload failed';
            }
        }
        
        if ($success_count > 0) {
            $message = "Successfully uploaded {$success_count} images";
            if (!empty($error_messages)) {
                $message .= ". Errors: " . implode(', ', $error_messages);
            }
            echo json_encode(['success' => true, 'message' => $message]);
        } else {
            throw new Exception('All uploads failed: ' . implode(', ', $error_messages));
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}

public function search() {
    $data['page_title'] = 'Search Projects';
    $data['user'] = $this->User_model->get_user_by_id($this->session->userdata('user_id'));
    $data['python_service_available'] = $this->pdf_service->is_service_healthy();
    
    $this->load->view('templates/header', $data);
    $this->load->view('templates/sidebar', $data);
    $this->load->view('project/search_projects', $data);
    $this->load->view('templates/footer');
}

public function get_all_projects_data() {
    try {
        $projects = $this->Project_model->get_all_projects();
        $projects_data = [];
        
        foreach ($projects as $project) {
            $project_data = $this->Project_model->get_project_data($project->id);
            $projects_data[] = [
                'id' => $project->id,
                'name' => $project->name,
                'description' => $project->description,
                'status' => $project->status,
                'created_at' => $project->created_at,
                'models' => $project_data['pdfs']
            ];
        }
        
        echo json_encode([
            'success' => true,
            'projects' => $projects_data
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
}

public function export_images_pdf() {
    try {
         set_time_limit(300); // 5 minutes
        ini_set('memory_limit', '512M'); // or even '1G' if needed
        ini_set('max_execution_time', 300);
        
        $json_data = file_get_contents('php://input');
        $data = json_decode($json_data, true);
        $json_data = file_get_contents('php://input');
        $data = json_decode($json_data, true);
        
        if (!$data || !isset($data['image_ids']) || !isset($data['project_id'])) {
            throw new Exception('Invalid request data');
        }
        
        $image_ids = $data['image_ids'];
        $project_id = $data['project_id'];
        
        // Get images data from database
        $this->load->model('Project_model');
        $images_data = [];
        
        foreach ($image_ids as $image_id) {
            $image = $this->Project_model->get_image_by_id($image_id);
            if ($image) {
                $pdf_data = $this->Project_model->get_pdf_by_id($image->pdf_id);
                $model_data = $this->Project_model->get_model_data_by_pdf_id($image->pdf_id);
                
                $images_data[] = [
                    'image_path' => $image->image_path,
                    'image_name' => $image->image_name,
                    'model_name' => $model_data->model_name ?? 'Unknown Model',
                    'instagram' => $model_data->instagram_handle ?? '',
                    'contact' => $model_data->contact_info ?? '',
                    'details' => $model_data->extracted_details ?? ''
                ];
            }
        }
        
        if (empty($images_data)) {
            throw new Exception('No valid images found for export');
        }
        
        // Generate PDF using Python service
        $post_data = json_encode([
            'images_data' => $images_data,
            'project_id' => $project_id,
            'company_logo' => base_url('assets/images/company-logo.png') // Add your company logo path
        ]);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'http://127.0.0.1:5000/generate-portfolio-pdf',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $post_data,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            ],
            CURLOPT_TIMEOUT => 60
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($http_code === 200) {
            // Return PDF file
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="model-portfolio-' . $project_id . '.pdf"');
            echo $response;
        } else {
            throw new Exception('PDF generation failed: HTTP ' . $http_code);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}

    public function index() {
        $data['page_title'] = 'Projects';
        $data['user'] = $this->User_model->get_user_by_id($this->session->userdata('user_id'));
        $data['projects'] = $this->Project_model->get_all_projects();
        $data['python_service_available'] = $this->pdf_service->is_service_healthy();
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('project/projects_list', $data);
        $this->load->view('templates/footer');
    }

    public function create() {
        $data['page_title'] = 'Create New Project';
        $data['user'] = $this->User_model->get_user_by_id($this->session->userdata('user_id'));
        $data['python_service_available'] = $this->pdf_service->is_service_healthy();
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('project/create_project', $data);
        $this->load->view('templates/footer');
    }

    public function save_project() {
        try {
            $project_name = $this->input->post('project_name');
            $project_description = $this->input->post('project_description');
            
            if (empty($project_name)) {
                throw new Exception('Project name is required');
            }
            
            // Create project via Python service
            $result = $this->pdf_service->create_project($project_name, $project_description);
            
            if (!$result['success']) {
                throw new Exception($result['error']);
            }
            
            $this->session->set_flashdata('success', 'Project created successfully!');
            redirect('project/upload/' . $result['project_id']);
            
        } catch (Exception $e) {
            $this->session->set_flashdata('error', $e->getMessage());
            redirect('project/create');
        }
    }

    public function upload($project_id) {
        $data['page_title'] = 'Upload PDFs';
        $data['user'] = $this->User_model->get_user_by_id($this->session->userdata('user_id'));
        $data['project'] = $this->Project_model->get_project($project_id);
        $data['python_service_available'] = $this->pdf_service->is_service_healthy();
        
        if (!$data['project']) {
            show_404();
        }
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('project/upload_pdfs', $data);
        $this->load->view('templates/footer');
    }

    public function process_upload($project_id) {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        
        try {
            if (!$this->pdf_service->is_service_healthy()) {
                throw new Exception('PDF processing service is unavailable.');
            }
            
            if (!isset($_FILES['pdf_files']) || empty($_FILES['pdf_files']['name'])) {
                throw new Exception('No PDF files selected.');
            }
            
            $upload_path = './uploads/temp/' . $project_id . '/';
            if (!is_dir($upload_path)) {
                mkdir($upload_path, 0755, true);
            }
            
            $file_paths = [];
            $files = $_FILES['pdf_files'];
            
            // Log upload details for debugging
            error_log("Upload Debug - Files count: " . count($files['name']));
            
            if (is_array($files['name'])) {
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK && !empty($files['name'][$i])) {
                        $file_extension = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
                        if ($file_extension !== 'pdf') {
                            error_log("Skipping non-PDF file: " . $files['name'][$i]);
                            continue;
                        }
                        
                        $temp_path = $files['tmp_name'][$i];
                        $file_name = uniqid() . '_' . $files['name'][$i];
                        $destination = $upload_path . $file_name;
                        
                        if (move_uploaded_file($temp_path, $destination)) {
                            $file_paths[] = $destination;
                            error_log("Successfully uploaded: " . $files['name'][$i]);
                        } else {
                            error_log("Failed to upload: " . $files['name'][$i]);
                        }
                    } else {
                        error_log("Upload error for: " . $files['name'][$i] . " - Error code: " . $files['error'][$i]);
                    }
                }
            }
            
            if (empty($file_paths)) {
                throw new Exception('No valid PDF files could be uploaded.');
            }
            
            error_log("Starting PDF processing for " . count($file_paths) . " files");
            
            // Process via Python service
            $batch_result = $this->pdf_service->process_project_pdfs($file_paths, $project_id);
            
            // Cleanup temp files
            foreach ($file_paths as $file_path) {
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
            }
            
            $this->session->set_flashdata('batch_processing_result', $batch_result);
            $this->session->set_flashdata('success', 'PDFs processed successfully! Processed ' . $batch_result['success'] . ' files.');
            
        } catch (Exception $e) {
            error_log("PDF Processing Error: " . $e->getMessage());
            $this->session->set_flashdata('error', $e->getMessage());
        }
        
        redirect('project/view/' . $project_id);
    }

    public function view($project_id) {
        $data['page_title'] = 'Project View';
        $data['user'] = $this->User_model->get_user_by_id($this->session->userdata('user_id'));
        $data['project'] = $this->Project_model->get_project($project_id);
        
        // Try to get data from Python service first, fallback to database
        $service_data = $this->pdf_service->get_project_data($project_id);
        
        if ($service_data['success']) {
            $data['project_data'] = [
                'pdfs' => $service_data['pdfs'],
                'additional_photos' => $service_data['additional_photos']
            ];
        } else {
            // Fallback to database
            $data['project_data'] = $this->Project_model->get_project_data($project_id);
        }
        
        $data['python_service_available'] = $this->pdf_service->is_service_healthy();
        
        if (!$data['project']) {
            show_404();
        }
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('project/project_view', $data);
        $this->load->view('templates/footer');
    }
public function delete_project($project_id) {
    try {
        // Check if user is logged in
        if (!$this->session->userdata('logged_in')) {
            echo json_encode(['success' => false, 'message' => 'Not authenticated']);
            return;
        }

        // Start transaction
        $this->db->trans_start();

        // Get project info
        $project = $this->db->get_where('projects', ['id' => $project_id])->row();
        if (!$project) {
            throw new Exception('Project not found');
        }

        // 1. Delete additional photos records and files
        $additional_photos = $this->db->get_where('additional_photos', ['project_id' => $project_id])->result();
        foreach ($additional_photos as $photo) {
            if (file_exists($photo->image_path)) {
                unlink($photo->image_path);
            }
        }
        $this->db->delete('additional_photos', ['project_id' => $project_id]);

        // 2. Delete extracted images records and files
        $extracted_images = $this->db->get_where('extracted_images', ['project_id' => $project_id])->result();
        foreach ($extracted_images as $image) {
            if (file_exists($image->image_path)) {
                unlink($image->image_path);
            }
        }
        $this->db->delete('extracted_images', ['project_id' => $project_id]);

        // 3. Delete extracted data
        $this->db->delete('extracted_data', ['project_id' => $project_id]);

        // 4. Delete project PDFs records and files
        $project_pdfs = $this->db->get_where('project_pdfs', ['project_id' => $project_id])->result();
        foreach ($project_pdfs as $pdf) {
            if (file_exists($pdf->file_path)) {
                unlink($pdf->file_path);
            }
        }
        $this->db->delete('project_pdfs', ['project_id' => $project_id]);

        // 5. Delete extracted models
        $this->db->delete('extracted_models', ['project_id' => $project_id]);

        // 6. Delete project record
        $this->db->delete('projects', ['id' => $project_id]);

        // 7. Delete project folder
        $project_folder = "./projects/{$project_id}";
        if (is_dir($project_folder)) {
            $this->delete_directory($project_folder);
        }

        // Commit transaction
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            throw new Exception('Database transaction failed');
        }

        echo json_encode(['success' => true, 'message' => 'Project deleted successfully']);

    } catch (Exception $e) {
        $this->db->trans_rollback();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

// Helper function to delete directory recursively
private function delete_directory($dir) {
    if (!is_dir($dir)) {
        return true;
    }
    
    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        if (is_dir($path)) {
            $this->delete_directory($path);
        } else {
            unlink($path);
        }
    }
    
    return rmdir($dir);
}
    public function update_model_info($pdf_id) {
        try {
            $json_data = file_get_contents('php://input');
            $data = json_decode($json_data, true);
            
            if (!$data) {
                throw new Exception('No data received');
            }
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => 'http://127.0.0.1:5000/update-model-info/' . $pdf_id,
                CURLOPT_CUSTOMREQUEST => 'PUT',
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
                CURLOPT_TIMEOUT => 30
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($http_code === 200) {
                $result = json_decode($response, true);
                if ($result['success']) {
                    echo json_encode(['success' => true, 'message' => 'Model information updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => $result['error']]);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to update model information. HTTP ' . $http_code . ': ' . $error]);
            }
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    public function upload_additional_photo($project_id) {
        try {
            if (!isset($_FILES['additional_photo']) || $_FILES['additional_photo']['error'] !== UPLOAD_ERR_OK) {
                throw new Exception('No photo file received.');
            }
            
            $photo = $_FILES['additional_photo'];
            $temp_path = $photo['tmp_name'];
            
            $post_data = [
                'photo' => new CURLFile($temp_path, $photo['type'], $photo['name'])
            ];
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => 'http://127.0.0.1:5000/upload-additional-photo/' . $project_id,
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => $post_data,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code === 200) {
                $result = json_decode($response, true);
                if ($result['success']) {
                    echo json_encode(['success' => true, 'message' => 'Additional photo uploaded successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => $result['error']]);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to upload photo']);
            }
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    public function upload_model_image($pdf_id) {
        try {
            if (!isset($_FILES['model_image']) || $_FILES['model_image']['error'] !== UPLOAD_ERR_OK) {
                throw new Exception('No image file received.');
            }
            
            $image = $_FILES['model_image'];
            $temp_path = $image['tmp_name'];
            
            $post_data = [
                'model_image' => new CURLFile($temp_path, $image['type'], $image['name'])
            ];
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => 'http://127.0.0.1:5000/upload-model-image/' . $pdf_id,
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => $post_data,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code === 200) {
                $result = json_decode($response, true);
                if ($result['success']) {
                    echo json_encode(['success' => true, 'message' => 'Model image uploaded successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => $result['error']]);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to upload image']);
            }
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    public function delete_image($image_id) {
        try {
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => 'http://127.0.0.1:5000/delete-image/' . $image_id,
                CURLOPT_CUSTOMREQUEST => 'DELETE',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code === 200) {
                $result = json_decode($response, true);
                if ($result['success']) {
                    echo json_encode(['success' => true, 'message' => 'Image deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => $result['error']]);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to delete image']);
            }
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    public function delete_additional_photo($photo_id) {
        try {
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => 'http://127.0.0.1:5000/delete-additional-photo/' . $photo_id,
                CURLOPT_CUSTOMREQUEST => 'DELETE',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code === 200) {
                $result = json_decode($response, true);
                if ($result['success']) {
                    echo json_encode(['success' => true, 'message' => 'Photo deleted successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => $result['error']]);
                }
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to delete photo']);
            }
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    public function get_project_status($project_id) {
        try {
            $result = $this->Pdf_service->get_project_status($project_id);
            echo json_encode($result);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }
    public function generate_pdf_from_preview() {
    try {
        set_time_limit(300);
        ini_set('memory_limit', '1G');
        
        error_log("=== PDF GENERATION STARTED ===");
        
        // Get input
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        if (!$data || !isset($data['image_ids'])) {
            throw new Exception('Invalid request data');
        }
        
        $image_ids = $data['image_ids'];
        $project_id = $data['project_id'] ?? 'portfolio_' . time();
        
        error_log("Processing project: $project_id with " . count($image_ids) . " images");
        
        // Limit to 6 images for testing
        $image_ids = array_slice($image_ids, 0, 6);
        
        // Get images data
        $this->load->database();
        $images = [];
        foreach ($image_ids as $image_id) {
            $query = $this->db->get_where('extracted_images', ['id' => $image_id]);
            $image = $query->row_array();
            
            if ($image && file_exists(FCPATH . $image['image_path'])) {
                // Get model info
                $model_query = $this->db->get_where('extracted_data', ['pdf_id' => $image['pdf_id']]);
                $model_info = $model_query->row_array();
                
                $pdf_query = $this->db->get_where('project_pdfs', ['id' => $image['pdf_id']]);
                $pdf_info = $pdf_query->row_array();
                
                $images[] = [
                    'id' => $image['id'],
                    'path' => FCPATH . $image['image_path'],
                    'name' => $image['image_name'],
                    'model_info' => $model_info ?: [],
                    'pdf_name' => $pdf_info['original_name'] ?? 'Unknown Model'
                ];
            }
        }
        
        if (empty($images)) {
            throw new Exception('No valid images found');
        }
        
        // Generate SIMPLE HTML
        $html = $this->generate_simple_html($images, $project_id);
        
        // Prepare data for Python
        $post_data = [
            'html_content' => $html,
            'images_data' => array_map(function($img) {
                return [
                    'image_path' => $img['path'],
                    'image_name' => $img['name'],
                    'id' => $img['id']
                ];
            }, $images),
            'project_id' => $project_id
        ];
        
        error_log("Sending to Python server...");
        
        // Send to Python
        $ch = curl_init('http://127.0.0.1:5001/generate-pdf-from-preview');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($post_data),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_TIMEOUT => 60,
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception("Connection error: $error");
        }
        
        if ($http_code != 200) {
            throw new Exception("Python server returned HTTP $http_code");
        }
        
        // Check if it's a PDF
        if (strpos($response, '%PDF-') === 0) {
            // Return PDF
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="portfolio-' . $project_id . '.pdf"');
            header('Content-Length: ' . strlen($response));
            echo $response;
            exit;
        } else {
            throw new Exception("Invalid response from server");
        }
        
    } catch (Exception $e) {
        error_log("❌ Error: " . $e->getMessage());
        
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
}

private function generate_simple_html($images, $project_id) {
    // Group by model
    $models = [];
    foreach ($images as $image) {
        $pdf_id = $image['model_info']['pdf_id'] ?? 0;
        if (!isset($models[$pdf_id])) {
            $models[$pdf_id] = [
                'info' => $image['model_info'],
                'pdf_name' => $image['pdf_name'],
                'images' => []
            ];
        }
        $models[$pdf_id]['images'][] = $image;
    }
    
    $html = '';
    $page_num = 1;
    
    foreach ($models as $model_data) {
        $model_info = $model_data['info'];
        $model_images = $model_data['images'];
        
        // Get model name
        $model_name = !empty($model_info['model_name']) 
            ? strtoupper($model_info['model_name'])
            : strtoupper(preg_replace('/[0-9\-_\.pdf]/i', ' ', $model_data['pdf_name']));
        
        // Split images into groups of 3
        $image_groups = array_chunk($model_images, 3);
        
        foreach ($image_groups as $group) {
            $html .= '<div class="page">';
            $html .= '<div class="header">';
            $html .= '<h1 class="model-name">' . htmlspecialchars($model_name) . '</h1>';
            $html .= '<div class="stats">';
            
            // Add measurements
            if (!empty($model_info['model_height'])) {
                $html .= '<div>HEIGHT: ' . htmlspecialchars($model_info['model_height']) . '</div>';
            }
            if (!empty($model_info['model_shoe_size'])) {
                $html .= '<div>SHOE SIZE: ' . htmlspecialchars($model_info['model_shoe_size']) . '</div>';
            }
            
            $html .= '</div></div>';
            
            // Photo grid
            $html .= '<div class="photo-grid">';
            
            foreach ($group as $image) {
                $html .= '<div class="photo-container">';
                $html .= '<img src="' . htmlspecialchars($image['path']) . '" ';
                $html .= 'alt="' . htmlspecialchars($image['name']) . '" ';
                $html .= 'data-image-id="' . $image['id'] . '">';
                $html .= '</div>';
            }
            
            // Fill empty slots
            for ($i = count($group); $i < 3; $i++) {
                $html .= '<div class="photo-container" style="background: #f5f5f5;"></div>';
            }
            
            $html .= '</div>';
            
            // Footer
            $html .= '<div class="footer">';
            $html .= '<div>INSTAGRAM | PORTFOLIO</div>';
            $html .= '<div>Page ' . $page_num . '</div>';
            $html .= '</div>';
            
            $html .= '</div>';
            $page_num++;
        }
    }
    
    return $html;
}
}