<?php
// fiber_api.php
header('Content-Type: application/json');
require 'db.php'; // Unified DB connection

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    if ($action === 'list') {
        $stmt = $pdo->query("SELECT id, project_name FROM projects ORDER BY updated_at DESC");
        echo json_encode(['status' => 'success', 'projects' => $stmt->fetchAll()]);
    }
    elseif ($action === 'load') {
        $stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
        $stmt->execute([$input['id']]);
        $project = $stmt->fetch();
        if ($project) {
            $project['cable_data'] = json_decode($project['cable_data']); 
            echo json_encode(['status' => 'success', 'project' => $project]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Project not found']);
        }
    }
    elseif ($action === 'save') {
        $name = $input['name'];
        $data = json_encode($input['data']); 
        $id = $input['id'] ?? null;

        if ($id) {
            $stmt = $pdo->prepare("UPDATE projects SET project_name = ?, cable_data = ? WHERE id = ?");
            $stmt->execute([$name, $data, $id]);
            echo json_encode(['status' => 'success', 'id' => $id]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO projects (project_name, cable_data) VALUES (?, ?)");
            $stmt->execute([$name, $data]);
            echo json_encode(['status' => 'success', 'id' => $pdo->lastInsertId()]);
        }
    }
    elseif ($action === 'rename') {
        $stmt = $pdo->prepare("UPDATE projects SET project_name = ? WHERE id = ?");
        $stmt->execute([$input['name'], $input['id']]);
        echo json_encode(['status' => 'success']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>