<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$db_directory = "F:\\ratings_data";
$db_file = $db_directory . "\\stories.db";

if (!file_exists($db_directory)) {
    mkdir($db_directory, 0777, true);
}

try {
    $db = new PDO("sqlite:" . $db_file);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("PRAGMA foreign_keys = ON;");

    // Read directly from GET attributes stream
    $action = $_GET['action'] ?? '';
    $creator_name = trim($_GET['creator_name'] ?? '');
    $story_title = trim($_GET['story_title'] ?? '');

    if (empty($action) || empty($creator_name) || empty($story_title)) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Missing parameter variables']);
        exit;
    }

    $stmt = $db->prepare("INSERT OR IGNORE INTO creators (name) VALUES (?)");
    $stmt->execute([$creator_name]);
    $stmt = $db->prepare("SELECT id FROM creators WHERE name = ?");
    $stmt->execute([$creator_name]);
    $creator_id = $stmt->fetchColumn();




    if ($action === 'check_story') {
        $stmt = $db->prepare("SELECT id, title, created_at FROM stories WHERE creator_id = ? AND title = ? ORDER BY created_at DESC");
        $stmt->execute([$creator_id, $story_title]);
        $matches = $stmt->fetchAll(PDO::FETCH_ASSOC);
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'matches' => $matches]);
        exit;
    }

    if ($action === 'create_blank') {
        $stmt = $db->prepare("INSERT INTO stories (creator_id, title) VALUES (?, ?)");
        $stmt->execute([$creator_id, $story_title]);
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'story_id' => $db->lastInsertId()]);
        exit;
    }

    // Condition 3: Deep copy existing story data mapping along with its scene timeline
    if ($action === 'duplicate_story' && isset($_GET['source_story_id'])) {
        $source_id = intval($_GET['source_story_id']);
        
        $stmt = $db->prepare("INSERT INTO stories (creator_id, title) VALUES (?, ?)");
        $stmt->execute([$creator_id, $story_title]);
        $new_story_id = $db->lastInsertId();

        // 1. Duplicate all character matrices
        $stmt = $db->prepare("SELECT * FROM characters WHERE story_id = ?");
        $stmt->execute([$source_id]); $old_chars = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $id_mapping = [];
        $char_fields = ['first_name', 'last_name', 'nickname', 'gender_id', 'sexuality_id', 'species_id', 'age_id', 'hair_color_id', 'eye_color_id', 'height_id', 'weight_id'];
        $sql_insert = "INSERT INTO characters (story_id, " . implode(', ', $char_fields) . ") VALUES (?, " . implode(', ', array_fill(0, count($char_fields), '?')) . ")";
        $stmt_insert = $db->prepare($sql_insert);

        foreach ($old_chars as $char) {
            $params = [$new_story_id];
            foreach ($char_fields as $field) { $params[] = $char[$field]; }
            $stmt_insert->execute($params); $id_mapping[$char['id']] = $db->lastInsertId();
        }

        // 2. Duplicate background static character relationships
        $stmt = $db->prepare("SELECT * FROM character_relationships WHERE story_id = ?");
        $stmt->execute([$source_id]); $old_rels = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $stmt_rel = $db->prepare("INSERT INTO character_relationships (story_id, character_id_1, character_id_2, relationship_type_id) VALUES (?, ?, ?, ?)");
        foreach ($old_rels as $rel) {
            if (isset($id_mapping[$rel['character_id_1']], $id_mapping[$rel['character_id_2']])) {
                $stmt_rel->execute([$new_story_id, $id_mapping[$rel['character_id_1']], $id_mapping[$rel['character_id_2']], $rel['relationship_type_id']]);
            }
        }

        // 3. Duplicate chronological narrative Scenes
        $stmt = $db->prepare("SELECT * FROM scenes WHERE story_id = ? ORDER BY scene_number ASC");
        $stmt->execute([$source_id]); $old_scenes = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $stmt_scene = $db->prepare("INSERT INTO scenes (story_id, scene_number, title, location_id, sub_location, description) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt_sc_char = $db->prepare("INSERT INTO scene_characters (scene_id, character_id, character_status) VALUES (?, ?, ?)");
        $stmt_sc_shift = $db->prepare("INSERT INTO scene_relationship_shifts (scene_id, character_id_1, character_id_2, relationship_type_id) VALUES (?, ?, ?, ?)");

        foreach ($old_scenes as $scene) {
            $stmt_scene->execute([$new_story_id, $scene['scene_number'], $scene['title'], $scene['location_id'], $scene['sub_location'], $scene['description']]);
            $new_scene_id = $db->lastInsertId();

            // Duplicate characters attached to this specific scene
            $stmt = $db->prepare("SELECT * FROM scene_characters WHERE scene_id = ?");
            $stmt->execute([$scene['id']]); $scene_chars = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($scene_chars as $sc) {
                if (isset($id_mapping[$sc['character_id']])) {
                    $stmt_sc_char->execute([$new_scene_id, $id_mapping[$sc['character_id']], $sc['character_status']]);
                }
            }

            // Duplicate relationship shifts recorded in this scene
            $stmt = $db->prepare("SELECT * FROM scene_relationship_shifts WHERE scene_id = ?");
            $stmt->execute([$scene['id']]); $scene_shifts = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($scene_shifts as $ss) {
                if (isset($id_mapping[$ss['character_id_1']], $id_mapping[$ss['character_id_2']])) {
                    $stmt_sc_shift->execute([$new_scene_id, $id_mapping[$ss['character_id_1']], $id_mapping[$ss['character_id_2']], $ss['relationship_type_id']]);
                }
            }
        }

        header('Content-Type: application/json'); echo json_encode(['status' => 'success', 'story_id' => $new_story_id]); exit;
    }

} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    exit;
}

    

api