<?php
// submit-story.php
// Free text-only story submission for Barriers categories.
// Available to ALL registered users (Community+ level).
// No token cost. Stories require admin approval.

session_start();
require_once 'config.php';

header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

try {
    // 1. Auth check — any registered user
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'You must be logged in to share a story.']);
        exit;
    }

    $user_id = intval($_SESSION['user_id']);

    // 2. Validate inputs
    $title = trim($_POST['story_title'] ?? '');
    $story = trim($_POST['story_content'] ?? '');
    $county = trim($_POST['story_county'] ?? '');
    $barrier_id = intval($_POST['barrier_category_id'] ?? 0);

    if (empty($title) || mb_strlen($title) < 5) {
        echo json_encode(['status' => 'error', 'message' => 'Please provide a title (at least 5 characters).']);
        exit;
    }

    $clean_story = mb_strlen(trim(strip_tags($story)));
    if ($clean_story < 20) {
        echo json_encode(['status' => 'error', 'message' => 'Your story must be at least 20 characters long.']);
        exit;
    }

    if ($clean_story > 10000) {
        echo json_encode(['status' => 'error', 'message' => 'Story is too long. Maximum 10,000 characters.']);
        exit;
    }

    if ($barrier_id < 1 || $barrier_id > 9) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid barrier category.']);
        exit;
    }

    // Rate limit: max 3 pending free stories per user
    $limit_stmt = $conn->prepare("SELECT COUNT(*) as cnt FROM submissions WHERE user_id = ? AND is_free_story = 1 AND status = 'pending'");
    $limit_stmt->bind_param("i", $user_id);
    $limit_stmt->execute();
    $pending_count = $limit_stmt->get_result()->fetch_assoc()['cnt'];
    $limit_stmt->close();

    if ($pending_count >= 3) {
        echo json_encode(['status' => 'error', 'message' => 'You have 3 pending stories awaiting approval. Please wait for them to be reviewed before submitting more.']);
        exit;
    }

    // 3. Get user info
    $u_stmt = $conn->prepare("SELECT org_name, email FROM users WHERE id = ?");
    $u_stmt->bind_param("i", $user_id);
    $u_stmt->execute();
    $user_data = $u_stmt->get_result()->fetch_assoc();
    $u_stmt->close();

    if (!$user_data) {
        echo json_encode(['status' => 'error', 'message' => 'User account not found.']);
        exit;
    }

    // 4. Sanitize
    $title = htmlspecialchars($title, ENT_QUOTES | ENT_HTML5);
    $county = htmlspecialchars($county, ENT_QUOTES | ENT_HTML5);
    // Story is rich-text HTML from Quill — stored as-is (same as paid submissions)

    $thematic_json = json_encode([$barrier_id]);
    $empty_json = json_encode([]);

    // 5. Insert
    $ins = $conn->prepare(
        "INSERT INTO submissions
            (org_name, title, contact_person, email, mobile, story, description, role, service_chains, enabling_pillars, thematic_categories, county, status, is_verified, category_id, user_id, last_token_cost, is_free_story)
         VALUES (?, ?, ?, ?, 'N/A', ?, '', 'Individual', ?, ?, ?, ?, 'pending', 0, 0, ?, 0, 1)"
    );

    if (!$ins) {
        throw new Exception("DB Error: " . $conn->error);
    }

    $contact = $user_data['org_name'] ?: 'Community Member';
    $ins->bind_param(
        "sssssssssi",
        $user_data['org_name'],
        $title,
        $contact,
        $user_data['email'],
        $story,
        $empty_json,       // service_chains
        $empty_json,       // enabling_pillars
        $thematic_json,    // thematic_categories
        $county,
        $user_id
    );

    if (!$ins->execute()) {
        throw new Exception("Insert failed: " . $ins->error);
    }

    echo json_encode([
        'status' => 'success',
        'message' => 'Your story has been submitted and is pending admin review. Thank you for sharing!'
    ]);

} catch (Exception $e) {
    error_log("submit-story.php error: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
}
