<?php
require_once 'config/database.php';

/**
 * ContactCallsController
 *
 * Lightweight call log for calls placed to contacts from the Contacts module
 * (browser → Twilio Voice). Distinct from the invoice-driven `calls` table,
 * which requires a follow_up_id. Also stores the note taken in the call widget.
 */
class ContactCallsController {
    private $conn;

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

    private function error($message) {
        return json_encode(['status' => 'error', 'message' => $message]);
    }

    /** Called when a call is placed. Returns the new log id. */
    public function start($data, $userId) {
        if (empty($data['phone'])) return $this->error('phone is required');

        $contactId = !empty($data['contact_id']) ? (int)$data['contact_id'] : null;

        $stmt = $this->conn->prepare(
            "INSERT INTO contact_calls (contact_id, user_id, phone, status, started_at)
             VALUES (:contact_id, :user_id, :phone, 'initiated', NOW())"
        );
        $stmt->bindValue(':contact_id', $contactId, $contactId === null ? PDO::PARAM_NULL : PDO::PARAM_INT);
        $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
        $stmt->bindValue(':phone', $data['phone']);

        if ($stmt->execute()) {
            return json_encode([
                'status' => 'success',
                'message' => 'Call log started',
                'data' => ['contact_call_id' => (int)$this->conn->lastInsertId()],
            ]);
        }
        return $this->error('Failed to start call log');
    }

    /** Called when the call ends (and again on "Save & close" to persist the note). */
    public function end($data) {
        $id = $data['contact_call_id'] ?? null;
        if (!$id) return $this->error('contact_call_id is required');

        $fields = ['ended_at = NOW()'];
        $params = [':id' => (int)$id];

        foreach (['call_sid' => 'call_sid', 'status' => 'status', 'note' => 'note'] as $key => $col) {
            if (array_key_exists($key, $data)) {
                $fields[] = "$col = :$col";
                $params[":$col"] = ($data[$key] !== '' ? $data[$key] : null);
            }
        }
        if (isset($data['duration'])) {
            $fields[] = 'duration = :duration';
            $params[':duration'] = (int)$data['duration'];
        }

        $sql = 'UPDATE contact_calls SET ' . implode(', ', $fields) . ' WHERE id = :id';
        $stmt = $this->conn->prepare($sql);
        if ($stmt->execute($params)) {
            return json_encode(['status' => 'success', 'message' => 'Call log updated']);
        }
        return $this->error('Failed to update call log');
    }

    /** Recent call history, optionally scoped to a contact. */
    public function history($filters) {
        $where = '1=1';
        $params = [];
        if (!empty($filters['contact_id'])) {
            $where .= ' AND cc.contact_id = :cid';
            $params[':cid'] = (int)$filters['contact_id'];
        }
        $stmt = $this->conn->prepare(
            "SELECT cc.*, CONCAT(u.first_name, ' ', u.last_name) AS caller_name
             FROM contact_calls cc
             LEFT JOIN users u ON cc.user_id = u.id
             WHERE $where
             ORDER BY cc.created_at DESC
             LIMIT 100"
        );
        $stmt->execute($params);
        return json_encode(['status' => 'success', 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }
}
