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

class Pdf_service {
    private $python_service_url;
    private $ci;
    
    public function __construct() {
        $this->ci =& get_instance();
        $this->python_service_url = 'http://127.0.0.1:5000';
    }
    
   public function process_project_pdfs($file_paths, $project_id) {
    if (empty($file_paths)) {
        throw new Exception('No files provided for batch processing');
    }
    
    $post_data = [];
    
    foreach ($file_paths as $index => $file_path) {
        if (file_exists($file_path)) {
            // Send multiple files with array syntax
            $post_data["pdf_files[$index]"] = new CURLFile(
                $file_path, 
                'application/pdf', 
                basename($file_path)
            );
        }
    }
    
    if (empty($post_data)) {
        throw new Exception('No valid files found for processing');
    }
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $this->python_service_url . '/process-project-pdfs/' . $project_id,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $post_data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 300, // 5 minutes timeout for multiple files
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    error_log("PDF Service Debug - Processing " . count($file_paths) . " files");
    error_log("PDF Service Debug - HTTP Code: " . $http_code);
    
    if ($http_code === 0) {
        throw new Exception('Cannot connect to PDF processing service. Error: ' . $error);
    }
    
    if ($http_code !== 200) {
        throw new Exception('Batch processing error: HTTP ' . $http_code . ' - Response: ' . ($response ?: 'No response'));
    }
    
    $result = json_decode($response, true);
    
    if (!$result || !isset($result['success'])) {
        throw new Exception('Invalid batch response: ' . $response);
    }
    
    if (!$result['success']) {
        throw new Exception('Batch processing failed: ' . ($result['error'] ?? 'Unknown error'));
    }
    
    return $result['batch_result'];
}
    
    public function create_project($project_name, $project_description = '') {
        $post_data = json_encode([
            'project_name' => $project_name,
            'project_description' => $project_description
        ]);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->python_service_url . '/create-project',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $post_data,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            ],
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        error_log("Create Project Debug - HTTP Code: " . $http_code);
        error_log("Create Project Debug - Response: " . $response);
        
        if ($http_code === 0) {
            throw new Exception('Cannot connect to PDF processing service. Error: ' . $error);
        }
        
        if ($http_code !== 200) {
            throw new Exception('Project creation error: HTTP ' . $http_code . ' - Response: ' . ($response ?: 'No response'));
        }
        
        $result = json_decode($response, true);
        
        if (!$result || !isset($result['success'])) {
            throw new Exception('Invalid response from service: ' . $response);
        }
        
        if (!$result['success']) {
            throw new Exception('Project creation failed: ' . ($result['error'] ?? 'Unknown error'));
        }
        
        return $result;
    }
    
    public function cleanup_session($session_id) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->python_service_url . '/cleanup/' . $session_id,
            CURLOPT_CUSTOMREQUEST => 'DELETE',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        return $http_code === 200;
    }
    
    public function is_service_healthy() {
        try {
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $this->python_service_url . '/health',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_CONNECTTIMEOUT => 3,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            return $http_code === 200;
        } catch (Exception $e) {
            error_log("Health check error: " . $e->getMessage());
            return false;
        }
    }
    
    public function get_project_status($project_id) {
        try {
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $this->python_service_url . '/project-status/' . $project_id,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code === 200) {
                return json_decode($response, true);
            }
            
            return ['success' => false, 'error' => 'HTTP ' . $http_code];
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    public function get_project_data($project_id) {
        try {
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $this->python_service_url . '/project-data/' . $project_id,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code === 200) {
                return json_decode($response, true);
            }
            
            return ['success' => false, 'error' => 'HTTP ' . $http_code];
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}