<?php
/**
 * ============================================================================
 * stories/delete.php - Delete Story 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();
$storyId = isset($_POST['story_id']) ? (int)$_POST['story_id'] : 0;

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $storyClass = new \App\Story($db);
    
    // Get story to verify ownership and get media URL
    $story = $storyClass->getStory($storyId);
    
    if (!$story) {
        echo json_encode(['success' => false, 'error' => 'Story not found']);
        exit();
    }
    
    if ($story['user_id'] != $userId) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit();
    }
    
    // Delete media file if exists
    if ($story['media_url']) {
        $filename = basename($story['media_url']);
        $filePath = __DIR__ . '/../assets/uploads/stories/' . $filename;
        if (file_exists($filePath)) {
            unlink($filePath);
        }
    }
    
    // Delete story
    $result = $storyClass->delete($storyId, $userId);
    
    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'Story deleted successfully'
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to delete story']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>