<?php

namespace App\Controllers;

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

class ReportController extends Controller {
    private $db;

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

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

        $input = $this->input();
        $this->validate($input, [
            'reason' => 'required',
            'conversation_id' => 'required'
        ]);

        $conversationId = (int)$input['conversation_id'];
        $reason = trim((string)$input['reason']);
        $reportedId = isset($input['reported_user_id']) ? (int)$input['reported_user_id'] : 0;

        if ($conversationId <= 0) {
            $this->json(['error' => 'Invalid conversation_id'], 422);
        }
        if ($reason === '') {
            $this->json(['error' => 'Reason is required'], 422);
        }

        $stmt = $this->db->prepare("SELECT user_a_id, user_b_id FROM conversations WHERE id = ? LIMIT 1");
        $stmt->execute([$conversationId]);
        $conv = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$conv) {
            $this->json(['error' => 'Conversation not found'], 404);
        }

        $a = (int)$conv['user_a_id'];
        $b = (int)$conv['user_b_id'];
        if ($a !== $userId && $b !== $userId) {
            $this->json(['error' => 'Conversation not accessible'], 403);
        }

        $otherId = ($a === $userId) ? $b : $a;
        if ($reportedId === 0) {
            $reportedId = $otherId;
        } elseif ($reportedId !== $otherId) {
            $reportedId = $otherId;
        }

        if ($reportedId === $userId) {
            $this->json(['error' => 'Cannot report yourself'], 400);
        }

        $stmt = $this->db->prepare("
            INSERT INTO reports (reporter_id, reported_user_id, conversation_id, reason, status, created_at, updated_at)
            VALUES (?, ?, ?, ?, 'open', NOW(), NOW())
        ");
        $stmt->execute([$userId, $reportedId, $conversationId, $reason]);

        $this->json(['success' => true, 'message' => 'Report submitted successfully']);
    }
}
