<?php
// ========================================
// CallLogsController.php
// ========================================

require_once 'config/database.php';
require_once 'helpers/uuid_helper.php';

class CallLogsController {
    private $conn;

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

    /**
     * Create a new call log
     */
    public function createCallLog($data) {
        try {
            if (!isset($data['invoice_id'], $data['taxpayer_id'], $data['caller_id'], $data['call_type'], $data['call_status'])) {
                return json_encode(['status' => 'error', 'message' => 'Missing required fields']);
            }

            $this->conn->beginTransaction();

            $callId = generateUUID();
            $query = "INSERT INTO call_logs (
                call_id, invoice_id, taxpayer_id, caller_id, call_type, 
                call_status, call_outcome, duration_seconds, notes, 
                scheduled_at, called_at, recording_url
            ) VALUES (
                :call_id, :invoice_id, :taxpayer_id, :caller_id, :call_type,
                :call_status, :call_outcome, :duration_seconds, :notes,
                :scheduled_at, NOW(), :recording_url
            )";

            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':call_id', $callId);
            $stmt->bindParam(':invoice_id', $data['invoice_id']);
            $stmt->bindParam(':taxpayer_id', $data['taxpayer_id']);
            $stmt->bindParam(':caller_id', $data['caller_id']);
            $stmt->bindParam(':call_type', $data['call_type']);
            $stmt->bindParam(':call_status', $data['call_status']);
            
            $callOutcome = $data['call_outcome'] ?? null;
            $durationSeconds = $data['duration_seconds'] ?? null;
            $notes = $data['notes'] ?? null;
            $scheduledAt = $data['scheduled_at'] ?? null;
            $recordingUrl = $data['recording_url'] ?? null;
            
            $stmt->bindParam(':call_outcome', $callOutcome);
            $stmt->bindParam(':duration_seconds', $durationSeconds);
            $stmt->bindParam(':notes', $notes);
            $stmt->bindParam(':scheduled_at', $scheduledAt);
            $stmt->bindParam(':recording_url', $recordingUrl);

            if ($stmt->execute()) {
                $this->conn->commit();
                return json_encode([
                    'status' => 'success',
                    'message' => 'Call log created successfully',
                    'call_id' => $callId
                ]);
            } else {
                $this->conn->rollBack();
                return json_encode(['status' => 'error', 'message' => 'Failed to create call log']);
            }
        } catch (Exception $e) {
            $this->conn->rollBack();
            return json_encode(['status' => 'error', 'message' => 'Exception: ' . $e->getMessage()]);
        }
    }

    /**
     * Get call logs by invoice ID
     */
    public function getCallLogsByInvoice($invoiceId) {
        try {
            $query = "SELECT 
                cl.call_id, cl.call_type, cl.call_status, cl.call_outcome,
                cl.duration_seconds, cl.notes, cl.called_at, cl.recording_url,
                u.full_name AS caller_name,
                t.taxpayer_name, t.phone_number
            FROM call_logs cl
            INNER JOIN users u ON cl.caller_id = u.user_id
            INNER JOIN taxpayer t ON cl.taxpayer_id = t.taxpayer_id
            WHERE cl.invoice_id = :invoice_id
            ORDER BY cl.called_at DESC";

            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':invoice_id', $invoiceId);
            $stmt->execute();

            $calls = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return json_encode([
                'status' => 'success',
                'data' => $calls
            ]);
        } catch (Exception $e) {
            return json_encode(['status' => 'error', 'message' => 'Exception: ' . $e->getMessage()]);
        }
    }

    /**
     * Get call logs by caller (IPO)
     */
    public function getCallLogsByCaller($callerId, $limit = 50) {
        try {
            $query = "SELECT 
                cl.call_id, cl.call_type, cl.call_status, cl.call_outcome,
                cl.duration_seconds, cl.called_at,
                i.invoice_number,
                t.taxpayer_name, t.phone_number
            FROM call_logs cl
            INNER JOIN invoices i ON cl.invoice_id = i.invoice_id
            INNER JOIN taxpayer t ON cl.taxpayer_id = t.taxpayer_id
            WHERE cl.caller_id = :caller_id
            ORDER BY cl.called_at DESC
            LIMIT :limit";

            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':caller_id', $callerId);
            $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
            $stmt->execute();

            $calls = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return json_encode([
                'status' => 'success',
                'data' => $calls
            ]);
        } catch (Exception $e) {
            return json_encode(['status' => 'error', 'message' => 'Exception: ' . $e->getMessage()]);
        }
    }

    /**
     * Update call log with outcome
     */
    public function updateCallLog($data) {
        try {
            if (!isset($data['call_id'])) {
                return json_encode(['status' => 'error', 'message' => 'Missing call_id']);
            }

            $this->conn->beginTransaction();

            $query = "UPDATE call_logs SET 
                call_outcome = :call_outcome,
                notes = :notes,
                duration_seconds = :duration_seconds
            WHERE call_id = :call_id";

            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':call_id', $data['call_id']);
            $stmt->bindParam(':call_outcome', $data['call_outcome']);
            $stmt->bindParam(':notes', $data['notes']);
            $stmt->bindParam(':duration_seconds', $data['duration_seconds']);

            if ($stmt->execute()) {
                $this->conn->commit();
                return json_encode([
                    'status' => 'success',
                    'message' => 'Call log updated successfully'
                ]);
            } else {
                $this->conn->rollBack();
                return json_encode(['status' => 'error', 'message' => 'Failed to update call log']);
            }
        } catch (Exception $e) {
            $this->conn->rollBack();
            return json_encode(['status' => 'error', 'message' => 'Exception: ' . $e->getMessage()]);
        }
    }

    /**
     * Get call statistics
     */
    public function getCallStatistics($days = 30) {
        try {
            $query = "SELECT 
                call_status,
                COUNT(*) AS total_calls,
                ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(), 2) AS percentage,
                AVG(duration_seconds) AS avg_duration_seconds
            FROM call_logs
            WHERE called_at >= DATE_SUB(CURDATE(), INTERVAL :days DAY)
            GROUP BY call_status
            ORDER BY total_calls DESC";

            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':days', $days, PDO::PARAM_INT);
            $stmt->execute();

            $stats = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return json_encode([
                'status' => 'success',
                'data' => $stats
            ]);
        } catch (Exception $e) {
            return json_encode(['status' => 'error', 'message' => 'Exception: ' . $e->getMessage()]);
        }
    }

    /**
     * Get daily call activity summary
     */
    public function getDailyCallActivity($days = 30) {
        try {
            $query = "SELECT 
                DATE(cl.called_at) AS call_date,
                COUNT(*) AS total_calls,
                COUNT(CASE WHEN cl.call_status = 'connected' THEN 1 END) AS connected_calls,
                COUNT(CASE WHEN cl.call_status = 'no_answer' THEN 1 END) AS no_answer_calls,
                COUNT(CASE WHEN cl.call_outcome = 'payment_promised' THEN 1 END) AS payment_promises,
                SUM(cl.duration_seconds) AS total_duration_seconds
            FROM call_logs cl
            WHERE cl.called_at >= DATE_SUB(CURDATE(), INTERVAL :days DAY)
            GROUP BY DATE(cl.called_at)
            ORDER BY call_date DESC";

            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':days', $days, PDO::PARAM_INT);
            $stmt->execute();

            $activity = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return json_encode([
                'status' => 'success',
                'data' => $activity
            ]);
        } catch (Exception $e) {
            return json_encode(['status' => 'error', 'message' => 'Exception: ' . $e->getMessage()]);
        }
    }
}
