<?php
session_start();
require 'config.php';

// Prevent any PHP errors from breaking the JSON output
error_reporting(0);
ini_set('display_errors', 0);

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

try {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }

    $user_id = $_SESSION['user_id'];
    $action = $_POST['action'] ?? '';

    if ($action === 'upload') {
        if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
            echo json_encode(['success' => false, 'error' => 'Image upload failed']);
            exit;
        }

        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'mov', 'webm'];
        $filename = $_FILES['image']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if (!in_array($ext, $allowed)) {
            echo json_encode(['success' => false, 'error' => 'Invalid file type']);
            exit;
        }

        $newParams = uniqid() . '.' . $ext;
        $targetPath = 'uploads/' . $newParams;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
            $caption = $_POST['caption'] ?? '';
            $type = $_POST['type'] ?? 'post'; // post, reel, story
            
            $mediaType = in_array($ext, ['mp4', 'mov', 'webm']) ? 'video' : 'image';
            
            if ($type === 'story') {
                $stmt = $pdo->prepare("INSERT INTO stories (user_id, media_url, media_type, expires_at) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 24 HOUR))");
                $stmt->execute([$user_id, $targetPath, $mediaType]);
            } else {
                $postType = ($type === 'reel') ? 'reel' : 'post';
                $stmt = $pdo->prepare("INSERT INTO posts (user_id, image_url, caption, type, media_type) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$user_id, $targetPath, $caption, $postType, $mediaType]);
            }
            
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Failed to save file']);
        }
        exit;
    }

    if ($action === 'update_profile') {
        $full_name = $_POST['full_name'];
        $bio = $_POST['bio'];
        
        if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
            $target = 'uploads/av_' . uniqid() . '.' . $ext;
            if (move_uploaded_file($_FILES['avatar']['tmp_name'], $target)) {
                $stmt = $pdo->prepare("UPDATE users SET avatar = ? WHERE id = ?");
                $stmt->execute([$target, $user_id]);
            }
        }

        $stmt = $pdo->prepare("UPDATE users SET full_name = ?, bio = ? WHERE id = ?");
        $stmt->execute([$full_name, $bio, $user_id]);
        
        echo json_encode(['success' => true]);
        exit;
    }

    if ($action === 'edit_post') {
        $post_id = $_POST['post_id'];
        $caption = $_POST['caption'];
        $stmt = $pdo->prepare("UPDATE posts SET caption = ? WHERE id = ? AND user_id = ?");
        $stmt->execute([$caption, $post_id, $user_id]);
        echo json_encode(['success' => true]);
        exit;
    }

    if ($action === 'delete_post') {
        $post_id = $_POST['post_id'];
        $stmt = $pdo->prepare("DELETE FROM posts WHERE id = ? AND user_id = ?");
        $stmt->execute([$post_id, $user_id]);
        echo json_encode(['success' => true]);
        exit;
    }

    if ($action === 'like') {
        $post_id = $_POST['post_id'];
        $stmt = $pdo->prepare("SELECT id FROM likes WHERE user_id = ? AND post_id = ?");
        $stmt->execute([$user_id, $post_id]);
        $existing = $stmt->fetch();

        if ($existing) {
            $stmt = $pdo->prepare("DELETE FROM likes WHERE id = ?");
            $stmt->execute([$existing['id']]);
            $liked = false;
        } else {
            $stmt = $pdo->prepare("INSERT INTO likes (user_id, post_id) VALUES (?, ?)");
            $stmt->execute([$user_id, $post_id]);
            $liked = true;
        }

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM likes WHERE post_id = ?");
        $stmt->execute([$post_id]);
        $count = $stmt->fetchColumn();

        echo json_encode(['success' => true, 'liked' => $liked, 'count' => $count]);
        exit;
    }

    if ($action === 'get_comments') {
        $post_id = $_POST['post_id'];
        $stmt = $pdo->prepare("
            SELECT c.*, u.username, u.avatar 
            FROM comments c 
            JOIN users u ON c.user_id = u.id 
            WHERE c.post_id = ? 
            ORDER BY c.created_at DESC
        ");
        $stmt->execute([$post_id]);
        $comments = $stmt->fetchAll();
        
        foreach ($comments as &$c) {
            $diff = time() - strtotime($c['created_at']);
            if ($diff < 60) $c['time_ago'] = 'Just now';
            elseif ($diff < 3600) $c['time_ago'] = floor($diff/60).'хв';
            elseif ($diff < 86400) $c['time_ago'] = floor($diff/3600).'год';
            else $c['time_ago'] = floor($diff/86400).'д';
        }
        
        echo json_encode(['success' => true, 'comments' => $comments]);
        exit;
    }

    if ($action === 'add_comment') {
        error_log("add_comment action called");
        error_log("POST data: " . print_r($_POST, true));
        
        $post_id = $_POST['post_id'] ?? null;
        $text = trim($_POST['text'] ?? '');
        
        error_log("post_id: $post_id, text: $text, user_id: $user_id");
        
        if (empty($text)) {
            error_log("Empty comment text");
            echo json_encode(['success' => false, 'error' => 'Comment cannot be empty']);
            exit;
        }
        
        if (empty($post_id)) {
            error_log("Missing post_id");
            echo json_encode(['success' => false, 'error' => 'Missing post_id']);
            exit;
        }
        
        try {
            $stmt = $pdo->prepare("INSERT INTO comments (user_id, post_id, comment_text) VALUES (?, ?, ?)");
            $stmt->execute([$user_id, $post_id, $text]);
            $newId = $pdo->lastInsertId();
            error_log("Comment inserted with ID: $newId");
            
            $stmt = $pdo->prepare("SELECT c.*, u.username, u.avatar FROM comments c JOIN users u ON c.user_id = u.id WHERE c.id = ?");
            $stmt->execute([$newId]);
            $comment = $stmt->fetch();
            $comment['time_ago'] = 'Just now';
            
            error_log("Comment data retrieved successfully");
            echo json_encode(['success' => true, 'comment' => $comment]);
        } catch (PDOException $e) {
            error_log("Database error: " . $e->getMessage());
            echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
        }
        exit;
    }

    if ($action === 'get_post_details') {
        $post_id = $_POST['post_id'];
        $stmt = $pdo->prepare("
            SELECT p.*, u.username, u.avatar,
            (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
            (SELECT COUNT(*) FROM saved_posts WHERE post_id = p.id AND user_id = ?) as is_saved
            FROM posts p
            JOIN users u ON p.user_id = u.id
            WHERE p.id = ?
        ");
        $stmt->execute([$user_id, $post_id]);
        $post = $stmt->fetch();
        if ($post) {
            echo json_encode(['success' => true, 'post' => $post]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Post not found']);
        }
        exit;
    }

    if ($action === 'delete_comment') {
        $comment_id = $_POST['comment_id'] ?? null;
        
        if (empty($comment_id)) {
            echo json_encode(['success' => false, 'error' => 'Missing comment_id']);
            exit;
        }
        
        try {
            // Check if user owns the comment
            $stmt = $pdo->prepare("SELECT user_id FROM comments WHERE id = ?");
            $stmt->execute([$comment_id]);
            $comment = $stmt->fetch();
            
            if (!$comment) {
                echo json_encode(['success' => false, 'error' => 'Comment not found']);
                exit;
            }
            
            if ($comment['user_id'] != $user_id) {
                echo json_encode(['success' => false, 'error' => 'Permission denied']);
                exit;
            }
            
            // Delete the comment
            $stmt = $pdo->prepare("DELETE FROM comments WHERE id = ?");
            $stmt->execute([$comment_id]);
            
            echo json_encode(['success' => true]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
        }
        exit;
    }

    if ($action === 'follow') {
        $following_id = $_POST['user_id'];
        $stmt = $pdo->prepare("SELECT * FROM follows WHERE follower_id = ? AND following_id = ?");
        $stmt->execute([$user_id, $following_id]);
        if ($stmt->fetch()) {
            $stmt = $pdo->prepare("DELETE FROM follows WHERE follower_id = ? AND following_id = ?");
            $stmt->execute([$user_id, $following_id]);
            echo json_encode(['success' => true, 'following' => false]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO follows (follower_id, following_id) VALUES (?, ?)");
            $stmt->execute([$user_id, $following_id]);
            echo json_encode(['success' => true, 'following' => true]);
        }
        exit;
    }

    if ($action === 'get_profile_posts') {
        $target_id = $_POST['user_id'];
        $tab = $_POST['tab'] ?? 'posts'; // posts, reels, saved
        
        if ($tab === 'saved') {
            // Check if own profile for privacy (usually only own saved are visible)
            if ($target_id != $user_id) {
                echo json_encode(['success' => false, 'error' => 'Permission denied']);
                exit;
            }
            $stmt = $pdo->prepare("
                SELECT p.* 
                FROM posts p 
                JOIN saved_posts s ON p.id = s.post_id 
                WHERE s.user_id = ? 
                ORDER BY s.created_at DESC
            ");
            $stmt->execute([$user_id]);
        } elseif ($tab === 'reels') {
            $stmt = $pdo->prepare("SELECT * FROM posts WHERE user_id = ? AND type = 'reel' ORDER BY created_at DESC");
            $stmt->execute([$target_id]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM posts WHERE user_id = ? AND type = 'post' ORDER BY created_at DESC");
            $stmt->execute([$target_id]);
        }
        
        $posts = $stmt->fetchAll();
        echo json_encode(['success' => true, 'posts' => $posts]);
        exit;
    }

    if ($action === 'save_post') {
        $post_id = $_POST['post_id'] ?? null;
        
        if (empty($post_id)) {
            echo json_encode(['success' => false, 'error' => 'Missing post_id']);
            exit;
        }
        
        try {
            // Check if already saved
            $stmt = $pdo->prepare("SELECT * FROM saved_posts WHERE user_id = ? AND post_id = ?");
            $stmt->execute([$user_id, $post_id]);
            
            if ($stmt->fetch()) {
                // Unsave
                $stmt = $pdo->prepare("DELETE FROM saved_posts WHERE user_id = ? AND post_id = ?");
                $stmt->execute([$user_id, $post_id]);
                echo json_encode(['success' => true, 'saved' => false]);
            } else {
                // Save
                $stmt = $pdo->prepare("INSERT INTO saved_posts (user_id, post_id) VALUES (?, ?)");
                $stmt->execute([$user_id, $post_id]);
                echo json_encode(['success' => true, 'saved' => true]);
            }
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
        }
        exit;
    }

    if ($action === 'get_messages') {
        $conv_id = $_POST['conversation_id'];
        $stmt = $pdo->prepare("
            SELECT m.*, u.username, u.avatar 
            FROM messages m
            JOIN users u ON m.sender_id = u.id
            WHERE m.conversation_id = ?
            ORDER BY m.created_at ASC
        ");
        $stmt->execute([$conv_id]);
        $messages = $stmt->fetchAll();
        
        echo json_encode(['success' => true, 'messages' => $messages]);
        exit;
    }

    if ($action === 'send_message') {
        $conv_id = $_POST['conversation_id'];
        $text = trim($_POST['message']);
        if (empty($text)) {
            echo json_encode(['success' => false, 'error' => 'Empty message']);
            exit;
        }
        $stmt = $pdo->prepare("INSERT INTO messages (conversation_id, sender_id, message) VALUES (?, ?, ?)");
        $stmt->execute([$conv_id, $user_id, $text]);
        
        // Update last_message in conversation
        $stmt = $pdo->prepare("UPDATE conversations SET last_message = ?, last_message_time = NOW() WHERE id = ?");
        $stmt->execute([$text, $conv_id]);
        
        echo json_encode(['success' => true]);
        exit;
    }

    if ($action === 'start_conversation') {
        $target_user_id = $_POST['user_id'];
        // Check if already exists
        $stmt = $pdo->prepare("SELECT id FROM conversations WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)");
        $stmt->execute([$user_id, $target_user_id, $target_user_id, $user_id]);
        $conv = $stmt->fetch();
        
        if ($conv) {
            echo json_encode(['success' => true, 'conversation_id' => $conv['id']]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO conversations (user1_id, user2_id) VALUES (?, ?)");
            $stmt->execute([$user_id, $target_user_id]);
            echo json_encode(['success' => true, 'conversation_id' => $pdo->lastInsertId()]);
        }
        exit;
    }

    if ($action === 'create_note') {
        $text = trim($_POST['text']);
        if (mb_strlen($text) > 60) {
            echo json_encode(['success' => false, 'error' => 'Too long']);
            exit;
        }
        
        // Remove old notes
        $stmt = $pdo->prepare("DELETE FROM notes WHERE user_id = ?");
        $stmt->execute([$user_id]);
        
        if (!empty($text)) {
            $stmt = $pdo->prepare("INSERT INTO notes (user_id, note_text, expires_at) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 24 HOUR))");
            $stmt->execute([$user_id, $text]);
        }
        
        echo json_encode(['success' => true]);
        exit;
    }

    if ($action === 'get_notes') {
        // Ensure table exists (Auto-migration)
        $pdo->exec("CREATE TABLE IF NOT EXISTS notes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            note_text VARCHAR(60),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            expires_at TIMESTAMP NULL,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )");

        // Get notes from people I follow + myself
        $stmt = $pdo->prepare("
            SELECT n.*, u.username, u.avatar 
            FROM notes n
            JOIN users u ON n.user_id = u.id
            WHERE (n.user_id = ? OR n.user_id IN (SELECT following_id FROM follows WHERE follower_id = ?))
            AND n.expires_at > NOW()
            ORDER BY n.created_at DESC
        ");
        $stmt->execute([$user_id, $user_id]);
        $notes = $stmt->fetchAll();
        echo json_encode(['success' => true, 'notes' => $notes]);
        exit;
    }
    
    if ($action === 'search_users') {
        $q = trim($_POST['q'] ?? '');
        if (empty($q)) {
            echo json_encode(['success' => true, 'users' => []]);
            exit;
        }
        $stmt = $pdo->prepare("SELECT id, username, full_name, avatar FROM users WHERE username LIKE ? OR full_name LIKE ? LIMIT 20");
        $stmt->execute(["%$q%", "%$q%"]);
        $users = $stmt->fetchAll();
        echo json_encode(['success' => true, 'users' => $users]);
        exit;
    }

    echo json_encode(['success' => false, 'error' => 'Invalid action']);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'DB Error: ' . $e->getMessage()]);
}
