<?php
class ClaudePDFAnalyzer {
    private $apiKey;
    private $apiEndpoint = 'https://api.anthropic.com/v1/messages';

    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }

    public function uploadAndAnalyzePDF($filePath) {
        // Validate PDF file
        if (!file_exists($filePath) || mime_content_type($filePath) !== 'application/pdf') {
            throw new Exception('Invalid PDF file');
        }

        // Convert PDF to base64
        $pdfContent = base64_encode(file_get_contents($filePath));

        // Prepare API request payload
        $payload = [
            'model' => 'claude-3-5-sonnet-20241022', // Adjust model as needed
            'system' => 'You are an expert in residential home design and construction with a strong desire to help clients select all of the items and materials needed to complete construction of their home. Your focus is on accuracy, thoroughness, and attention to detail.',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'document',
                            'source' => [
                                'type' => 'base64',
                                'media_type' => 'application/pdf',
                                'data' => $pdfContent
                            ],
                            // 'cache_control' => [
                            //     'type' => 'ephemeral'
                            // ]
                        ],
                        [
                            'type' => 'text',
                            'text' => '
                                Analyze these residential construction floor plans. 

                                Provide a list of all selections, interior and exterior, that must be made by a client in order to complete construction of the home. 

                                The output should be structured like an array where each array element is a single selection, and each selection is itself an array with the following keys: selection, category, room, level, and type. 
                                
                                The selection key is the title of the selection (e.g. \"Counter Tops\"). 

                                The category key is a single category from this list: Accents, Appliances, Base, Built-ins, Cabinet, Cabinet Hardware, Cabinets, Ceiling Coverings, Closets, Counter Tops, Crown, Entry Doors & Hardware, Faucets, Fascia, Fireplace, Flooring, Interior Doors & Hardware, Interior Doors Finish, Interior Lighting, Lighting, Mantle, Mirrors, Other, Paint / Texture, Porch Ceilings, Porch Floors, Porch Railings, Railing, Roof, Shower, Siding, Soffits, Specialty, Stairs, Stone, Timber, Tub, Toilet, Trim, Vanities & Tops, Wall Coverings, Windows & Doors, Window Interior Finish, Window Trim. 

                                The room key is the room that the selection is located in on the floor plan and should exactly match the name of the room as shown on the floor plan. This value should always be a single room. It should never be more than one room.

                                The level key describes the floor on which the selection is located and should come from this list: Main Level, Upper Level, Lower Level, Garage, Garage Apartment, Tower.

                                The type key describes whether the selection is an Interior selection or an Exterior selection and should always be either \"Interior\" or \"Exterior\".

                                Be as specific and thorough as possible. Include materials and selection items needed to finish interior and exterior stairs and staircases. Include interior and exterior fireplaces as selection items where applicable. Include garage materials, like garage doors, where applicable. Respond with the array output only (in other words, do not preceed the array output with statements like \"Based on the floor plans provided, here is a comprehensive list of selections needed, structured according to your requirements:\"). Attempt to order selections by the room in which they are located. For example, all of the selections for the Kitchen should appear contiguously.
                            '
                        ]
                    ]
                ]
            ],
            'max_tokens' => 4096
        ];

        // Send API request
        $ch = curl_init($this->apiEndpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'x-api-key: ' . $this->apiKey,
            'Anthropic-Version: 2023-06-01',
            // 'anthropic-beta: pdfs-2024-09-25,prompt-caching-2024-07-31'
            'anthropic-beta: pdfs-2024-09-25'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new Exception('API request failed: ' . $response);
        }

        // Process and return finish selections
        $responseData = json_decode($response, true);
        // return $this->parseFinishSelections($responseData['content'][0]['text']);
        return $responseData;
    }

    // private function parseFinishSelections($analysisText) {
    //     // Basic parsing of finish selections
    //     $selections = [
    //         'Interior' => [],
    //         'Exterior' => []
    //     ];

    //     $categories = [
    //         'Interior' => ['flooring', 'paint', 'countertops', 'cabinets', 'tiles', 'lighting'],
    //         'Exterior' => ['siding', 'roofing', 'windows', 'doors', 'trim', 'landscaping']
    //     ];

    //     foreach ($categories as $type => $typeCategories) {
    //         foreach ($typeCategories as $category) {
    //             $selections[$type][$category] = $this->extractSelectionDetails($analysisText, $category);
    //         }
    //     }

    //     return $selections;
    // }

    // private function extractSelectionDetails($text, $category) {
    //     // Simple extraction logic - can be enhanced with more sophisticated parsing
    //     $pattern = "/(?:$category):\s*([^\n]+)/i";
    //     preg_match($pattern, $text, $matches);
    //     return $matches[1] ?? 'Selection needed';
    // }
}

// Usage example
try {
    $apiKey = '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';
    $analyzer = new ClaudePDFAnalyzer($apiKey);
    $finishSelections = $analyzer->uploadAndAnalyzePDF('plans.pdf');
    echo "<pre>";
    print_r($finishSelections);
    echo "</pre>";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}