<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Config\Database;
use App\Middleware\AuthMiddleware;
use PDO;

class BlockController extends Controller {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }

    private function resolveTargetIdFromConversation($userId, $conversationId) {
        $stmt = $this->db->prepare("SELECT user_a_id, user_b_id FROM conversations WHERE id = ? LIMIT 1");
        $stmt->execute([(int)$conversationId]);
        $conv = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$conv) return 0;

        $a = (int)$conv['user_a_id'];
        $b = (int)$conv['user_b_id'];
        if ($a !== (int)$userId && $b !== (int)$userId) return 0;
        return $a === (int)$userId ? $b : $a;
    }

    public function status() {
        $userIdRaw = AuthMiddleware::authenticate();
        $userId = is_numeric($userIdRaw) ? (int)$userIdRaw : 0;
        if ($userId <= 0) $this->json(['error' => 'Unauthorized'], 401);

        $input = $this->input();
        $conversationId = isset($input['conversation_id']) ? (int)$input['conversation_id'] : 0;
        $targetId = isset($input['target_id']) ? (int)$input['target_id'] : 0;

        if ($targetId === 0 && $conversationId > 0) {
            $targetId = $this->resolveTargetIdFromConversation($userId, $conversationId);
        }
        if ($targetId <= 0 || $targetId === $userId) {
            $this->json(['error' => 'Invalid user'], 400);
        }

        $stmt = $this->db->prepare("SELECT 1 FROM blocked_users WHERE blocker_id = ? AND blocked_id = ? LIMIT 1");
        $stmt->execute([$userId, $targetId]);
        $isBlocked = (bool)$stmt->fetchColumn();

        $this->json(['success' => true, 'blocked' => $isBlocked, 'target_id' => $targetId]);
    }

    public function toggle() {
        $userIdRaw = AuthMiddleware::authenticate();
        $userId = is_numeric($userIdRaw) ? (int)$userIdRaw : 0;
        if ($userId <= 0) $this->json(['error' => 'Unauthorized'], 401);

        $input = $this->input();
        $conversationId = isset($input['conversation_id']) ? (int)$input['conversation_id'] : 0;
        $targetId = isset($input['target_id']) ? (int)$input['target_id'] : 0;

        if ($targetId === 0 && $conversationId > 0) {
            $targetId = $this->resolveTargetIdFromConversation($userId, $conversationId);
        }

        if ($targetId <= 0 || $targetId === $userId) {
            $this->json(['error' => 'Invalid user to block'], 400);
        }

        $stmt = $this->db->prepare("SELECT id FROM blocked_users WHERE blocker_id = ? AND blocked_id = ? LIMIT 1");
        $stmt->execute([$userId, $targetId]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            $stmt = $this->db->prepare("DELETE FROM blocked_users WHERE id = ?");
            $stmt->execute([(int)$existing['id']]);
            $this->json(['success' => true, 'status' => 'unblocked', 'message' => 'User unblocked', 'target_id' => $targetId]);
        } else {
            $stmt = $this->db->prepare("INSERT INTO blocked_users (blocker_id, blocked_id, created_at) VALUES (?, ?, NOW())");
            $stmt->execute([$userId, $targetId]);
            $this->json(['success' => true, 'status' => 'blocked', 'message' => 'User blocked', 'target_id' => $targetId]);
        }
    }
}

