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

class Portfolio extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
        $this->load->library('session');
    }
    
    /**
     * Public portfolio view for a single model
     * URL: /portfolio/model/PROJECT_ID/MODEL_NAME
     */
    public function model($project_id, $model_name = null) {
        try {
            // Log request for debugging
            log_message('info', "Portfolio request - Project: $project_id, Model: $model_name");
            
            // Decode URL parameter
            if ($model_name) {
                $model_name = urldecode($model_name);
                log_message('info', "Decoded model name: $model_name");
            }
            
            // Get project info
            $project = $this->db->get_where('projects', ['id' => $project_id])->row();
            
            if (!$project) {
                log_message('error', "Project not found: $project_id");
                show_404();
            }
            
            // FIRST: Try to find the exact PDF by model name
            $pdf_data = null;
            $pdf_id = null;
            
            if ($model_name) {
                // Method 1: Check extracted_data table for model name
                $this->db->select('ed.*, pp.*');
                $this->db->from('extracted_data ed');
                $this->db->join('project_pdfs pp', 'pp.id = ed.pdf_id', 'left');
                $this->db->where('pp.project_id', $project_id);
                
                // Try multiple matching strategies
                $this->db->group_start();
                
                // Exact match (case-insensitive)
                $this->db->where('LOWER(TRIM(ed.model_name)) =', strtolower(trim($model_name)));
                
                // Like match
                $this->db->or_like('ed.model_name', $model_name);
                
                // Match with PDF original name (without .pdf)
                $clean_model_name = str_replace(['-', '_', ' ', '.pdf'], '', strtolower($model_name));
                $this->db->or_where("REPLACE(REPLACE(REPLACE(LOWER(pp.original_name), '-', ''), '_', ''), '.pdf', '') =", $clean_model_name);
                
                $this->db->group_end();
                
                $query = $this->db->get();
                $pdf_data = $query->row_array();
                
                if ($pdf_data) {
                    log_message('info', "Found PDF via model name: " . ($pdf_data['model_name'] ?? 'N/A'));
                }
            }
            
            // Method 2: If still not found, try to find by PDF original name
            if (!$pdf_data && $model_name) {
                log_message('info', "Trying to find by PDF filename...");
                
                $this->db->select('pp.*, ed.*');
                $this->db->from('project_pdfs pp');
                $this->db->join('extracted_data ed', 'pp.id = ed.pdf_id', 'left');
                $this->db->where('pp.project_id', $project_id);
                
                // Clean the model name for comparison
                $search_name = strtolower($model_name);
                $search_name = str_replace([' ', '-', '_', '.pdf'], '', $search_name);
                
                $this->db->group_start();
                $this->db->like('LOWER(pp.original_name)', strtolower($model_name));
                $this->db->or_where("REPLACE(REPLACE(REPLACE(LOWER(pp.original_name), '-', ''), '_', ''), '.pdf', '') =", $search_name);
                $this->db->group_end();
                
                $query = $this->db->get();
                $pdf_data = $query->row_array();
                
                if ($pdf_data) {
                    log_message('info', "Found PDF via filename: " . ($pdf_data['original_name'] ?? 'N/A'));
                }
            }
            
            // Method 3: If still not found and model_name not provided, get first PDF
            if (!$pdf_data) {
                log_message('info', "Getting first PDF in project...");
                
                $this->db->select('pp.*, ed.*');
                $this->db->from('project_pdfs pp');
                $this->db->join('extracted_data ed', 'pp.id = ed.pdf_id', 'left');
                $this->db->where('pp.project_id', $project_id);
                $this->db->order_by('pp.id', 'ASC');
                $this->db->limit(1);
                
                $query = $this->db->get();
                $pdf_data = $query->row_array();
                
                if ($pdf_data) {
                    log_message('info', "Using first PDF: " . ($pdf_data['original_name'] ?? 'N/A'));
                }
            }
            
            if (!$pdf_data) {
                log_message('error', "No PDF found for project: $project_id");
                show_404();
            }
            
            // Get PDF ID
            $pdf_id = $pdf_data['id'];
            log_message('info', "Using PDF ID: $pdf_id");
            
            // Get ALL images for this SPECIFIC PDF ONLY
            $this->db->select('*');
            $this->db->from('extracted_images');
            $this->db->where('pdf_id', $pdf_id);
            $this->db->order_by('page_number, id');
            
            $images_query = $this->db->get();
            $images = $images_query->result_array();
            
            log_message('info', "Found " . count($images) . " images for PDF ID: $pdf_id");
            
            if (empty($images)) {
                log_message('warning', "No images found for PDF ID: $pdf_id");
                // Continue anyway to show model details
            }
            
            // Debug: Log what we found
            log_message('info', "PDF Details:");
            log_message('info', "- PDF ID: " . ($pdf_data['id'] ?? 'N/A'));
            log_message('info', "- Original Name: " . ($pdf_data['original_name'] ?? 'N/A'));
            log_message('info', "- Model Name: " . ($pdf_data['model_name'] ?? 'N/A'));
            log_message('info', "- Project ID: " . ($pdf_data['project_id'] ?? 'N/A'));
            
            // Prepare data for view
            $data = [
                'page_title' => ($pdf_data['model_name'] ?? 'Model') . ' - GO Productions Portfolio',
                'project' => $project,
                'model' => $pdf_data,
                'images' => $images,
                'pdf_id' => $pdf_id,
                'is_single_model' => true
            ];
            
            // Load the view
            $this->load->view('portfolio/single_model', $data);
            
        } catch (Exception $e) {
            log_message('error', 'Portfolio error: ' . $e->getMessage());
            log_message('error', $e->getTraceAsString());
            show_error($e->getMessage());
        }
    }
    
    /**
     * Alternative URL format: /portfolio/PROJECT_ID/PDF_ID
     * More accurate since we use the actual PDF ID
     */
    public function view($project_id, $pdf_id = null) {
        try {
            log_message('info', "Portfolio view - Project: $project_id, PDF ID: $pdf_id");
            
            // Get project info
            $project = $this->db->get_where('projects', ['id' => $project_id])->row();
            
            if (!$project) {
                show_404();
            }
            
            // If PDF ID is provided, use it directly
            if ($pdf_id) {
                $this->db->select('pp.*, ed.*');
                $this->db->from('project_pdfs pp');
                $this->db->join('extracted_data ed', 'pp.id = ed.pdf_id', 'left');
                $this->db->where('pp.id', $pdf_id);
                $this->db->where('pp.project_id', $project_id);
            } else {
                // Get first PDF
                $this->db->select('pp.*, ed.*');
                $this->db->from('project_pdfs pp');
                $this->db->join('extracted_data ed', 'pp.id = ed.pdf_id', 'left');
                $this->db->where('pp.project_id', $project_id);
                $this->db->order_by('pp.id', 'ASC');
                $this->db->limit(1);
            }
            
            $query = $this->db->get();
            $pdf_data = $query->row_array();
            
            if (!$pdf_data) {
                show_404();
            }
            
            // Get all images for this specific PDF
            $this->db->order_by('page_number, id');
            $images_query = $this->db->get_where('extracted_images', ['pdf_id' => $pdf_data['id']]);
            $images = $images_query->result_array();
            
            log_message('info', "Found " . count($images) . " images for PDF ID: " . $pdf_data['id']);
            
            $data = [
                'page_title' => ($pdf_data['model_name'] ?? 'Model') . ' - GO Productions Portfolio',
                'project' => $project,
                'model' => $pdf_data,
                'images' => $images,
                'pdf_id' => $pdf_data['id'],
                'is_single_model' => true
            ];
            
            $this->load->view('portfolio/single_model', $data);
            
        } catch (Exception $e) {
            log_message('error', 'Portfolio view error: ' . $e->getMessage());
            show_error($e->getMessage());
        }
    }
    
    /**
     * Debug function to see all models in project
     */
    public function debug($project_id) {
        if (!$this->session->userdata('logged_in')) {
            show_404();
        }
        
        echo "<h2>Debug: Project $project_id</h2>";
        
        // Get all PDFs with their extracted data
        $this->db->select('pp.id as pdf_id, pp.original_name, ed.model_name, 
                          (SELECT COUNT(*) FROM extracted_images WHERE pdf_id = pp.id) as image_count');
        $this->db->from('project_pdfs pp');
        $this->db->join('extracted_data ed', 'pp.id = ed.pdf_id', 'left');
        $this->db->where('pp.project_id', $project_id);
        $this->db->order_by('pp.id');
        
        $pdfs = $this->db->get()->result_array();
        
        echo "<table border='1' cellpadding='10'>";
        echo "<tr><th>PDF ID</th><th>Original Name</th><th>Model Name</th><th>Image Count</th><th>Links</th></tr>";
        
        foreach ($pdfs as $pdf) {
            echo "<tr>";
            echo "<td>{$pdf['pdf_id']}</td>";
            echo "<td>{$pdf['original_name']}</td>";
            echo "<td>{$pdf['model_name']}</td>";
            echo "<td>{$pdf['image_count']}</td>";
            echo "<td>";
            echo "<a href='" . site_url("portfolio/view/$project_id/{$pdf['pdf_id']}") . "' target='_blank'>View by PDF ID</a><br>";
            if ($pdf['model_name']) {
                echo "<a href='" . site_url("portfolio/model/$project_id/" . urlencode($pdf['model_name'])) . "' target='_blank'>View by Model Name</a>";
            }
            echo "</td>";
            echo "</tr>";
        }
        
        echo "</table>";
        
        // Show sample URLs
        echo "<h3>Sample URLs:</h3>";
        foreach ($pdfs as $pdf) {
            if ($pdf['model_name']) {
                echo "By model name: <code>" . site_url("portfolio/model/$project_id/" . urlencode($pdf['model_name'])) . "</code><br>";
            }
            echo "By PDF ID: <code>" . site_url("portfolio/view/$project_id/{$pdf['pdf_id']}") . "</code><br><br>";
        }
    }
}