<?php
require_once '../config/database.php';

$db = new Database();
$conn = $db->connect();

// Set content type to JSON
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $username = isset($_GET['username']) ? $_GET['username'] : null;
        if ($username) {
            // Fetch stories for a specific user
            $stmt = $conn->prepare('SELECT * FROM stories WHERE username = :username ORDER BY created_at ASC');
            $stmt->execute([':username' => $username]);
        } else {
            // Fetch all stories
            $stmt = $conn->prepare('SELECT * FROM stories ORDER BY created_at ASC');
            $stmt->execute();
        }
        $stories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($stories);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to fetch stories: ' . $e->getMessage()]);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    // Handle story creation
    if (isset($input['id'], $input['username'], $input['image_url'])) {
        try {
            $stmt = $conn->prepare('INSERT INTO stories (id, username, image_url, created_at) VALUES (:id, :username, :image_url, NOW())');
            $stmt->execute([
                ':id' => $input['id'],
                ':username' => $input['username'],
                ':image_url' => $input['image_url']
            ]);
            http_response_code(201);
            echo json_encode(['message' => 'Story created successfully']);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to create story: ' . $e->getMessage()]);
        }
    }
    // Handle recording a story view
    elseif (isset($input['story_id'], $input['viewer_username'])) {
        try {
            $stmt = $conn->prepare('INSERT INTO story_viewers (story_id, viewer_username, viewed_at) VALUES (:story_id, :viewer_username, NOW()) ON DUPLICATE KEY UPDATE viewed_at = NOW()');
            $stmt->execute([
                ':story_id' => $input['story_id'],
                ':viewer_username' => $input['viewer_username']
            ]);
            http_response_code(200);
            echo json_encode(['message' => 'Story view recorded']);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to record view: ' . $e->getMessage()]);
        }
    }
    // Handle reporting a story
    elseif (isset($input['story_id'], $input['reporter_username'])) {
        try {
            $stmt = $conn->prepare('INSERT INTO story_reports (story_id, reporter_username, reported_at) VALUES (:story_id, :reporter_username, NOW())');
            $stmt->execute([
                ':story_id' => $input['story_id'],
                ':reporter_username' => $input['reporter_username']
            ]);
            http_response_code(200);
            echo json_encode(['message' => 'Story reported successfully']);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to report story: ' . $e->getMessage()]);
        }
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid POST request']);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['story_id'], $input['username'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing story_id or username']);
        exit;
    }

    try {
        // Verify the story belongs to the user
        $stmt = $conn->prepare('SELECT username FROM stories WHERE id = :story_id');
        $stmt->execute([':story_id' => $input['story_id']]);
        $story = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$story || $story['username'] !== $input['username']) {
            http_response_code(403);
            echo json_encode(['error' => 'Unauthorized to delete this story']);
            exit;
        }

        $stmt = $conn->prepare('DELETE FROM stories WHERE id = :story_id');
        $stmt->execute([':story_id' => $input['story_id']]);
        http_response_code(200);
        echo json_encode(['message' => 'Story deleted successfully']);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to delete story: ' . $e->getMessage()]);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['viewers']) && isset($_GET['story_id'])) {
    try {
        $stmt = $conn->prepare('SELECT viewer_username, viewed_at FROM story_viewers WHERE story_id = :story_id');
        $stmt->execute([':story_id' => $_GET['story_id']]);
        $viewers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($viewers);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to fetch viewers: ' . $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>