<?php

namespace App\Controllers;

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

class SocialController extends Controller {
    private $db;

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

    public function follow() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        $targetId = $input['user_id'];

        $stmt = $this->db->prepare("INSERT IGNORE INTO follows (follower_id, followed_id, created_at) VALUES (?, ?, NOW())");
        $stmt->execute([$userId, $targetId]);

        $this->json(['success' => true]);
    }

    public function unfollow($targetId) {
        $userId = AuthMiddleware::authenticate();
        
        $stmt = $this->db->prepare("DELETE FROM follows WHERE follower_id = ? AND followed_id = ?");
        $stmt->execute([$userId, $targetId]);

        $this->json(['success' => true]);
    }

    public function block() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        $targetId = $input['user_id'];
        $reason = isset($input['reason']) ? $input['reason'] : null;

        $stmt = $this->db->prepare("INSERT IGNORE INTO blocks (blocker_id, blocked_id, reason, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$userId, $targetId, $reason]);

        // Also unfollow
        $stmt = $this->db->prepare("DELETE FROM follows WHERE (follower_id = ? AND followed_id = ?) OR (follower_id = ? AND followed_id = ?)");
        $stmt->execute([$userId, $targetId, $targetId, $userId]);

        $this->json(['success' => true]);
    }

    public function report() {
        $userId = AuthMiddleware::authenticate();
        $input = $this->input();
        $this->validate($input, ['reported_user_id' => 'required', 'reason' => 'required']);

        $stmt = $this->db->prepare("INSERT INTO reports (reporter_id, reported_user_id, message_id, reason, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())");
        $stmt->execute([
            $userId, 
            $input['reported_user_id'], 
            isset($input['message_id']) ? $input['message_id'] : null,
            $input['reason']
        ]);

        $this->json(['success' => true]);
    }
}
