<?php

require_once 'config/database.php';

class ConversationNotesController {
    private $conn;

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    /**
     * Create or update conversation note
     */
    public function saveNote($data) {
        try {
            if (!isset($data['call_id'], $data['follow_up_id'], $data['note_text'])) {
                return json_encode([
                    'status' => 'error', 
                    'message' => 'Missing required fields: call_id, follow_up_id, note_text'
                ]);
            }

            $this->conn->beginTransaction();

            // Check if note already exists for this call
            $checkQuery = "SELECT id FROM conversation_notes WHERE call_id = :call_id LIMIT 1";
            $checkStmt = $this->conn->prepare($checkQuery);
            $checkStmt->bindParam(':call_id', $data['call_id']);
            $checkStmt->execute();
            $existingNote = $checkStmt->fetch(PDO::FETCH_ASSOC);

            if ($existingNote) {
                // Update existing note
                $updateQuery = "UPDATE conversation_notes 
                               SET note_text = :note_text,
                                   is_taxpayer_generator = :is_taxpayer_generator,
                                   reason_not_paying_id = :reason_not_paying_id,
                                   need_support = :need_support
                               WHERE id = :id";
                
                $updateStmt = $this->conn->prepare($updateQuery);
                $updateStmt->bindParam(':note_text', $data['note_text']);
                $updateStmt->bindParam(':is_taxpayer_generator', $data['is_taxpayer_generator']);
                $updateStmt->bindParam(':reason_not_paying_id', $data['reason_not_paying_id']);
                $updateStmt->bindParam(':need_support', $data['need_support']);
                $updateStmt->bindParam(':id', $existingNote['id']);
                
                if (!$updateStmt->execute()) {
                    $this->conn->rollBack();
                    return json_encode([
                        'status' => 'error',
                        'message' => 'Failed to update conversation note'
                    ]);
                }

                $this->conn->commit();
                return json_encode([
                    'status' => 'success',
                    'message' => 'Conversation note updated',
                    'note_id' => $existingNote['id']
                ]);
            } else {
                // Create new note
                $insertQuery = "INSERT INTO conversation_notes 
                               (call_id, follow_up_id, is_taxpayer_generator, reason_not_paying_id, 
                                need_support, note_text) 
                               VALUES 
                               (:call_id, :follow_up_id, :is_taxpayer_generator, :reason_not_paying_id,
                                :need_support, :note_text)";
                
                $insertStmt = $this->conn->prepare($insertQuery);
                $insertStmt->bindParam(':call_id', $data['call_id']);
                $insertStmt->bindParam(':follow_up_id', $data['follow_up_id']);
                $insertStmt->bindParam(':is_taxpayer_generator', $data['is_taxpayer_generator']);
                $insertStmt->bindParam(':reason_not_paying_id', $data['reason_not_paying_id']);
                $insertStmt->bindParam(':need_support', $data['need_support']);
                $insertStmt->bindParam(':note_text', $data['note_text']);
                
                if (!$insertStmt->execute()) {
                    $this->conn->rollBack();
                    return json_encode([
                        'status' => 'error',
                        'message' => 'Failed to create conversation note'
                    ]);
                }

                $noteId = $this->conn->lastInsertId();

                $this->conn->commit();
                return json_encode([
                    'status' => 'success',
                    'message' => 'Conversation note created',
                    'note_id' => $noteId
                ]);
            }
        } catch (Exception $e) {
            $this->conn->rollBack();
            return json_encode([
                'status' => 'error',
                'message' => 'Exception: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Get conversation notes for a call
     */
    public function getNotesByCall($callId) {
        try {
            $query = "SELECT cn.*, 
                            c.call_sid, c.status as call_status,
                            fu.invoice_id, fu.ipo_id
                     FROM conversation_notes cn
                     LEFT JOIN calls c ON cn.call_id = c.id
                     LEFT JOIN follow_ups fu ON cn.follow_up_id = fu.id
                     WHERE cn.call_id = :call_id
                     ORDER BY cn.created_at DESC";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':call_id', $callId);
            $stmt->execute();
            
            $notes = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            return json_encode([
                'status' => 'success',
                'data' => $notes
            ]);
        } catch (Exception $e) {
            return json_encode([
                'status' => 'error',
                'message' => 'Exception: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Get conversation notes for a follow-up
     */
    public function getNotesByFollowUp($followUpId) {
        try {
            $query = "SELECT cn.*, 
                            c.call_sid, c.status as call_status, c.duration,
                            c.start_time, c.recording_file
                     FROM conversation_notes cn
                     LEFT JOIN calls c ON cn.call_id = c.id
                     WHERE cn.follow_up_id = :follow_up_id
                     ORDER BY cn.created_at DESC";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':follow_up_id', $followUpId);
            $stmt->execute();
            
            $notes = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            return json_encode([
                'status' => 'success',
                'data' => $notes
            ]);
        } catch (Exception $e) {
            return json_encode([
                'status' => 'error',
                'message' => 'Exception: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Get conversation notes for an invoice
     */
    public function getNotesByInvoice($invoiceId) {
        try {
            $query = "SELECT cn.*, 
                            c.call_sid, c.status as call_status, c.duration,
                            c.start_time, c.recording_file,
                            fu.ipo_id, fu.attempts, fu.status as followup_status
                     FROM conversation_notes cn
                     LEFT JOIN calls c ON cn.call_id = c.id
                     LEFT JOIN follow_ups fu ON cn.follow_up_id = fu.id
                     WHERE fu.invoice_id = :invoice_id
                     ORDER BY cn.created_at DESC";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':invoice_id', $invoiceId);
            $stmt->execute();
            
            $notes = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            return json_encode([
                'status' => 'success',
                'data' => $notes
            ]);
        } catch (Exception $e) {
            return json_encode([
                'status' => 'error',
                'message' => 'Exception: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Delete conversation note
     */
    public function deleteNote($noteId) {
        try {
            $this->conn->beginTransaction();

            $query = "DELETE FROM conversation_notes WHERE id = :id";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':id', $noteId);
            
            if ($stmt->execute()) {
                $this->conn->commit();
                return json_encode([
                    'status' => 'success',
                    'message' => 'Conversation note deleted'
                ]);
            } else {
                $this->conn->rollBack();
                return json_encode([
                    'status' => 'error',
                    'message' => 'Failed to delete conversation note'
                ]);
            }
        } catch (Exception $e) {
            $this->conn->rollBack();
            return json_encode([
                'status' => 'error',
                'message' => 'Exception: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Get conversation note statistics for reporting
     */
    public function getNoteStats($filters = []) {
        try {
            $whereConditions = [];
            $params = [];

            if (isset($filters['ipo_id'])) {
                $whereConditions[] = "fu.ipo_id = :ipo_id";
                $params[':ipo_id'] = $filters['ipo_id'];
            }

            if (isset($filters['date_from'])) {
                $whereConditions[] = "cn.created_at >= :date_from";
                $params[':date_from'] = $filters['date_from'];
            }

            if (isset($filters['date_to'])) {
                $whereConditions[] = "cn.created_at <= :date_to";
                $params[':date_to'] = $filters['date_to'];
            }

            $whereClause = !empty($whereConditions) 
                ? "WHERE " . implode(" AND ", $whereConditions) 
                : "";

            $query = "SELECT 
                        COUNT(*) as total_notes,
                        COUNT(DISTINCT cn.call_id) as total_calls_with_notes,
                        COUNT(DISTINCT cn.follow_up_id) as total_followups_with_notes,
                        SUM(CASE WHEN cn.is_taxpayer_generator = 1 THEN 1 ELSE 0 END) as taxpayer_confirmed,
                        SUM(CASE WHEN cn.is_taxpayer_generator = 0 THEN 1 ELSE 0 END) as taxpayer_not_confirmed,
                        SUM(CASE WHEN cn.need_support = 1 THEN 1 ELSE 0 END) as needs_support_count,
                        COUNT(DISTINCT cn.reason_not_paying_id) as unique_reasons
                     FROM conversation_notes cn
                     LEFT JOIN follow_ups fu ON cn.follow_up_id = fu.id
                     $whereClause";
            
            $stmt = $this->conn->prepare($query);
            
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            
            $stmt->execute();
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            return json_encode([
                'status' => 'success',
                'data' => $stats
            ]);
        } catch (Exception $e) {
            return json_encode([
                'status' => 'error',
                'message' => 'Exception: ' . $e->getMessage()
            ]);
        }
    }
}

?>