<?php
/**
 * ============================================================================
 * posts/delete.php - Delete Post API
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

$userId = getUserId();
$postId = isset($_POST['post_id']) ? (int)$_POST['post_id'] : 0;

if (!$postId) {
    echo json_encode(['success' => false, 'error' => 'Invalid post ID']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $postClass = new \App\Post($db);
    
    // Verify post ownership
    $post = $postClass->getPost($postId, $userId);
    
    if (!$post) {
        echo json_encode(['success' => false, 'error' => 'Post not found']);
        exit();
    }
    
    if ($post['user_id'] != $userId) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit();
    }
    
    // Delete associated media files
    if ($post['media_urls']) {
        $mediaUrls = json_decode($post['media_urls'], true);
        if ($mediaUrls && is_array($mediaUrls)) {
            foreach ($mediaUrls as $url) {
                $filename = basename($url);
                $filePath = __DIR__ . '/../assets/uploads/posts/' . $filename;
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }
        }
    }
    
    // Delete post
    $result = $postClass->delete($postId, $userId);
    
    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'Post deleted successfully'
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to delete post']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>