<?php
/* require_once 'config.php'; */
$_SESSION['KEY'] = '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';


// Get the API key from environment variable
$api_key = $_SESSION['KEY'];
session_start();

/* if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
} */

// Handle audio submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['audio'])) {
    try {
        $tempFile = $_FILES['audio']['tmp_name'];
        
        // First, transcribe the audio using Whisper API
        $curl = curl_init();
        $postFields = [
            'file' => new CURLFile($tempFile, 'audio/wav', 'audio.wav'),
            'model' => 'whisper-1'
        ];
        
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://api.openai.com/v1/audio/transcriptions',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $api_key
            ]
        ]);
        
        $transcriptionResponse = curl_exec($curl);
        $transcriptionHttpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        if ($transcriptionHttpCode !== 200) {
            throw new Exception('Transcription failed: ' . $transcriptionResponse);
        }
        
        $transcriptionData = json_decode($transcriptionResponse, true);
        $transcription = $transcriptionData['text'];
        
        // Then, send transcribed text to ChatGPT
        $curl = curl_init();
        $postData = [
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                ['role' => 'user', 'content' => $transcription]
            ]
        ];
        
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://api.openai.com/v1/chat/completions',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($postData),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $_ENV['OPENAI_API_KEY'],
                'Content-Type: application/json'
            ]
        ]);
        
        $completionResponse = curl_exec($curl);
        $completionHttpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        if ($completionHttpCode !== 200) {
            throw new Exception('Chat completion failed: ' . $completionResponse);
        }
        
        $completionData = json_decode($completionResponse, true);
        $aiResponse = $completionData['choices'][0]['message']['content'];
        
        // Return JSON response
        echo json_encode([
            'success' => true,
            'transcription' => $transcription,
            'response' => $aiResponse
        ]);
        exit();
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Voice Dictation - SPARK</title>
    <link rel="stylesheet" href="css/styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        .summary-section {
            max-width: 800px;
            margin: 2rem auto;
            padding: 0 2rem;
        }

        .input-group {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .input-field {
            flex-grow: 1;
            padding: 0.75rem 1rem;
            border: 1px solid var(--text-secondary);
            border-radius: 0.5rem;
            background-color: var(--background-color);
            color: var(--text-primary);
            font-family: 'Poppins', sans-serif;
        }

        .button {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 0.5rem;
            background-color: var(--accent-color);
            color: white;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .button:hover {
            background-color: var(--primary-color);
            transform: translateY(-1px);
        }

        .loading-section {
            display: none;
            text-align: center;
            padding: 2rem;
            background-color: var(--surface-color);
            border-radius: 1rem;
            margin-bottom: 2rem;
        }

        .response-section {
            background-color: var(--surface-color);
            border-radius: 1rem;
            padding: 2rem;
            margin-bottom: 2rem;
            display: none;
        }

        .response-content {
            white-space: pre-wrap;
            color: var(--text-primary);
            line-height: 1.6;
            margin-bottom: 1rem;
        }

        .action-buttons {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
        }

        .home-button {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: var(--accent-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .home-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="content-wrapper">
            <h1><i class="fas fa-microphone"></i> Voice Dictation</h1>
            
            <div class="control-panel">
                <button id="startRecord" class="action-button">
                    <i class="fas fa-microphone"></i> Start Recording
                </button>
                <button id="stopRecord" class="action-button" disabled>
                    <i class="fas fa-stop"></i> Stop Recording
                </button>
                <button id="backButton" class="secondary-button" onclick="window.location.href='index.php'">
                    <i class="fas fa-arrow-left"></i> Back
                </button>
            </div>

            <div class="result-container">
                <div class="transcription-box">
                    <h3>Your Speech</h3>
                    <div id="transcriptionText" class="text-content"></div>
                </div>
                
                <div class="response-box">
                    <h3>AI Response</h3>
                    <div id="responseText" class="text-content"></div>
                </div>
            </div>

            <div id="status" class="status-message"></div>
        </div>
    </div>

    <script>
        let mediaRecorder;
        let audioChunks = [];

        document.getElementById('startRecord').addEventListener('click', async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];

                mediaRecorder.ondataavailable = (event) => {
                    audioChunks.push(event.data);
                };

                mediaRecorder.onstop = async () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    await sendAudioToServer(audioBlob);
                };

                mediaRecorder.start();
                document.getElementById('startRecord').disabled = true;
                document.getElementById('stopRecord').disabled = false;
                document.getElementById('status').textContent = 'Recording...';
            } catch (err) {
                console.error('Error accessing microphone:', err);
                document.getElementById('status').textContent = 'Error accessing microphone';
            }
        });

        document.getElementById('stopRecord').addEventListener('click', () => {
            mediaRecorder.stop();
            document.getElementById('startRecord').disabled = false;
            document.getElementById('stopRecord').disabled = true;
            document.getElementById('status').textContent = 'Processing...';
        });

        async function sendAudioToServer(audioBlob) {
            const formData = new FormData();
            formData.append('audio', audioBlob);

            try {
                const response = await fetch('dictate.php', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('transcriptionText').textContent = data.transcription;
                    document.getElementById('responseText').textContent = data.response;
                    document.getElementById('status').textContent = 'Complete!';
                } else {
                    document.getElementById('status').textContent = 'Error: ' + data.error;
                }
            } catch (err) {
                console.error('Error sending audio:', err);
                document.getElementById('status').textContent = 'Error sending audio to server';
            }
        }
    </script>
</body>
</html>
