<?php
$datetime = date("Y-m-d H:i:s");
$txt  = "\n$datetime - ".$_SERVER['PHP_SELF']."\n";
$txt .= print_r($user, true);
$txt .= print_r($_POST, true);
$txt .= print_r($_FILES, true);

if ( !$user['superAdmin'] ) {
    $txt .= "403 not superAdmin\n";
    $txt .= "done\n\n\n\n";
    $file = fopen(PATH_LOGS.'/btb.new-groups-from-plan.log', "a");
    fwrite($file, $txt);
    fclose($file);

    http_response_code(403);
    echo json_encode('You do not have permission to create selection sheets');
    exit;
}

// if ( !$project = $db->row("SELECT * FROM project WHERE id = ?", $_POST['projectId']) ) {
//     $txt .= "400 invalid project\n";
//     $txt .= "done\n\n\n\n";
//     $file = fopen(PATH_LOGS.'/btb.new-selection-sheet.log', "a");
//     fwrite($file, $txt);
//     fclose($file);
    
//     http_response_code(400);
//     echo json_encode('Invalid project ID');
//     exit;
// } else {
//     $txt .= print_r($project, true);
// }

if ( !empty($_FILES) ) {
    $txt .= "looping over _FILES\n";

    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

    $txt .= "ext: $ext\n";

    if ( $ext != 'PDF' && $ext != 'pdf' ) {

        $txt .= "not pdf\n";
        $txt .= "done\n\n\n\n";
        $file = fopen(PATH_LOGS.'/btb.new-selection-sheet.log', "a");
        fwrite($file, $txt);
        fclose($file);

        http_response_code(400);
        echo json_encode('Only PDF accepted');
        exit;

    } else {
        $filename = strtotime($datetime).'-ai-analyze-pdf-'.$_FILES['file']['name'];

        $txt .= "new filename: $filename\n";

        if ( move_uploaded_file($_FILES['file']['tmp_name'], PATH_AI_ATTACHMENTS.'/'.$filename) ) {

            $txt .= "file moved\n";

        } else {

            $txt .= "file move failed\n";
            $txt .= "done\n\n\n\n";
            $file = fopen(PATH_LOGS.'/btb.new-selection-sheet.log', "a");
            fwrite($file, $txt);
            fclose($file);

            http_response_code(409);
            echo 'There was a problem uploading your file.';
            exit;
        }
    }
} else {

    $txt .= "_FILES array was empty\n";
    $txt .= "done\n\n\n\n";
    $file = fopen(PATH_LOGS.'/btb.new-selection-sheet.log', "a");
    fwrite($file, $txt);
    fclose($file);

    http_response_code(400);
    echo json_encode('No PDF was uploaded');
    exit;
}

$payload = [
    'max_tokens' => 4096,
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'text',
                    // 'text' => 'Analyze the attached floor plans and provide a JSON-formatted list of all of the rooms in the house separated by level. Do not provide any text other than the JSON-formatted output requested. Levels should always be from the following list: "Main Level", "Upper Level", "Lower Level". Do not use a "room" key. In other words, the structure of the JSON object should be {Level:{Room}}. The list of rooms should not be a key-value pair. Ensure output is always valid JSON. The list of rooms should be alphabetized. Whenever a closet is present in the list, also include the room the closet belongs to. For example: "Closet (Bedroom #2)"'
                    'text' => 'Create a JSON output of rooms by level from the provided floor plans, following these specifications:
                        1. Format Specifications:
                        - Use only these level names: "Main Level", "Upper Level", "Lower Level"
                        - Structure: {Level: [array of room names]}
                        - Room names should be in alphabetical order
                        - For closets, specify the parent room in parentheses: "Closet (Master Bedroom)"

                        2. Example Format:
                        {
                        "Main Level": [
                            "Bathroom",
                            "Closet (Master Bedroom)",
                            "Kitchen",
                            "Master Bedroom"
                        ]
                        }

                        3. Requirements:
                        - Output must be valid JSON only
                        - No additional text or explanations
                        - No room property keys, use arrays instead
                        - Include all visible rooms from the plans

                        Please analyze the floor plans and provide the JSON output following these specifications."

                        This optimized prompt:
                        1. Provides a clear example
                        2. Uses bullet points for clarity
                        3. Groups requirements logically
                        4. Specifies exact formatting expectations
                        5. Reduces ambiguity in the instructions
                    '
                ],
                [
                    'type' => 'document',
                    'source' => [
                        'type' => 'base64',
                        'media_type' => mime_content_type(PATH_AI_ATTACHMENTS.'/'.$filename),
                        'data' => base64_encode(file_get_contents(PATH_AI_ATTACHMENTS.'/'.$filename))
                    ]
                ]
            ]
        ]
    ],
    'model' => 'claude-3-5-sonnet-20241022',
    'system' => 'Your job is to help automate a time-consuming part of custom home building. You analyze floors plans and provide exactly what is requested in a format that can be used programmatically'
];

$txt .= "payload set:\n";
// $txt .= print_r($payload, true);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.anthropic.com/v1/messages");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'x-api-key: '.CLAUDE_API_TOKEN, 'Anthropic-Version: 2023-06-01', 'anthropic-beta: pdfs-2024-09-25,prompt-caching-2024-07-31']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

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

$txt .= "curl sent\n";
$txt .= print_r($response, true);

if ( $responseCode !== 200 ) {

    $txt .= "non-200 response from api\n";
    $txt .= "done\n\n\n\n";
    $file = fopen(PATH_LOGS.'/btb.new-selection-sheet.log', "a");
    fwrite($file, $txt);
    fclose($file);

    http_response_code(400);
    echo json_encode("There was an error: ".print_r($response, true));
    exit;
}

$txt .= "done\n\n\n\n";
$file = fopen(PATH_LOGS.'/btb.new-selection-sheet.log', "a");
fwrite($file, $txt);
fclose($file);

$text = $response->content[0]->text;
$array = json_decode($text, true);

// $array = [
//     'Main Level' => [
//         'Master Bedroom',
//         'Master Bathroom',
//         'Great Room',
//         'Living Room',
//         'Kitchen',
//         'Dining Room',
//         'Study',
//         'Half Bathroom',
//         'Closet'
//     ],
//     'Upper Level' => [
//         'Bedroom #2',
//         'Bathroom #2',
//         'Bedroom #3',
//         'Bathroom #3',
//         'Closet',
//         'Closet',
//         'Loft'
//     ],
//     'Lower Level' => [
//         'Den',
//         'Playroom',
//         'Theater',
//         'Exercise Room',
//         'HVAC',
//         'Storage',
//         'Safe Room'
//     ]
// ];

$selectionCategories = $db->run("SELECT * FROM selection_tag WHERE type = 'category'");
  
include '../template/new-groups-from-plan.php';
