<?php
require_once __DIR__ . '/config/auth.php';
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/functions.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'unauthenticated']);
    exit;
}
$uid = (int)$_SESSION['user_id'];
$action = $_POST['action'] ?? $_GET['action'] ?? '';

// ── Start or get conversation ──────────────────────────────────────────────
if ($action === 'start_conversation') {
    $other_id = (int)($_POST['other_id'] ?? 0);
    $type     = $_POST['type'] === 'user_admin' ? 'user_admin' : 'user_user';
    if (!$other_id) { echo json_encode(['error' => 'Invalid user']); exit; }

    // Find existing conversation between these two users
    $r = $conn->query("
        SELECT c.id FROM conversations c
        JOIN conversation_participants p1 ON p1.conversation_id = c.id AND p1.user_id = $uid
        JOIN conversation_participants p2 ON p2.conversation_id = c.id AND p2.user_id = $other_id
        WHERE c.type = '$type'
        LIMIT 1
    ");
    if ($r && $r->num_rows > 0) {
        echo json_encode(['conversation_id' => $r->fetch_assoc()['id']]);
    } else {
        $conn->query("INSERT INTO conversations (type) VALUES ('$type')");
        $cid = $conn->insert_id;
        $conn->query("INSERT INTO conversation_participants (conversation_id, user_id) VALUES ($cid, $uid), ($cid, $other_id)");
        echo json_encode(['conversation_id' => $cid]);
    }
    exit;
}

// ── Send message ───────────────────────────────────────────────────────────
if ($action === 'send') {
    $cid = (int)($_POST['conversation_id'] ?? 0);
    $msg = trim($_POST['message'] ?? '');
    if (!$cid || $msg === '') { echo json_encode(['error' => 'Empty']); exit; }

    // Verify sender is participant
    $check = $conn->query("SELECT id FROM conversation_participants WHERE conversation_id=$cid AND user_id=$uid");
    if (!$check || $check->num_rows === 0) { echo json_encode(['error' => 'Forbidden']); exit; }

    $msg_esc = $conn->real_escape_string($msg);
    $conn->query("INSERT INTO messages (conversation_id, sender_id, message) VALUES ($cid, $uid, '$msg_esc')");
    echo json_encode(['ok' => true, 'id' => $conn->insert_id]);
    exit;
}

// ── Fetch messages ─────────────────────────────────────────────────────────
if ($action === 'fetch') {
    $cid   = (int)($_GET['conversation_id'] ?? 0);
    $after = (int)($_GET['after'] ?? 0);
    if (!$cid) { echo json_encode(['messages' => []]); exit; }

    $is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';

    // Verify participant (admins can view any reported conversation)
    if (!$is_admin) {
        $check = $conn->query("SELECT id FROM conversation_participants WHERE conversation_id=$cid AND user_id=$uid");
        if (!$check || $check->num_rows === 0) { echo json_encode(['error' => 'Forbidden']); exit; }
    }

    // Only mark seen if admin is an actual participant
    $part = $conn->query("SELECT id FROM conversation_participants WHERE conversation_id=$cid AND user_id=$uid");
    if ($part && $part->num_rows > 0) {
        $conn->query("UPDATE messages SET seen_status='seen' WHERE conversation_id=$cid AND sender_id != $uid AND seen_status='unseen'");
    }

    $r = $conn->query("
        SELECT m.id, m.sender_id, m.message, m.seen_status, m.created_at,
               u.name as sender_name, u.avatar as sender_avatar
        FROM messages m
        JOIN users u ON u.id = m.sender_id
        WHERE m.conversation_id = $cid AND m.id > $after
        ORDER BY m.created_at ASC
    ");
    $msgs = [];
    while ($row = $r->fetch_assoc()) $msgs[] = $row;
    echo json_encode(['messages' => $msgs]);
    exit;
}

// ── List conversations ─────────────────────────────────────────────────────
if ($action === 'list') {
    $is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';

    if ($is_admin) {
        // Admin sees all conversations
        $r = $conn->query("
            SELECT c.id, c.type, c.created_at,
                   (SELECT message FROM messages WHERE conversation_id=c.id ORDER BY created_at DESC LIMIT 1) as last_msg,
                   (SELECT created_at FROM messages WHERE conversation_id=c.id ORDER BY created_at DESC LIMIT 1) as last_time,
                   (SELECT COUNT(*) FROM messages WHERE conversation_id=c.id AND seen_status='unseen' AND sender_id != $uid) as unread,
                   GROUP_CONCAT(DISTINCT u.name ORDER BY u.id SEPARATOR ', ') as participants,
                   (SELECT cp2.user_id FROM conversation_participants cp2 WHERE cp2.conversation_id=c.id AND cp2.user_id != $uid LIMIT 1) as other_id,
                   (SELECT u2.avatar FROM conversation_participants cp2 JOIN users u2 ON u2.id=cp2.user_id WHERE cp2.conversation_id=c.id AND cp2.user_id != $uid LIMIT 1) as other_avatar
            FROM conversations c
            JOIN conversation_participants cp ON cp.conversation_id = c.id
            JOIN users u ON u.id = cp.user_id
            GROUP BY c.id
            ORDER BY last_time DESC
        ");
    } else {
        $r = $conn->query("
            SELECT c.id, c.type, c.created_at,
                   (SELECT message FROM messages WHERE conversation_id=c.id ORDER BY created_at DESC LIMIT 1) as last_msg,
                   (SELECT created_at FROM messages WHERE conversation_id=c.id ORDER BY created_at DESC LIMIT 1) as last_time,
                   (SELECT COUNT(*) FROM messages WHERE conversation_id=c.id AND seen_status='unseen' AND sender_id != $uid) as unread,
                   (SELECT u2.name FROM conversation_participants cp2 JOIN users u2 ON u2.id=cp2.user_id WHERE cp2.conversation_id=c.id AND cp2.user_id != $uid LIMIT 1) as other_name,
                   (SELECT u2.avatar FROM conversation_participants cp2 JOIN users u2 ON u2.id=cp2.user_id WHERE cp2.conversation_id=c.id AND cp2.user_id != $uid LIMIT 1) as other_avatar,
                   (SELECT u2.id FROM conversation_participants cp2 JOIN users u2 ON u2.id=cp2.user_id WHERE cp2.conversation_id=c.id AND cp2.user_id != $uid LIMIT 1) as other_id
            FROM conversations c
            JOIN conversation_participants cp ON cp.conversation_id = c.id AND cp.user_id = $uid
            ORDER BY last_time DESC
        ");
    }
    $list = [];
    while ($row = $r->fetch_assoc()) $list[] = $row;
    echo json_encode(['conversations' => $list]);
    exit;
}

// ── Report conversation ────────────────────────────────────────────────────
if ($action === 'report') {
    $cid           = (int)($_POST['conversation_id'] ?? 0);
    $reported_user = (int)($_POST['reported_user_id'] ?? 0);
    $reason        = trim($_POST['reason'] ?? '');
    if (!$cid || !$reported_user || !$reason) { echo json_encode(['error' => 'Missing fields']); exit; }
    $reason_esc = $conn->real_escape_string($reason);
    $conn->query("INSERT INTO conversation_reports (reporter_id, reported_user_id, conversation_id, reason) VALUES ($uid, $reported_user, $cid, '$reason_esc')");
    echo json_encode(['ok' => true]);
    exit;
}

// ── Admin: get reported conversations ─────────────────────────────────────
if ($action === 'reported_list') {
    if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { echo json_encode(['error' => 'Forbidden']); exit; }
    $r = $conn->query("
        SELECT cr.*, u1.name as reporter_name, u2.name as reported_name
        FROM conversation_reports cr
        JOIN users u1 ON u1.id = cr.reporter_id
        JOIN users u2 ON u2.id = cr.reported_user_id
        ORDER BY cr.created_at DESC
    ");
    $list = [];
    while ($row = $r->fetch_assoc()) $list[] = $row;
    echo json_encode(['reports' => $list]);
    exit;
}

// ── Admin: mark report reviewed ────────────────────────────────────────────
if ($action === 'mark_reviewed') {
    if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { echo json_encode(['error' => 'Forbidden']); exit; }
    $rid = (int)($_POST['report_id'] ?? 0);
    $conn->query("UPDATE conversation_reports SET status='reviewed' WHERE id=$rid");
    echo json_encode(['ok' => true]);
    exit;
}

// ── Admin: take action on report ──────────────────────────────────────────
if ($action === 'report_action') {
    if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { echo json_encode(['error' => 'Forbidden']); exit; }
    $rid         = (int)($_POST['report_id'] ?? 0);
    $decision    = $_POST['decision'] ?? ''; // approve | reject | warn
    $sub_action  = $_POST['sub_action'] ?? ''; // suspend | ban | restrict (when approve)
    if (!$rid || !in_array($decision, ['approve','reject','warn'])) { echo json_encode(['error' => 'Invalid']); exit; }

    // Get report details
    $rep = $conn->query("SELECT * FROM conversation_reports WHERE id=$rid")->fetch_assoc();
    if (!$rep) { echo json_encode(['error' => 'Not found']); exit; }
    $reported_uid = (int)$rep['reported_user_id'];

    // Ensure columns exist (compatible with MySQL 5.7+)
    $chk1 = $conn->query("SHOW COLUMNS FROM conversation_reports LIKE 'admin_decision'");
    if ($chk1->num_rows === 0) $conn->query("ALTER TABLE conversation_reports ADD COLUMN admin_decision VARCHAR(50) DEFAULT NULL");
    $chk2 = $conn->query("SHOW COLUMNS FROM conversation_reports LIKE 'admin_note'");
    if ($chk2->num_rows === 0) $conn->query("ALTER TABLE conversation_reports ADD COLUMN admin_note TEXT DEFAULT NULL");
    $conn->query("ALTER TABLE users MODIFY COLUMN account_status ENUM('pending','active','rejected','suspended','banned') DEFAULT 'pending'");

    if ($decision === 'approve') {
        $new_status = 'suspended';
        if ($sub_action === 'ban') $new_status = 'banned';
        $conn->query("UPDATE users SET account_status='$new_status' WHERE id=$reported_uid");
        $msg_esc = $conn->real_escape_string("Your account has been $new_status due to a reported violation.");
        $conn->query("INSERT INTO notifications (user_id, message, notification_type) VALUES ($reported_uid, '$msg_esc', 'general')");
        $conn->query("UPDATE conversation_reports SET status='reviewed', admin_decision='$new_status' WHERE id=$rid");
        logActivity($conn, 'report_action', 'user', $reported_uid, "Report approved — user $new_status");
        echo json_encode(['ok' => true, 'result' => $new_status]);
    } elseif ($decision === 'reject') {
        $conn->query("UPDATE conversation_reports SET status='reviewed', admin_decision='rejected' WHERE id=$rid");
        logActivity($conn, 'report_action', 'user', $reported_uid, 'Report rejected — no action taken');
        echo json_encode(['ok' => true, 'result' => 'rejected']);
    } elseif ($decision === 'warn') {
        $msg_esc = $conn->real_escape_string('⚠️ Official Warning: Your behavior has been flagged. Further violations may result in suspension.');
        $conn->query("INSERT INTO notifications (user_id, message, notification_type) VALUES ($reported_uid, '$msg_esc', 'general')");
        $conn->query("UPDATE conversation_reports SET status='reviewed', admin_decision='warned' WHERE id=$rid");
        logActivity($conn, 'report_action', 'user', $reported_uid, 'Report — warning sent to user');
        echo json_encode(['ok' => true, 'result' => 'warned']);
    }
    exit;
}

// ── Delete message ─────────────────────────────────────────────────────────
if ($action === 'delete_message') {
    $mid = (int)($_POST['message_id'] ?? 0);
    if (!$mid) { echo json_encode(['error' => 'Invalid']); exit; }
    $is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
    // Admin can delete any message; users can only delete their own
    if ($is_admin) {
        $conn->query("DELETE FROM messages WHERE id=$mid");
    } else {
        $conn->query("DELETE FROM messages WHERE id=$mid AND sender_id=$uid");
    }
    echo json_encode(['ok' => $conn->affected_rows > 0]);
    exit;
}

// ── Delete conversation ────────────────────────────────────────────────────
if ($action === 'delete_conversation') {
    $cid = (int)($_POST['conversation_id'] ?? 0);
    if (!$cid) { echo json_encode(['error' => 'Invalid']); exit; }
    
    // Verify user is a participant
    $check = $conn->query("SELECT id FROM conversation_participants WHERE conversation_id=$cid AND user_id=$uid");
    if (!$check || $check->num_rows === 0) { echo json_encode(['error' => 'Forbidden']); exit; }
    
    // Delete reports first (no cascade, must delete manually)
    $conn->query("DELETE FROM conversation_reports WHERE conversation_id=$cid");
    // Delete messages
    $conn->query("DELETE FROM messages WHERE conversation_id=$cid");
    // Delete all participants
    $conn->query("DELETE FROM conversation_participants WHERE conversation_id=$cid");
    // Delete the conversation completely
    $conn->query("DELETE FROM conversations WHERE id=$cid");
    
    echo json_encode(['ok' => true]);
    exit;
}

// ── Clear all messages in conversation ──────────────────────────────────────
if ($action === 'clear_messages') {
    $cid = (int)($_POST['conversation_id'] ?? 0);
    if (!$cid) { echo json_encode(['error' => 'Invalid']); exit; }
    
    // Verify user is a participant
    $check = $conn->query("SELECT id FROM conversation_participants WHERE conversation_id=$cid AND user_id=$uid");
    if (!$check || $check->num_rows === 0) { echo json_encode(['error' => 'Forbidden']); exit; }
    
    // Delete all messages in the conversation
    $conn->query("DELETE FROM messages WHERE conversation_id=$cid");
    
    echo json_encode(['ok' => true]);
    exit;
}

// ── Get users list (for starting new chat) ────────────────────────────────
if ($action === 'users_list') {
    $search = $conn->real_escape_string(trim($_GET['q'] ?? ''));
    $is_admin = isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
    $role_filter = $is_admin ? '' : "AND role != 'admin'"; // users can message admins too
    $r = $conn->query("SELECT id, name, avatar, role FROM users WHERE id != $uid AND name LIKE '%$search%' $role_filter ORDER BY name LIMIT 20");
    $list = [];
    while ($row = $r->fetch_assoc()) $list[] = $row;
    echo json_encode(['users' => $list]);
    exit;
}

// ── Get user profile ──────────────────────────────────────────────────────
if ($action === 'get_profile') {
    $target_id = (int)($_GET['user_id'] ?? 0);
    if (!$target_id) { echo json_encode(['error' => 'Invalid']); exit; }
    $r = $conn->query("SELECT id, name, email, avatar, role, gender, created_at FROM users WHERE id=$target_id");
    if (!$r || $r->num_rows === 0) { echo json_encode(['error' => 'Not found']); exit; }
    echo json_encode(['profile' => $r->fetch_assoc()]);
    exit;
}

echo json_encode(['error' => 'Unknown action']);
